repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
videlanicolas/puppet-ceph
lib/puppet/provider/ceph_config/ini_setting.rb
# Copyright (C) <NAME> <<EMAIL>> # # 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. # # Author: <NAME> <<EMAIL>> # Author: <NAME> <xarses> Puppet::Type.type(:ceph_config).provide( :ini_setting, :parent => Puppet::Type.type(:ini_setting).provider(:ruby) ) do def section resource[:name].split('/', 2).first end def setting resource[:name].split('/', 2).last end def separator ' = ' end def self.file_path '/etc/ceph/ceph.conf' end # required to be able to hack the path in unit tests # also required if a user wants to otherwise overwrite the default file_path # Note: purge will not work on over-ridden file_path def file_path if not resource[:path] self.class.file_path else resource[:path] end end end
videlanicolas/puppet-ceph
spec/defines/ceph_osd_spec.rb
# # Copyright (C) 2014 Cloudwatt <<EMAIL>> # # 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. # # Author: <NAME> <<EMAIL>> # Author: <NAME> <<EMAIL>> # require 'spec_helper' describe 'ceph::osd' do shared_examples 'ceph osd' do describe "with default params" do let :title do 'vg_test/lv_test' end it { should contain_exec('ceph-osd-prepare-vg_test/lv_test').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ $(echo vg_test/lv_test|cut -c 1) = '/' ]; then disk=vg_test/lv_test else # If data is vg/lv, block device is /dev/vg/lv disk=/dev/vg_test/lv_test fi if ! test -b \$disk ; then # Since nautilus, only block devices or lvm logical volumes can be used for OSDs exit 1 fi ceph-volume lvm prepare --cluster ceph --data vg_test/lv_test ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex ceph-volume lvm list vg_test/lv_test ", 'logoutput' => true ) } it { should contain_exec('ceph-osd-activate-vg_test/lv_test').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ $(echo vg_test/lv_test|cut -c 1) = '/' ]; then disk=vg_test/lv_test else # If data is vg/lv, block device is /dev/vg/lv disk=/dev/vg_test/lv_test fi if ! test -b \$disk ; then # Since nautilus, only block devices or lvm logical volumes can be used for OSDs exit 1 fi id=$(ceph-volume lvm list vg_test/lv_test | grep 'osd id'|awk -F 'osd id' '{print \$2}'|tr -d ' ') fsid=$(ceph-volume lvm list vg_test/lv_test | grep 'osd fsid'|awk -F 'osd fsid' '{print \$2}'|tr -d ' ') ceph-volume lvm activate \$id \$fsid ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex id=$(ceph-volume lvm list vg_test/lv_test | grep 'osd id'|awk -F 'osd id' '{print \$2}'|tr -d ' ') ps -fCceph-osd|grep \"\\--id \$id \" ", 'logoutput' => true ) } end describe "with bluestore params" do let :title do 'vg_test/lv_test' end let :params do { :cluster => 'testcluster', :journal => '/srv/journal', :fsid => 'f39ace04-f967-4c3d-9fd2-32af2d2d2cd5', :store_type => 'bluestore', :bluestore_wal => 'vg_test/lv_wal', :bluestore_db => 'vg_test/lv_db', } end it { should contain_exec('ceph-osd-check-fsid-mismatch-vg_test/lv_test').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex exit 1 ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ -z $(ceph-volume lvm list vg_test/lv_test |grep 'cluster fsid' | awk -F'fsid' '{print \$2}'|tr -d ' ') ]; then exit 0 fi test f39ace04-f967-4c3d-9fd2-32af2d2d2cd5 = $(ceph-volume lvm list vg_test/lv_test |grep 'cluster fsid' | awk -F'fsid' '{print \$2}'|tr -d ' ') ", 'logoutput' => true ) } it { should contain_exec('ceph-osd-prepare-vg_test/lv_test').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ $(echo vg_test/lv_test|cut -c 1) = '/' ]; then disk=vg_test/lv_test else # If data is vg/lv, block device is /dev/vg/lv disk=/dev/vg_test/lv_test fi if ! test -b \$disk ; then # Since nautilus, only block devices or lvm logical volumes can be used for OSDs exit 1 fi ceph-volume lvm prepare --bluestore --cluster testcluster --cluster-fsid f39ace04-f967-4c3d-9fd2-32af2d2d2cd5 --data vg_test/lv_test --block.wal vg_test/lv_wal --block.db vg_test/lv_db ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex ceph-volume lvm list vg_test/lv_test ", 'logoutput' => true ) } it { should contain_exec('ceph-osd-activate-vg_test/lv_test').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ $(echo vg_test/lv_test|cut -c 1) = '/' ]; then disk=vg_test/lv_test else # If data is vg/lv, block device is /dev/vg/lv disk=/dev/vg_test/lv_test fi if ! test -b \$disk ; then # Since nautilus, only block devices or lvm logical volumes can be used for OSDs exit 1 fi id=$(ceph-volume lvm list vg_test/lv_test | grep 'osd id'|awk -F 'osd id' '{print \$2}'|tr -d ' ') fsid=$(ceph-volume lvm list vg_test/lv_test | grep 'osd fsid'|awk -F 'osd fsid' '{print \$2}'|tr -d ' ') ceph-volume lvm activate \$id \$fsid ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex id=$(ceph-volume lvm list vg_test/lv_test | grep 'osd id'|awk -F 'osd id' '{print \$2}'|tr -d ' ') ps -fCceph-osd|grep \"\\--id \$id \" ", 'logoutput' => true ) } end describe "with dmcrypt enabled" do let :title do '/dev/sdc' end let :params do { :dmcrypt => true, } end it { is_expected.to contain_exec('ceph-osd-prepare-/dev/sdc').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ $(echo /dev/sdc|cut -c 1) = '/' ]; then disk=/dev/sdc else # If data is vg/lv, block device is /dev/vg/lv disk=/dev//dev/sdc fi if ! test -b \$disk ; then # Since nautilus, only block devices or lvm logical volumes can be used for OSDs exit 1 fi ceph-volume lvm prepare --cluster ceph --dmcrypt --dmcrypt-key-dir '/etc/ceph/dmcrypt-keys' --data /dev/sdc ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex ceph-volume lvm list /dev/sdc ", 'logoutput' => true ) } it { is_expected.to contain_exec('ceph-osd-activate-/dev/sdc').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ $(echo /dev/sdc|cut -c 1) = '/' ]; then disk=/dev/sdc else # If data is vg/lv, block device is /dev/vg/lv disk=/dev//dev/sdc fi if ! test -b \$disk ; then # Since nautilus, only block devices or lvm logical volumes can be used for OSDs exit 1 fi id=$(ceph-volume lvm list /dev/sdc | grep 'osd id'|awk -F 'osd id' '{print \$2}'|tr -d ' ') fsid=$(ceph-volume lvm list /dev/sdc | grep 'osd fsid'|awk -F 'osd fsid' '{print \$2}'|tr -d ' ') ceph-volume lvm activate \$id \$fsid ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex id=$(ceph-volume lvm list /dev/sdc | grep 'osd id'|awk -F 'osd id' '{print \$2}'|tr -d ' ') ps -fCceph-osd|grep \"\\--id \$id \" ", 'logoutput' => true ) } end describe "with dmcrypt custom keydir" do let :title do '/dev/sdc' end let :params do { :dmcrypt => true, :dmcrypt_key_dir => '/srv/ceph/keys', } end it { is_expected.to contain_exec('ceph-osd-prepare-/dev/sdc').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ $(echo /dev/sdc|cut -c 1) = '/' ]; then disk=/dev/sdc else # If data is vg/lv, block device is /dev/vg/lv disk=/dev//dev/sdc fi if ! test -b \$disk ; then # Since nautilus, only block devices or lvm logical volumes can be used for OSDs exit 1 fi ceph-volume lvm prepare --cluster ceph --dmcrypt --dmcrypt-key-dir '/srv/ceph/keys' --data /dev/sdc ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex ceph-volume lvm list /dev/sdc ", 'logoutput' => true ) } it { is_expected.to contain_exec('ceph-osd-activate-/dev/sdc').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ $(echo /dev/sdc|cut -c 1) = '/' ]; then disk=/dev/sdc else # If data is vg/lv, block device is /dev/vg/lv disk=/dev//dev/sdc fi if ! test -b \$disk ; then # Since nautilus, only block devices or lvm logical volumes can be used for OSDs exit 1 fi id=$(ceph-volume lvm list /dev/sdc | grep 'osd id'|awk -F 'osd id' '{print \$2}'|tr -d ' ') fsid=$(ceph-volume lvm list /dev/sdc | grep 'osd fsid'|awk -F 'osd fsid' '{print \$2}'|tr -d ' ') ceph-volume lvm activate \$id \$fsid ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex id=$(ceph-volume lvm list /dev/sdc | grep 'osd id'|awk -F 'osd id' '{print \$2}'|tr -d ' ') ps -fCceph-osd|grep \"\\--id \$id \" ", 'logoutput' => true ) } end describe "with custom params" do let :title do 'vg_test/lv_test' end let :params do { :cluster => 'testcluster', :journal => 'vg_test/lv_journal', :fsid => 'f39ace04-f967-4c3d-9fd2-32af2d2d2cd5', :store_type => 'filestore' } end it { should contain_exec('ceph-osd-check-fsid-mismatch-vg_test/lv_test').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex exit 1 ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ -z $(ceph-volume lvm list vg_test/lv_test |grep 'cluster fsid' | awk -F'fsid' '{print \$2}'|tr -d ' ') ]; then exit 0 fi test f39ace04-f967-4c3d-9fd2-32af2d2d2cd5 = $(ceph-volume lvm list vg_test/lv_test |grep 'cluster fsid' | awk -F'fsid' '{print \$2}'|tr -d ' ') ", 'logoutput' => true ) } it { should contain_exec('ceph-osd-prepare-vg_test/lv_test').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ $(echo vg_test/lv_test|cut -c 1) = '/' ]; then disk=vg_test/lv_test else # If data is vg/lv, block device is /dev/vg/lv disk=/dev/vg_test/lv_test fi if ! test -b \$disk ; then # Since nautilus, only block devices or lvm logical volumes can be used for OSDs exit 1 fi ceph-volume lvm prepare --filestore --cluster testcluster --cluster-fsid f39ace04-f967-4c3d-9fd2-32af2d2d2cd5 --data vg_test/lv_test --journal vg_test/lv_journal ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex ceph-volume lvm list vg_test/lv_test ", 'logoutput' => true ) } it { should contain_exec('ceph-osd-activate-vg_test/lv_test').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ $(echo vg_test/lv_test|cut -c 1) = '/' ]; then disk=vg_test/lv_test else # If data is vg/lv, block device is /dev/vg/lv disk=/dev/vg_test/lv_test fi if ! test -b \$disk ; then # Since nautilus, only block devices or lvm logical volumes can be used for OSDs exit 1 fi id=$(ceph-volume lvm list vg_test/lv_test | grep 'osd id'|awk -F 'osd id' '{print \$2}'|tr -d ' ') fsid=$(ceph-volume lvm list vg_test/lv_test | grep 'osd fsid'|awk -F 'osd fsid' '{print \$2}'|tr -d ' ') ceph-volume lvm activate \$id \$fsid ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex id=$(ceph-volume lvm list vg_test/lv_test | grep 'osd id'|awk -F 'osd id' '{print \$2}'|tr -d ' ') ps -fCceph-osd|grep \"\\--id \$id \" ", 'logoutput' => true ) } end describe "with NVMe param" do let :title do '/dev/nvme0n1' end it { should contain_exec('ceph-osd-prepare-/dev/nvme0n1').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ $(echo /dev/nvme0n1|cut -c 1) = '/' ]; then disk=/dev/nvme0n1 else # If data is vg/lv, block device is /dev/vg/lv disk=/dev//dev/nvme0n1 fi if ! test -b \$disk ; then # Since nautilus, only block devices or lvm logical volumes can be used for OSDs exit 1 fi ceph-volume lvm prepare --cluster ceph --data /dev/nvme0n1 ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex ceph-volume lvm list /dev/nvme0n1 ", 'logoutput' => true ) } it { should contain_exec('ceph-osd-activate-/dev/nvme0n1').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ $(echo /dev/nvme0n1|cut -c 1) = '/' ]; then disk=/dev/nvme0n1 else # If data is vg/lv, block device is /dev/vg/lv disk=/dev//dev/nvme0n1 fi if ! test -b \$disk ; then # Since nautilus, only block devices or lvm logical volumes can be used for OSDs exit 1 fi id=$(ceph-volume lvm list /dev/nvme0n1 | grep 'osd id'|awk -F 'osd id' '{print \$2}'|tr -d ' ') fsid=$(ceph-volume lvm list /dev/nvme0n1 | grep 'osd fsid'|awk -F 'osd fsid' '{print \$2}'|tr -d ' ') ceph-volume lvm activate \$id \$fsid ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex id=$(ceph-volume lvm list /dev/nvme0n1 | grep 'osd id'|awk -F 'osd id' '{print \$2}'|tr -d ' ') ps -fCceph-osd|grep \"\\--id \$id \" ", 'logoutput' => true ) } end describe "with cciss param" do let :title do '/dev/cciss/c0d0' end it { should contain_exec('ceph-osd-prepare-/dev/cciss/c0d0').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ $(echo /dev/cciss/c0d0|cut -c 1) = '/' ]; then disk=/dev/cciss/c0d0 else # If data is vg/lv, block device is /dev/vg/lv disk=/dev//dev/cciss/c0d0 fi if ! test -b \$disk ; then # Since nautilus, only block devices or lvm logical volumes can be used for OSDs exit 1 fi ceph-volume lvm prepare --cluster ceph --data /dev/cciss/c0d0 ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex ceph-volume lvm list /dev/cciss/c0d0 ", 'logoutput' => true ) } it { should contain_exec('ceph-osd-activate-/dev/cciss/c0d0').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex if [ $(echo /dev/cciss/c0d0|cut -c 1) = '/' ]; then disk=/dev/cciss/c0d0 else # If data is vg/lv, block device is /dev/vg/lv disk=/dev//dev/cciss/c0d0 fi if ! test -b \$disk ; then # Since nautilus, only block devices or lvm logical volumes can be used for OSDs exit 1 fi id=$(ceph-volume lvm list /dev/cciss/c0d0 | grep 'osd id'|awk -F 'osd id' '{print \$2}'|tr -d ' ') fsid=$(ceph-volume lvm list /dev/cciss/c0d0 | grep 'osd fsid'|awk -F 'osd fsid' '{print \$2}'|tr -d ' ') ceph-volume lvm activate \$id \$fsid ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -ex id=$(ceph-volume lvm list /dev/cciss/c0d0 | grep 'osd id'|awk -F 'osd id' '{print \$2}'|tr -d ' ') ps -fCceph-osd|grep \"\\--id \$id \" ", 'logoutput' => true ) } end describe "with ensure absent" do let :title do 'vg_test/lv_test' end let :params do { :ensure => 'absent', } end it { should contain_exec('remove-osd-vg_test/lv_test').with( 'command' => "/bin/true # comment to satisfy puppet syntax requirements set -ex id=$(ceph-volume lvm list vg_test/lv_test | grep 'osd id'|awk -F 'osd id' '{print \$2}'|tr -d ' ') if [ \"\$id\" ] ; then ceph --cluster ceph osd out osd.\$id stop ceph-osd cluster=ceph id=\$id || true service ceph stop osd.\$id || true systemctl stop ceph-osd@\$id || true ceph --cluster ceph osd crush remove osd.\$id ceph --cluster ceph auth del osd.\$id ceph --cluster ceph osd rm \$id rm -fr /var/lib/ceph/osd/ceph-\$id/* umount /var/lib/ceph/osd/ceph-\$id || true rm -fr /var/lib/ceph/osd/ceph-\$id ceph-volume lvm zap vg_test/lv_test fi ", 'unless' => "/bin/true # comment to satisfy puppet syntax requirements set -x ceph-volume lvm list vg_test/lv_test if [ \$? -eq 0 ]; then exit 1 else exit 0 fi ", 'logoutput' => true ) } end describe "with ensure set to bad value" do let :title do '/srv' end let :params do { :ensure => 'badvalue', } end it { should raise_error(Puppet::Error, /Ensure on OSD must be either present or absent/) } end end on_supported_os({ :supported_os => OSDefaults.get_supported_os }).each do |os,facts| context "on #{os}" do let (:facts) do facts.merge!(OSDefaults.get_facts()) end it_behaves_like 'ceph osd' end end end
BenMorganIO/astrometry
lib/astrometry.rb
%w(version image).each do |file| require "astrometry/#{file}" end module Astrometry end
BenMorganIO/astrometry
lib/astrometry/image.rb
module Astrometry class Image # @param input [String] The input is the file that is to be parsed by astrometry. attr_accessor :input # @param file [String] The file that is to be parsed. # @return [String] def initialize(file) @input = file end # Executes the astrometry `solve-field` command and begins parsing your # image. # @return [TrueClass] if the image is successfully parsed. # @return [NilClass] if the image if unsuccessfully parsed. def solve_field system "solve-field #{file}" end end end
BenMorganIO/astrometry
lib/astrometry/version.rb
<gh_stars>0 module Astrometry # @return [String] VERSION = '0.0.1' end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/screenshot_steps.rb
<gh_stars>10-100 module CalSmokeApp module Screenshots require 'fileutils' # SCREENSHOT_PATH for this project is set in the config/cucumber.yml # # The value is ./screenshots # # If the ./screenshots directory does not exist, the erb in the # config/cucumber.yml will create it. # # If the SCREENSHOT_PATH is undefined, screenshots will appear # in the ./ directory. # # http://calabashapi.xamarin.com/ios/file.ENVIRONMENT_VARIABLES.html#label-SCREENSHOT_PATH # # On the Xamarin Test Cloud, we should not rely on SCREENSHOT_PATH # to be defined or to be set to directory we can write to. def screenshots_subdirectory if RunLoop::Environment.xtc? screenshot_dir = './screenshots' else screenshot_dir = ENV['SCREENSHOT_PATH'] if !screenshot_dir screenshot_dir = "./screenshots" end end unless File.exist?(screenshot_dir) FileUtils.mkdir_p(screenshot_dir) end path = File.join(screenshot_dir, 'scenario-screenshots') # Compensate for a bad behavior in Calabash. # :prefix needs to have a trailing / "#{path}/" end # By default, Calabash appends a number to the end of the screenshot # name. There is no way to override this behavior. def un_numbered_screenshot(name, dir) res = http({:method => :get, :path => 'screenshot'}) if File.extname(name).downcase == '.png' path = File.join(dir, name) else path = File.join(dir, "#{name}.png") end File.open(path, 'wb') do |f| f.write res end path end end end World(CalSmokeApp::Screenshots) And(/^I have cleared existing screenshots for this feature$/) do path = screenshots_subdirectory if File.exist?(path) FileUtils.rm_rf(path) end end And(/^the scenario\-screenshots subdirectory exists$/) do path = screenshots_subdirectory unless File.exist?(path) FileUtils.mkdir_p(path) end end When(/^I take a screenshot with the default screenshot method$/) do path = screenshots_subdirectory screenshot({:prefix => path, :name => 'my-screenshot'}) end Then(/^the screenshot will have a number appended to the name$/) do dir = screenshots_subdirectory begin count = Calabash::Cucumber::FailureHelpers.class_variable_get(:@@screenshot_count) - 1 rescue NameError => _ raise "Class variable @@screenshot_count is undefined.\nHas a screenshot been taken yet?" end path = File.join(dir, "my-screenshot_#{count}.png") expect(File.exists?(path)).to be == true end When(/^I take a screenshot with my un\-numbered screenshot method$/) do dir = screenshots_subdirectory un_numbered_screenshot('my-screenshot', dir) end Then(/^the screenshot will not have a number appended to the name$/) do dir = screenshots_subdirectory path = File.join(dir, 'my-screenshot.png') expect(File.exists?(path)).to be == true end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/shared_steps.rb
Given(/^I see the (controls|gestures|scrolls|special|date picker) tab$/) do |tab| wait_for_element_exists("tabBarButton") case tab when 'controls' index = 0 when 'gestures' index = 1 when 'scrolls' index = 2 when 'special' index = 3 when 'date picker' index = 4 end touch("tabBarButton index:#{index}") expected_view = "#{tab} page" wait_for_element_exists("view marked:'#{expected_view}'") end Then(/^I type "([^"]*)"$/) do |text_to_type| query = 'UITextField' options = wait_options(query) wait_for_element_exists(query, options) touch(query) wait_for_keyboard keyboard_enter_text text_to_type end When(/^I touch the back button$/) do query = "view marked:'Back'" options = wait_options('Navbar back button') wait_for_element_exists(query, options) touch(query) wait_for_none_animating end Given(/^the app has launched$/) do wait_for_elements_exist('tabBarButton') end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/support/env.rb
# Do not use Calabash pre-defined steps. require 'calabash-cucumber/wait_helpers' require 'calabash-cucumber/operations' World(Calabash::Cucumber::Operations) require 'rspec' require 'chronic' # Pry is not allowed on the Xamarin Test Cloud. This will force a validation # error if you mistakenly submit a binding.pry to the Test Cloud. if !ENV['XAMARIN_TEST_CLOUD'] require 'pry' Pry.config.history.file = '.pry-history' require 'pry-nav' end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/support/dylib.rb
module CalSmoke module Dylib @@dylib = nil def self.dylib @@dylib ||= lambda { git_path = File.expand_path('~/git/calabash/calabash-ios-server/calabash-dylibs/libCalabashDynSim.dylib') if File.exist? git_path git_path else File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'libCalabashDynSim.dylib')) end }.call end end end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/support/list_tags.rb
<gh_stars>10-100 =begin Copyright (c) 2012, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name <NAME> nor the names of contributors to this software may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =end require 'cucumber/formatter/console' require 'cucumber/formatter/io' module Cucumber module Formatter class ListTags include Io include Console def initialize(step_mother, path_or_io, options) @io = ensure_io(path_or_io, "list_tags") @all_tags = [] end def tag_name(tag_name) @all_tags << tag_name end def after_features(features) @all_tags.uniq.sort.each {|tag| @io.puts tag} end end end end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/flash_steps.rb
<gh_stars>10-100 Then(/^I can flash the buttons$/) do views = flash('UIButton') expect(views.length).to be == 3 end And(/^I can flash the labels in the tab bar$/) do views = flash("UITabBar descendant UITabBarButton descendant label") expect(views.length).to be == 5 end When(/^the flash query matches no views$/) do @flash_results = flash("view marked:'some view that does not exist'") end Then(/^flash returns an empty array$/) do expect(@flash_results.empty?).to be == true end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/sheets_steps.rb
module CalSmoke module Sheets def sheet_query if ios7? 'UIActionSheet' else "view:'_UIAlertControllerView'" end end def sheet_exists?(sheet_title=nil) if sheet_title.nil? !query(sheet_query).empty? else !query("#{sheet_query} descendant label marked:'#{sheet_title}'").empty? end end def wait_for_sheet timeout = 30 message = "Waited #{timeout} seconds for a sheet to appear" options = {timeout: timeout, timeout_message: message} wait_for(options) do sheet_exists? end end def wait_for_sheet_with_title(sheet_title) timeout = 30 message = "Waited #{timeout} seconds for a sheet with title '#{sheet_title}' to appear" options = {timeout: timeout, timeout_message: message} wait_for(options) do sheet_exists?(sheet_title) end end def tap_sheet_button(button_title) wait_for_sheet if ios7? query = "UIActionSheet child button child label marked:'#{button_title}'" else query = "view:'_UIAlertControllerActionView' marked:'#{button_title}'" end touch(query) end end end World(CalSmoke::Sheets) When(/^I touch the show sheet button$/) do wait_for_element_exists("view marked:'show sheet'") touch("view marked:'show sheet'") end Then(/^I see a sheet$/) do wait_for_sheet end Then(/^I see the "([^"]*)" sheet$/) do |sheet_title| wait_for_sheet_with_title(sheet_title) end Then(/^I can dismiss the sheet with the Cancel button$/) do tap_sheet_button('Cancel') end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/keyboard_steps.rb
<filename>CalSmokeApp/features/step_definitions/keyboard_steps.rb module CalSmokeApp module Keyboard end end World(CalSmokeApp::Keyboard)
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/selector_steps.rb
<filename>CalSmokeApp/features/step_definitions/selector_steps.rb module CalSmoke module Selectors def call_selector(array_or_symbol) query("view marked:'controls page'", array_or_symbol) end def returned_from_selector(array_or_symbol) result = call_selector(array_or_symbol) if result.empty? raise "Expected call to '#{array_or_symbol}' to return at least one value" end result.first end def expect_selector_truthy(array_or_symbol) res = call_selector(array_or_symbol) expect(res.empty?).to be_falsey expect(res.first).to be == 1 end end end World(CalSmoke::Selectors) When(/^I call an unknown selector on a view$/) do result = query("view marked:'controls page'", :unknownSelector) if result.empty? raise "Expected a query match for \"view marked:'controls page'\"" end @received_back_from_selector = result.first end Then(/^I expect to receive back "(.*?)"$/) do |expected| expect(@received_back_from_selector).to be == expected end When(/^I call a method that references the matched view$/) do args = [{stringFromMethodWithSelf:'__self__'}] @received_back_from_selector = returned_from_selector(args) end Then(/^the view alarm property is off$/) do result = query("view marked:'controls page'", :alarm, :isOn) if result.empty? raise "Expected query match for \"view marked:'controls page'\"" end expect(result.first).to be == 0 end And(/^I can turn the alarm on$/) do result = query("view marked:'controls page'", :alarm, [{setIsOn:1}]) if result.empty? raise "Expected query match for \"view marked:'controls page'\"" end result = query("view marked:'controls page'", :alarm, :isOn) if result.empty? raise "Expected query match for \"view marked:'controls page'\"" end expect(result.first).to be == 1 end Then(/^I call selector with pointer argument$/) do arg = [{takesPointer:'a string'}] expect_selector_truthy(arg) end Then(/^I call selector with (unsigned int|int) argument$/) do |signed| if signed == 'int' arg = [{takesInt:-1}]; else arg = [{takesUnsignedInt:1}]; end expect_selector_truthy(arg) end Then(/^I call selector with (unsigned short|short) argument$/) do |signed| if signed == 'short' arg = [{takesShort:-1}]; else arg = [{takesUnsignedShort:1}]; end expect_selector_truthy(arg) end Then(/^I call selector with (unsigned long|long) argument$/) do |signed| if signed == 'long' arg = [{takesLong:-1}]; else arg = [{takesUnsignedLong:1}]; end expect_selector_truthy(arg) end Then(/^I call selector with (unsigned long long|long long) argument$/) do |signed| if signed == 'long long' arg = [{takesLongLong:-1}]; else arg = [{takesUnsignedLongLong:1}]; end expect_selector_truthy(arg) end Then(/^I call selector with float argument$/) do arg = [{takesFloat:0.1}] expect_selector_truthy(arg) end Then(/^I call selector with (long double|double) argument$/) do |signed| if signed == 'double' arg = [{takesDouble:0.1}]; else arg = [{takesLongDouble:Math::PI}]; end expect_selector_truthy(arg) end Then(/^I call selector with (unsigned char|char) argument$/) do |signed| if signed == 'char' # Passed a string arg = [{takesChar:'a'}] expect_selector_truthy(arg) # Passed a number arg = [{takesChar:-22}] expect_selector_truthy(arg) else # Passed a string arg = [{takesUnsignedChar:'a'}] expect_selector_truthy(arg) # Passed a number arg = [{takesUnsignedChar:22}] expect_selector_truthy(arg) end end Then(/^I call selector with BOOL argument$/) do # true/false arg = [{takesBOOL:true}] expect_selector_truthy(arg) arg = [{takesBOOL:false}] expect_selector_truthy(arg) # YES/NO arg = [{takesBOOL:1}] expect_selector_truthy(arg) arg = [{takesBOOL:0}] expect_selector_truthy(arg) end Then(/I call selector with c string argument$/) do arg = [{takesCString:'a c string'}] expect_selector_truthy(arg) end Then(/I call selector with (point|rect) argument$/) do |type| if type == 'point' point = {x:5.0, y:10.2} arg = [{takesPoint:point}] else rect = {x:5, y:10, width:44, height:44} arg = [{takesRect:rect}] end expect_selector_truthy(arg) end Then(/^I call a selector that returns void$/) do #expect(returned_from_selector(:returnsVoid)).to be == '<VOID>' expect(returned_from_selector(:returnsVoid)).to be == nil end Then(/^I call a selector that returns a pointer$/) do expect(returned_from_selector(:returnsPointer)).to be == 'a pointer' end Then(/^I call a selector that returns an? (unsigned char|char)$/) do |signed| if signed[/unsigned/, 0] result = returned_from_selector(:returnsUnsignedChar) expected = 97 # ASCII code for 'a' else result = returned_from_selector(:returnsChar) expected = -22 end expect(result).to be == expected end Then(/^I call a selector that returns a c string$/) do expect(returned_from_selector(:returnsCString)).to be == 'c string' end Then(/^I call a selector that returns a (BOOL|bool)$/) do |boolean| if boolean == 'BOOL' result = returned_from_selector(:returnsBOOL) else result = returned_from_selector(:returnsBool) end expect(result).to be == 1 end Then(/^I call a selector that returns an? (unsigned int|int)$/) do |signed| if signed[/unsigned/, 0] result = returned_from_selector(:returnsUnsignedInt) expected = 3 else result = returned_from_selector(:returnsInt) expected = -3 end expect(result).to be == expected end Then(/^I call a selector that returns an? (unsigned short|short)$/) do |signed| if signed[/unsigned/, 0] result = returned_from_selector(:returnsUnsignedShort) expected = 2 else result = returned_from_selector(:returnsShort) expected = -2 end expect(result).to be == expected end Then(/^I call a selector that returns a (long double|double)$/) do |double| if double[/long/, 0] result = returned_from_selector(:returnsLongDouble) expected = 0.55 else result = returned_from_selector(:returnsDouble) expected = 0.5 end expect(result).to be == expected end Then(/^I call a selector that returns a float$/) do expect(returned_from_selector(:returnsFloat)).to be == 3.14 end Then(/^I call a selector that returns an? (unsigned long|long)$/) do |signed| if signed[/unsigned/, 0] result = returned_from_selector(:returnsUnsignedLong) expected = 4 else result = returned_from_selector(:returnsLong) expected = -4 end expect(result).to be == expected end Then(/^I call a selector that returns an? (unsigned long long|long long)$/) do |signed| if signed[/unsigned/, 0] result = returned_from_selector(:returnsUnsignedLongLong) expected = 5 else result = returned_from_selector(:returnsLongLong) expected = -5 end expect(result).to be == expected end Then(/^I call a selector that returns a point$/) do hash = {'X' => 0, 'Y' => 0, 'description' => 'NSPoint: {0, 0}'} expect(returned_from_selector(:returnsPoint)).to be == hash end Then(/^I call a selector that returns a rect$/) do hash = {"Width" => 0, "Height" => 0, "X" => 0, "Y" => 0, "description" => "NSRect: {{0, 0}, {0, 0}}"} expect(returned_from_selector(:returnsRect)).to be == hash end Then(/^I call a selector that returns a CalSmokeAlarm struct$/) do expect(returned_from_selector(:returnSmokeAlarm)).to be_a_kind_of String end Then(/^I call a selector on a view that has 3 arguments$/) do args = ['a', 'b', 'c'] array = [{selectorWithArg:args[0]}, {arg:args[1]}, {arg:args[2]}] result = returned_from_selector(array) ap result #expect(result).to be == args end Then(/^I make a chained call to a selector with 3 arguments$/) do args = ['a', 'b', 'c'] array = [{selectorWithArg:args[0]}, {arg:args[1]}, {arg:args[2]}] result = query("view marked:'controls page'", :alarm, array) ap result #expect(result).to be == args end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/server_log_level_steps.rb
<filename>CalSmokeApp/features/step_definitions/server_log_level_steps.rb Then(/^I can ask the server for its log level$/) do expect(server_log_level).to be == 'info' end And(/^I set the server log level to debug$/) do expect(set_server_log_level('debug')).to be == 'debug' end Then(/^the server log level should be debug$/) do expect(server_log_level).to be == 'debug' end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/issue_246_screenshot_steps.rb
<reponame>MortenGregersen/ios-smoke-test-app module CalSmokeApp module ScreenshotEmbed def screenshot_count screenshot_dir = ENV["SCREENSHOT_PATH"] if !screenshot_dir screenshot_dir = "./screenshots" end unless File.exist?(screenshot_dir) FileUtils.mkdir_p(screenshot_dir) end Dir.glob("#{screenshot_dir}/*.png").count end def log_screenshot_context(kontext, e) $stdout.puts " #{kontext} #{e.class} #{e.message}" $stdout.flush end def expect_screenshot_count(expected) if Calabash::Cucumber::Environment.xtc? # Skip this test on the XTC. else expect(screenshot_count).to be == expected end end end end World(CalSmokeApp::ScreenshotEmbed) When(/^I use screenshot_and_raise in the context of cucumber$/) do last_count = screenshot_count begin screenshot_and_raise 'Hey!' rescue => e @screenshot_and_raise_error = e log_screenshot_context("Cucumber", e) expect_screenshot_count(last_count + 1) end end When(/I screenshot_and_raise in a page that does not inherit from IBase$/) do last_count = screenshot_count begin NotPOM::HomePage.new.my_buggy_method rescue => e log_screenshot_context("NotPOM", e) @screenshot_and_raise_error = e expect_screenshot_count(last_count + 1) end end When(/I screenshot_and_raise in a page that does inherit from IBase$/) do last_count = screenshot_count begin POM::HomePage.new(self).my_buggy_method rescue => e log_screenshot_context("POM", e) @screenshot_and_raise_error = e expect_screenshot_count(last_count + 1) end end Then(/^I should get a runtime error$/) do if @screenshot_and_raise_error.nil? raise 'Expected the previous step to raise an error' end expect(@screenshot_and_raise_error).to be_a_kind_of(RuntimeError) end But(/^it should not be a NoMethod error for embed$/) do expect(@screenshot_and_raise_error.message[/embed/, 0]).to be_falsey expect(@screenshot_and_raise_error).not_to be_a_kind_of(NoMethodError) end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/spec/support/ideviceinstaller/unit/installer_spec.rb
describe 'Calabash IDeviceInstaller' do let(:ipa_path) { ipa_path = File.expand_path('./xtc-staging/CalSmoke-cal.ipa') unless File.exist?(ipa_path) system('make', 'ipa-cal') end ipa_path } let(:udid) { 'device udid' } let(:device) { RunLoop::Device.new('denis', '8.3', udid) } let(:fake_binary) { FileUtils.touch(File.join(Dir.mktmpdir, 'ideviceinstaller')).first } let(:options) { {:path_to_binary => fake_binary} } let(:installer) { Calabash::IDeviceInstaller.new(ipa_path, udid, options) } describe '.new' do describe 'raises an error when' do describe 'cannot find an ideviceinstaller binary' do it 'that was installed by homebrew' do expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return('/path/does/not/exist') expect { Calabash::IDeviceInstaller.new(nil, nil) }.to raise_error(Calabash::IDeviceInstaller::BinaryNotFound) end it 'that was passed as an optional argument' do expect { Calabash::IDeviceInstaller.new(nil, nil, {:path_to_binary => '/some/other/ideviceinstaller'}) }.to raise_error(Calabash::IDeviceInstaller::BinaryNotFound) end it 'cannot find ideviceinstaller in the $PATH' do expect(Calabash::IDeviceInstaller).to receive(:binary_in_path).and_return(nil) expect(Calabash::IDeviceInstaller).to receive(:homebrew_binary).and_return('/path/does/not/exist') expect { Calabash::IDeviceInstaller.new(nil, nil) }.to raise_error(Calabash::IDeviceInstaller::BinaryNotFound) end end it 'cannot create an ipa' do expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(Calabash::IPA).to receive(:new).and_raise RuntimeError expect { Calabash::IDeviceInstaller.new(nil, nil) }.to raise_error(Calabash::IDeviceInstaller::CannotCreateIPA) end it 'cannot find a device with udid' do expect(File).to receive(:exist?).with('/usr/local/bin/ideviceinstaller').and_return(true) expect(Calabash::IPA).to receive(:new).and_return nil expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([]) expect { Calabash::IDeviceInstaller.new(nil, nil) }.to raise_error(Calabash::IDeviceInstaller::DeviceNotFound) end end it 'sets it variables' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(installer.binary).to be == fake_binary expect(installer.tries).to be == Calabash::IDeviceInstaller::DEFAULT_RETRYABLE_OPTIONS[:tries] expect(installer.interval).to be == Calabash::IDeviceInstaller::DEFAULT_RETRYABLE_OPTIONS[:interval] expect(installer.ipa).to be_truthy expect(installer.udid).to be == device.udid end end it '#to_s' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect { installer.to_s }.not_to raise_error end it '#binary' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(installer.instance_variable_get(:@binary)).to be == installer.binary end describe '#app_installed?' do it 'returns false when app is not installed' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(installer).to receive(:execute_ideviceinstaller_cmd).and_return({:out => ''}) expect(installer.app_installed?).to be_falsey end it 'returns true when app is installed' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) out = { :out => [ 'Total: 3 apps', 'com.apple.itunesconnect.mobile - Connect 261', 'com.deutschebahn.navigator - DB Navigator 18', 'sh.calaba.CalSmoke-cal - CalSmoke 1.0' ].join("\n") } expect(installer).to receive(:execute_ideviceinstaller_cmd).and_return(out) expect(installer.app_installed?).to be_truthy end end describe '#install_app' do describe 'return true if app was successfully installed' do it 'was successfully installed' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(installer).to receive(:app_installed?).and_return(false, true) expect(installer).to receive(:execute_ideviceinstaller_cmd).and_return({}) expect(installer.install_app).to be == true end end it 'raises error if app was not installed' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(installer).to receive(:app_installed?).and_return(false, false) expect(installer).to receive(:execute_ideviceinstaller_cmd).and_return({}) expect { installer.install_app }.to raise_error(Calabash::IDeviceInstaller::InstallError) end it 'calls uninstall if the app is already installed' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(installer).to receive(:app_installed?).and_return(true, true) expect(installer).to receive(:uninstall_app).and_return(true) expect(installer).to receive(:execute_ideviceinstaller_cmd).and_return({}) expect(installer.install_app).to be == true end end describe '#ensure_app_installed' do it 'returns true if app is installed' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(installer).to receive(:app_installed?).and_return(true) expect(installer.ensure_app_installed).to be == true end it 'calls install otherwise' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(installer).to receive(:app_installed?).and_return(false) expect(installer).to receive(:install_app).and_return(true) expect(installer.ensure_app_installed).to be == true end end describe '#uninstall_app' do describe 'return true if app' do it 'is not installed' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(installer).to receive(:app_installed?).and_return(false) expect(installer.uninstall_app).to be == true end it 'was successfully uninstalled' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(installer).to receive(:app_installed?).and_return(true, false) expect(installer).to receive(:execute_ideviceinstaller_cmd).and_return({}) expect(installer.uninstall_app).to be == true end end it 'raises error if app was not installed' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(installer).to receive(:app_installed?).and_return(true, true) expect(installer).to receive(:execute_ideviceinstaller_cmd).and_return({}) expect { installer.uninstall_app }.to raise_error(Calabash::IDeviceInstaller::UninstallError) end end describe 'private' do it '.homebrew_binary' do expect(Calabash::IDeviceInstaller.homebrew_binary).to be == '/usr/local/bin/ideviceinstaller' end describe '.binary_in_path' do it 'returns ideviceinstaller path if it is in $PATH' do expect(Calabash::IDeviceInstaller).to receive(:shell_out).and_return('/path/to/binary') expect(Calabash::IDeviceInstaller.binary_in_path).to be == '/path/to/binary' end it 'returns nil if ideviceinstaller is not in $PATH' do expect(Calabash::IDeviceInstaller).to receive(:shell_out).and_return('', nil) expect(Calabash::IDeviceInstaller.binary_in_path).to be == nil expect(Calabash::IDeviceInstaller.binary_in_path).to be == nil end end describe '.expect_binary' do describe 'raises error when' do it 'user supplies a binary that does not exist' do binary = '/path/does/not/exist' expect(Calabash::IDeviceInstaller).to receive(:select_binary).with(binary).and_return(binary) expect { Calabash::IDeviceInstaller.expect_binary(binary) }.to raise_error(Calabash::IDeviceInstaller::BinaryNotFound) end it 'binary cannot be found in $PATH or in the default location' do binary = 'path/does/not/exist' expect(Calabash::IDeviceInstaller).to receive(:homebrew_binary).and_return(binary) expect(Calabash::IDeviceInstaller).to receive(:binary_in_path).and_return(nil) expect { Calabash::IDeviceInstaller.expect_binary }.to raise_error(Calabash::IDeviceInstaller::BinaryNotFound) end end it 'returns the discovered binary path' do expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(Calabash::IDeviceInstaller.expect_binary).to be == fake_binary end end it '.available_devices' do devices = Calabash::IDeviceInstaller.available_devices expect(devices).to be_a_kind_of(Array) unless devices.empty? expect(devices.first).to be_a_kind_of(RunLoop::Device) end end it '#retriable_intervals' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(installer.send(:retriable_intervals)).to be_a_kind_of Array end it '#timeout' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(installer.send(:timeout)).to be_a_kind_of Numeric end describe '#exec_with_open3' do it 'raises InvocationError if it encounters an error' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) expect(Open3).to receive(:popen3).and_raise StandardError expect { installer.send(:exec_with_open3, []) }.to raise_error Calabash::IDeviceInstaller::InvocationError end end describe '#execute_ideviceinstaller_cmd' do it 'succeeds when exit status is 0' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) hash = { :exit_status => 0 } expect(installer).to receive(:exec_with_open3).and_return(hash) expect(installer.send(:execute_ideviceinstaller_cmd, [])).to be == hash end it 'retries if exit status in not 0' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) hashes = [ { :exit_status => 1 }, { :exit_status => 1 }, { :exit_status => 0, :pid => 2 } ] expect(installer).to receive(:retriable_intervals).and_return(Array.new(3, 0.1)) expect(installer).to receive(:exec_with_open3).and_return(*hashes) expect(installer.send(:execute_ideviceinstaller_cmd, [])[:pid]).to be == 2 end it 'retries if execution results in an error' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) hash = { :exit_status => 0, :pid => 2 } expect(installer).to receive(:retriable_intervals).and_return(Array.new(2, 0.1)) expect(installer).to receive(:exec_with_open3).and_raise(Calabash::IDeviceInstaller::InvocationError) expect(installer).to receive(:exec_with_open3).and_return(hash) expect(installer.send(:execute_ideviceinstaller_cmd, [])[:pid]).to be == 2 end it 'retries if execution exceeds timeout' do expect(Calabash::IDeviceInstaller).to receive(:available_devices).and_return([device]) expect(Calabash::IDeviceInstaller).to receive(:select_binary).and_return(fake_binary) hash = { :exit_status => 0, :pid => 2 } expect(installer).to receive(:retriable_intervals).and_return(Array.new(2, 0.1)) expect(installer).to receive(:exec_with_open3).and_raise(Calabash::IDeviceInstaller::InvocationError) expect(installer).to receive(:exec_with_open3).and_return(hash) expect(installer.send(:execute_ideviceinstaller_cmd, [])[:pid]).to be == 2 end end end end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/slider_steps.rb
Then(/^I can get the min and max values of the slider$/) do query = "UISlider marked:'slider'" options = wait_options(query) wait_for_elements_exist(query, options) max = query(query, :maximumValue).first min = query(query, :minimumValue).first expect(max).to be == 10 expect(min).to be == -10 end And(/^I can set the value of the slider to (\d+)$/) do |value| query = "UISlider marked:'slider'" options = wait_options(query) wait_for_elements_exist(query, options) slider_set_value(query, value.to_i) value = query(query, :value).first expect(value).to be == value.to_i end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/support/wait_options.rb
require 'calabash-cucumber/wait_helpers' module CalSmokeApp module WaitOpts include Calabash::Cucumber::WaitHelpers # A convenience function for passing wait options to a wait_for* function # @return [Hash] default wait options # # Pass this to your wait_for_* functions # # @param [String] query What you are waiting for # @param [Hash] opts wait options # @option opts :timeout defaults to wait_timeout() # @option opts :disappear iff true changes the error message to indicate # that we were waiting for the view to disappear def wait_options(query, opts={}) default_opts = {:disappear => false, :timeout => wait_timeout} merged = default_opts.merge(opts) # handle :timeout => nil timeout = merged[:timeout] || wait_timeout if query.is_a?(String) qstr = query elsif query.is_a?(Array) qstr = query.join($-0) else raise ArgumentError, %Q[ Expected query to be a String or Array, but found: #{query} ] end if merged[:disappear] msg = %Q[ Waited for #{timeout} seconds but could still see: #{qstr} ] else msg = %Q[ Waited for #{timeout} seconds but did not see: #{qstr} ] end { :timeout => timeout, :retry_frequency => retry_freq, :post_timeout => wait_step_pause, :timeout_message => msg } end # how long to wait for a view before failing def wait_timeout (ENV['WAIT_TIMEOUT'] || 2.0).to_f end # how often to retry querying for a view def retry_freq (ENV['RETRY_FREQ'] || 0.1).to_f end # the time to wait after a wait condition evals to +true+ def wait_step_pause (ENV['POST_TIMEOUT'] || 0.0).to_f end end end World(CalSmokeApp::WaitOpts)
MortenGregersen/ios-smoke-test-app
CalSmokeApp/spec/support/ideviceinstaller/integration/ideviceinstaller_spec.rb
module IDeviceId def self.binary binary = `which idevice_id`.strip if binary.nil? || binary.empty? nil else binary end end def self.idevice_id_bin_path self.binary || '/usr/local/bin/idevice_id' end def self.idevice_id_available? File.exist?(self.idevice_id_bin_path) end # Xcode 6 + iOS 8 - devices on the same network, whether development or # not, appear when calling $ xcrun instruments -s devices. For the # purposes of testing, we will only try to connect to devices that are # connected via USB. # # Also idevice_id, which ideviceinstaller relies on, will sometimes report # devices 2x which will cause ideviceinstaller to fail. def self.physical_devices_for_testing devices = Calabash::IDeviceInstaller.available_devices if self.idevice_id_available? white_list = `#{self.idevice_id_bin_path} -l`.strip.split("\n") devices.select do | device | white_list.include?(device.udid) && white_list.count(device.udid) == 1 end else devices end end end describe 'Calabash IDeviceInstaller Integration' do if !File.exist?('/usr/local/bin/ideviceinstaller') it 'Skipping ideviceinstaller integration tests: /usr/local/bin/ideviceinstaller does not exist' do end elsif IDeviceId.physical_devices_for_testing.empty? it 'Skipping ideviceinstaller integration tests: no connected devices' do end else let(:options) { Calabash::IDeviceInstaller::DEFAULT_RETRYABLE_OPTIONS } let (:installer) { ipa_path = File.expand_path('./xtc-staging/CalSmoke-cal.ipa') unless File.exist?(ipa_path) system('make', 'ipa-cal') end udid = IDeviceId.physical_devices_for_testing.first.udid Calabash::IDeviceInstaller.new(ipa_path, udid, options) } it '#to_s' do capture_stdout do puts installer end end it '#install_app' do installer.install_app end it '#uninstall_app' do installer.uninstall_app end describe 'ensure popen3 exits cleanly' do let(:options) { {:timeout => 1, :tries => 2, :interval => 0.2} } it '#install_app' do expect { installer.install_app }.to raise_error(Calabash::IDeviceInstaller::InvocationError, 'execution expired') expect(installer.instance_variable_get(:@stdin).closed?).to be_truthy expect(installer.instance_variable_get(:@stdout).closed?).to be_truthy expect(installer.instance_variable_get(:@stderr).closed?).to be_truthy pid = installer.instance_variable_get(:@pid) terminator = RunLoop::ProcessTerminator.new(pid, 'TERM', 'ideviceinstaller') expect(terminator.process_alive?).to be == false end end end end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/drag_and_drop_steps.rb
<gh_stars>10-100 module CalSmokeApp module DragAndDrop class Color attr_reader :red, :green, :blue def initialize(red, green, blue) @red = red @green = green @blue = blue end def to_s "#<Color #{red}, #{green}, #{blue}>" end def inspect to_s end def self.color_with_hash(hash) red = (hash['red'] * 256).to_i green = (hash['green'] * 256).to_i blue = (hash['blue'] * 256).to_i Color.new(red, green, blue) end def == (other) [red == other.red, green == other.green, blue == other.blue].all? end def self.red Color.new(153, 39, 39) end def self.blue Color.new(29, 90, 171) end def self.green Color.new(33, 128, 65) end end def frame_equal(a, b) [a['x'] == b['x'], a['y'] == b['y'], a['height'] == b['height'], a['width'] == b['width']].all? end def color_for_box(box_id) case box_id when 'red' Color.red when 'green' Color.green when 'blue' Color.blue else raise "Unknown box_id '#{box_id}'. Expected red, blue, or green" end end end end World(CalSmokeApp::DragAndDrop) When(/^I drag the (red|blue|green) box to the (left|right) well$/) do |box, well| from_query = "UIImageView marked:'#{box}'" to_query = "UIView marked:'#{well} well'" wait_for_elements_exist([from_query, to_query]) @dragged_box_query = from_query @dragged_box_start_frame = query(from_query).first['frame'] @target_well_query = to_query @final_color_of_target_well = color_for_box(box) pan(from_query, to_query, {duration: 1.0}) end Then(/^the well should change color$/) do query = @target_well_query result = query(query, :backgroundColor) actual = CalSmokeApp::DragAndDrop::Color.color_with_hash(result.first) expect(actual).to be == @final_color_of_target_well end And(/^the box goes back to its original position$/) do query = @dragged_box_query box_id = query.split('marked:')[1] timeout = 4 message = "Waited #{timeout} seconds for '#{box_id}' box to return to original position." options = {timeout: timeout, timeout_message: message} wait_for(options) do result = query(query) if result.empty? false else actual = result.first['frame'] frame_equal(actual, @dragged_box_start_frame) end end end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/user_defaults_steps.rb
module Calabash module IOS module ResetBetweenScenarioSteps def qstr_for_switch "view marked:'controls page' switch marked:'switch'" end def switch_state qstr = qstr_for_switch res = nil wait_for do res = query(qstr, :isOn).first not res.nil? end res == 1 end def add_file_to_sandbox_dir(filename, directory) arg = JSON.generate({'directory' => directory, 'filename' => filename}) res = backdoor('addFileToSandboxDirectory:', arg) unless res raise "expected backdoor call to write '#{filename}' in '#{directory}'" end end def expect_file_in_sandbox_dir(filename, directory) res = backdoor('arrayForFilesInSandboxDirectory:', directory) if res.nil? raise "expected backdoor to return files for '#{directory}'" end unless res.include?(filename) raise "expected to see '#{filename}' in '#{res}'" end end def expect_file_does_not_exist_in_directory(filename, directory) res = backdoor('arrayForFilesInSandboxDirectory:', directory) if res.nil? raise "expected backdoor to return files for '#{directory}'" end if res.include?(filename) raise "expected not to see '#{filename}' in '#{res}'" end end end end end World(Calabash::IOS::ResetBetweenScenarioSteps) Given(/^I turn the switch on$/) do wait_for_element_exists qstr_for_switch unless switch_state # having a very hard time touching this switch. :( sleep(1.0) touch qstr_for_switch sleep(0.5) # Trying to debug iOS 8 NSUserDefaults problem. # http://www.screencast.com/t/dxwNbDxn0Dp # # UPDATE: Problem has been fixed in Xcode 6.1 in iOS 8.1 Simulators. # # The gist is that when running with the instruments tool, NSUserDefaults # do not appear to be persisted. # # Both of these and the 'touch' above can cause the switch to change state # and trigger a UIEvent. However, none of them persist changes to # NSUserDefaults despite the Objc code on the app side demonstrating that # the defaults have been written. # uia("target.frontMostApp().mainWindow().elements()['first page'].switches()['switch'].tap()") # uia("target.frontMostApp().mainWindow().elements()['first page'].switches()['switch'].setValue(1)") end unless switch_state screenshot_and_raise 'expected switch to be on' end end Then (/^I should see the switch is (on|off)$/) do |state| actual_state = switch_state ? 'on' : 'off' unless actual_state == state screenshot_and_raise "expected switch to be '#{state}' but found '#{actual_state}'" end end And(/^I drop some files in the sandbox$/) do ['tmp', 'Documents', 'Library'].each do |dir| add_file_to_sandbox_dir('foo.txt', dir) end end Then(/^I should see the files I put in the sandbox$/) do ['tmp', 'Documents', 'Library'].each do |dir| expect_file_in_sandbox_dir('foo.txt', dir) end end Then(/^I should not see the files I put in the sandbox$/) do ['tmp', 'Documents', 'Library'].each do |dir| expect_file_does_not_exist_in_directory('foo.txt', dir) end end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/support/dry_run.rb
require "calabash-cucumber"
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/keychain_steps.rb
<filename>CalSmokeApp/features/step_definitions/keychain_steps.rb module Calabash module IOS module KeychainSteps def keychain_service_name 'calabash.smoke.test.app.service' end end end end World(Calabash::IOS::KeychainSteps) When(/^I clear the keychain$/) do keychain_clear_accounts_for_service(keychain_service_name) end Given(/^that the keychain is clear$/) do keychain_clear_accounts_for_service(keychain_service_name) end Then(/^the keychain should contain the account password "(.*?)" for "(.*?)"$/) do |password, username| actual = keychain_password(keychain_service_name, username) if xamarin_test_cloud? if actual.nil? screenshot_and_raise "expected an entry for '#{username}' in the keychain" end else unless actual == password screenshot_and_raise "expected '#{password}' in keychain but found '#{actual}'" end end end Given(/^that the keychain contains the account password "(.*?)" for "(.*?)"$/) do |password, username| # app uses the first account/password pair it finds, so clear out # any preexisting saved passwords for our service keychain_clear_accounts_for_service(keychain_service_name) keychain_set_password(keychain_service_name, username, password) end Then(/^the keychain should be empty because I called clear_keychain$/) do accounts = keychain_accounts_for_service(keychain_service_name) # Locally, the Keychain is cleared. # # On the XTC, there is additional Keychain item created for all apps during # test execution that should not be cleared. This keychain item is _always_ # cleared when the device is reset: between Scenarios and between tests. # Put another way, this Keychain item will _never_ leak - it is always destroyed # between tests. There is a Scenario that demonstrates this behavior. # # Waiting on iOS 10 change in XTC. When this starts failing, we know the XTC # has updated. # # https://github.com/xamarin/test-cloud-frontend/issues/2506 if xamarin_test_cloud? && !ios10? if accounts.count != 1 raise "Expected one keychain account on the XTC" end else if !accounts.empty? raise "Expected no accounts but found '#{accounts}'" end end end Then(/^the keychain should be empty because I reset the device$/) do accounts = keychain_accounts_for_service(keychain_service_name) if !accounts.empty? raise "Expected no accounts but found '#{accounts}'" end end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/support/ideviceinstaller.rb
require "tmpdir" require "fileutils" require "run_loop" require "csv" module Calabash # A model of the an .ipa - a application binary for iOS devices. class IPA # The path to this .ipa. # @!attribute [r] path # @return [String] A path to this .ipa. attr_reader :path # The bundle identifier of this ipa. # @!attribute [r] bundle_identifier # @return [String] The bundle identifier of this ipa; obtained by inspecting # the app's Info.plist. attr_reader :bundle_identifier # Create a new ipa instance. # @param [String] path_to_ipa The path the .ipa file. # @return [Calabash::IPA] A new ipa instance. # @raise [RuntimeError] If the file does not exist. # @raise [RuntimeError] If the file does not end in .ipa. def initialize(path_to_ipa) unless File.exist? path_to_ipa raise "Expected an ipa at '#{path_to_ipa}'" end unless path_to_ipa.end_with?('.ipa') raise "Expected '#{path_to_ipa}' to be" end @path = path_to_ipa end # @!visibility private def to_s "#<IPA: #{bundle_identifier}: '#{path}'>" end # The bundle identifier of this ipa. # @return [String] A string representation of this ipa's CFBundleIdentifier # @raise [RuntimeError] If ipa does not expand into a Payload/<app name>.app # directory. # @raise [RuntimeError] If an Info.plist does exist in the .app. def bundle_identifier unless File.exist?(bundle_dir) raise "Expected a '#{File.basename(path).split('.').first}.app'\nat path '#{payload_dir}'" end @bundle_identifier ||= lambda { info_plist_path = File.join(bundle_dir, 'Info.plist') unless File.exist? info_plist_path raise "Expected an 'Info.plist' at '#{bundle_dir}'" end pbuddy = RunLoop::PlistBuddy.new pbuddy.plist_read('CFBundleIdentifier', info_plist_path) }.call end private def tmpdir @tmpdir ||= Dir.mktmpdir end def payload_dir @payload_dir ||= lambda { FileUtils.cp(path, tmpdir) zip_path = File.join(tmpdir, File.basename(path)) Dir.chdir(tmpdir) do system('unzip', *['-q', zip_path]) end File.join(tmpdir, 'Payload') }.call end def bundle_dir @bundle_dir ||= lambda { Dir.glob(File.join(payload_dir, '*')).detect {|f| File.directory?(f) && f.end_with?('.app')} }.call end end # A wrapper around the ideviceinstaller tool. # # @note libimobiledevice, ideviceinstaller, and homebrew are third-party # tools. Please don't report problems with these tools on the Calabash # support channels. We don't maintain them, we just use them. # # @see http://www.libimobiledevice.org/ # @see https://github.com/libimobiledevice/libimobiledevice # @see https://github.com/libimobiledevice/ideviceinstaller # @see http://brew.sh/ class IDeviceInstaller # The default Retriable and Timeout options. ideviceinstaller is a good # tool. Experience has shown that it takes no more than 2 tries to # install an ipa. You can override these defaults by passing arguments # to the initializer. DEFAULT_RETRYABLE_OPTIONS = { :tries => 2, :interval => 1, :timeout => 10 } # Raised when the ideviceinstaller binary cannot be found. class BinaryNotFound < RuntimeError; end # Raised when a IPA instance cannot be created. class CannotCreateIPA < RuntimeError; end # Raised when the specified device cannot be found. class DeviceNotFound < RuntimeError; end # Raised when there is a problem installing an ipa on the target device. class InstallError < RuntimeError; end # Raised when there is a problem uninstalling an ipa on the target device. class UninstallError < RuntimeError; end # Raised when the command line invocation of ideviceinstaller fails. class InvocationError < RuntimeError; end # The path to the ideviceinstaller binary. # @!attribute [r] binary # @return [String] A path to the ideviceinstaller binary. attr_reader :binary # The ipa to install. # @!attribute [r] ipa # @return [Calabash::IPA] The ipa to install. attr_reader :ipa # The udid of the device to install the ipa on. # @!attribute [r] udid # @return [String] The udid of the device to install the ipa on. attr_reader :udid # The number of times to try any ideviceinstaller command. This is an # option for Retriable.retriable. # @!attribute [r] tries # @return [Numeric] The number of times to try any ideviceinstaller command. attr_reader :tries # How long to wait before retrying a failed ideviceinstaller command. This # is an option for Retriable.retriable. # @!attribute [r] interval # @return [Numeric] How long to wait before retrying a failed # ideviceinstaller command. attr_reader :interval # How long to wait for any ideviceinstaller command to complete before # timing out. This is an option to Timeout.timeout. # @!attribute [r] timeout # @return [Numeric] How long to wait for any ideviceinstaller command to # complete before timing out. attr_reader :timeout # Create an instance of an installer. # # The target device _must_ be connected via USB to the host machine. # # @param [String] path_to_ipa The path to ipa to install. # @param [String] udid_or_name The udid or name of the device to install # the ipa on. # @param [Hash] options Options to control the behavior of the installer. # # @option options [Numeric] :tries (2) The number of times to retry a failed # ideviceinstaller command. # @option options [Numeric] :interval (1.0) How long to wait before retrying # a failed ideviceinstaller command. # @option options [Numeric] :timeout (10) How long to wait for any # ideviceinstaller command to complete before timing out. # @option options [String] :path_to_binary (/usr/local/bin/ideviceinstaller) # The full path the ideviceinstaller library. # # @return [Calabash::IDeviceInstaller] A new instance of IDeviceInstaller. # # @raise [BinaryNotFound] If no ideviceinstaller binary can be found on the # system. # @raise [CannotCreateIPA] If an IPA instance cannot be created from the # `path_to_ipa`. # @raise [DeviceNotFound] If the device specified by `udid_or_name` cannot # be found. def initialize(path_to_ipa, udid, options={}) merged_opts = DEFAULT_RETRYABLE_OPTIONS.merge(options) @binary = IDeviceInstaller.expect_binary(merged_opts[:path_to_binary]) begin @ipa = Calabash::IPA.new(path_to_ipa) rescue RuntimeError => e raise CannotCreateIPA, e end @udid = udid @tries = merged_opts[:tries] @interval = merged_opts[:interval] @timeout = merged_opts[:timeout] end # @!visibility private def to_s "#<Installer: #{binary} #{ipa.path} #{udid}>" end def app_installed? command = [binary, "--udid", udid, "--list-apps"] hash = execute_ideviceinstaller_cmd(command) out = hash[:out].gsub(/\"/, "") csv = CSV.new(out, {headers: true}).to_a.map do |row| row.to_hash end csv.detect do |row| row["CFBundleIdentifier"] == ipa.bundle_identifier end end # Install the ipa on the target device. # # @note IMPORTANT If the app is already installed, uninstall it first. # If you don't want to reinstall, use `ensure_app_installed` instead of # this method. # # @note The 'ideviceinstaller --install' command does not overwrite an app # if it is already installed on a device. # # @see Calabash::IDeviceInstaller#ensure_app_installed # # @return [Boolean] Return true if the app was installed. # @raise [InstallError] If the app was not installed. # @raise [UninstallError] If the app was not uninstalled. def install_app uninstall_app if app_installed? args = [binary, "--udid", udid, "--install", ipa.path] result = execute_ideviceinstaller_cmd(args) if result[:exit_status] != 0 raise InstallError, %Q[ Could not install '#{ipa}' on '#{udid}': #{result[:out]} ] end true end # Ensure the ipa has been installed on the device. If the app is already # installed, do nothing. Otherwise, install the app. # # @return [Boolean] Return true if the app was installed. # @raise [InstallError] If the app was not installed. def ensure_app_installed return true if app_installed? install_app end # Uninstall the ipa from the target_device. # # @return [Boolean] Return true if the app was uninstalled. # @raise [UninstallError] If the app was not uninstalled. def uninstall_app return true unless app_installed? command = [binary, "--udid", udid, "--uninstall", ipa.bundle_identifier] execute_ideviceinstaller_cmd(command) if app_installed? raise UninstallError, "Could not uninstall '#{ipa}' on '#{udid}'" end true end private def self.homebrew_binary '/usr/local/bin/ideviceinstaller' end def self.binary_in_path which = self.shell_out('which ideviceinstaller') if which.nil? || which.empty? nil else which end end def self.shell_out(cmd) `#{cmd}`.strip end def self.select_binary(user_supplied=nil) user_supplied || self.binary_in_path || self.homebrew_binary end def self.expect_binary(user_supplied=nil) binary = self.select_binary(user_supplied) unless File.exist?(binary) if user_supplied raise BinaryNotFound, "Expected binary at '#{user_supplied}'" else raise BinaryNotFound, %Q[ Expected binary to be in $PATH or '/usr/local/bin/ideviceinstaller' You must install ideviceinstaller to use this class. We recommend installing ideviceinstaller with homebrew. ] end end binary end # Expensive! Avoid calling this more than 1x. This cannot be memoized # into a class variable or class instance variable because the state will # change when devices attached/detached or join/leave the network. def self.available_devices physical_devices end def retriable_intervals Array.new(tries, interval) end def execute_ideviceinstaller_cmd(command) result = {} on = [InvocationError] on_retry = Proc.new do |_, try, elapsed_time, next_interval| puts "INFO: ideviceinstaller: attempt #{try} failed in '#{elapsed_time}'; will retry in '#{next_interval}'" end options = { intervals: retriable_intervals, on_retry: on_retry, on: on } require "retriable" ::Retriable.retriable(options) do options = {:timeout => 120, :log_cmd => true} result = RunLoop::Shell.run_shell_command(command, options) exit_status = result[:exit_status] if exit_status != 0 raise InvocationError, %Q[ Could not execute: #{command.join(" ")} Command generated this output: #{result[:out]} ] end end result end end end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/spec/support/ideviceinstaller/unit/ipa_spec.rb
describe 'Calabash IPA' do let(:ipa_path) { ipa_path = File.expand_path('./xtc-staging/CalSmoke-cal.ipa') unless File.exist?(ipa_path) system('make', 'ipa-cal') end ipa_path } let(:ipa) { Calabash::IPA.new(ipa_path) } describe '.new' do describe 'raises an exception' do it 'when the path does not exist' do expect { Calabash::IPA.new('/path/does/not/exist') }.to raise_error end it 'when the path does not end in .ipa' do expect(File).to receive(:exist?).with('/path/foo.app').and_return(true) expect { Calabash::IPA.new('/path/foo.app') }.to raise_error end end it 'sets the path' do expect(ipa.path).to be == ipa_path end end it '#to_s' do expect { ipa.to_s}.not_to raise_error end describe '#bundle_identifier' do it "reads the app's Info.plist" do expect(ipa.bundle_identifier).to be == 'sh.calaba.CalSmoke-cal' end describe 'raises an error when' do it 'cannot find the bundle_dir' do expect(ipa).to receive(:bundle_dir).and_return(nil) expect { ipa.bundle_identifier }.to raise_error end it 'cannot find the Info.plist' do expect(ipa).to receive(:bundle_dir).at_least(:once).and_return(Dir.mktmpdir) expect { ipa.bundle_identifier }.to raise_error end end end describe 'private' do it '#tmpdir' do tmp_dir = ipa.send(:tmpdir) expect(File.exist?(tmp_dir)).to be_truthy expect(File.directory?(tmp_dir)).to be_truthy expect(ipa.instance_variable_get(:@tmpdir)).to be == tmp_dir end it '#payload_dir' do payload_dir = ipa.send(:payload_dir) expect(File.exist?(payload_dir)).to be_truthy expect(File.directory?(payload_dir)).to be_truthy expect(ipa.instance_variable_get(:@payload_dir)).to be == payload_dir end it '#bundle_dir' do bundle_dir = ipa.send(:bundle_dir) expect(File.exist?(bundle_dir)).to be_truthy expect(File.directory?(bundle_dir)).to be_truthy expect(ipa.instance_variable_get(:@bundle_dir)).to be == bundle_dir end end end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/pages/pom.rb
module POM require "calabash-cucumber/ibase" class HomePage < Calabash::IBase def my_buggy_method screenshot_and_raise 'Hey!' end end end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/german_steps.rb
Then(/^I see localized text "([^"]*)"$/) do |text| query = "* marked:'localized label'" wait_for do !query(query).empty? end actual = query(query).first["text"] unless actual == text fail(%Q[Expected text to be localized, but found: actual: #{actual} expected: #{text} ]) end end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/pan_steps.rb
When(/^I pan left on the screen$/) do top_view = query('*').first rect = top_view['rect'] from_x = 0 from_y = rect['height'] * 0.5 from_offset = {x: from_x, y: from_y} to_x = rect['width'] * 0.75 to_y = from_y to_offset = {x: to_x, y: to_y} pan_coordinates(from_offset, to_offset, {duration: 0.5}) wait_for_none_animating end Then(/^I go back to the Scrolls page$/) do query = "view marked:'scrolls page'" options = wait_options(query) wait_for_element_exists(query, options) end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/pages/not_pom.rb
<filename>CalSmokeApp/features/pages/not_pom.rb module NotPOM class HomePage include Calabash::Cucumber::Operations def my_buggy_method screenshot_and_raise 'Hey!' end end end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/config/xtc-other-gems.rb
<reponame>MortenGregersen/ios-smoke-test-app<gh_stars>0 gem 'retriable', '~> 2.0' gem "cucumber", "~> 2.0" gem "xamarin-test-cloud", "~> 2.0" gem 'rake', '~> 10.3' gem 'bundler', '~> 1.6' gem 'xcpretty', '~> 0.1' gem 'rspec', '~> 3.0' gem 'pry' gem 'pry-nav' gem 'luffa', '~> 1.0', '>= 1.0.2' gem 'chronic', '>= 0.10.2', '< 1.0'
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/scroll_steps.rb
Then(/^I see the scrolling views table$/) do query = "UITableView marked:'table'" options = wait_options('Scrolling views table') wait_for_element_exists(query, options) end When(/^I touch the (collection|table|scroll) views row$/) do |row_name| query = "UITableViewCell marked:'#{row_name} views row'" options = wait_options(query) wait_for_elements_exist(query, options) touch(query) wait_for_none_animating end Then(/^I see the (collection|table|scroll) views page$/) do |page_name| query = "view marked:'#{page_name} views page'" options = wait_options(query) wait_for_elements_exist(query, options) end Then(/^I scroll the logos collection to the steam icon by mark$/) do query = "UICollectionView marked:'logo gallery'" options = wait_options(query) wait_for_element_exists(query, options) options = { :query => query, :scroll_position => :top, :animated => true } scroll_to_collection_view_item_with_mark('steam', options) wait_for_none_animating end Then(/^I scroll the logos collection to the github icon by index$/) do query = "UICollectionView marked:'logo gallery'" options = wait_options(query) wait_for_element_exists(query, options) options = { :query => query, :scroll_position => :center_vertical, :animated => false } scroll_to_collection_view_item(13, 0, options) wait_for_none_animating end Then(/^I scroll up on the logos collection to the android icon$/) do query = "UICollectionView marked:'logo gallery'" options = wait_options(query) wait_for_element_exists(query, options) icon_query = "UICollectionViewCell marked:'android'" visible = lambda { query(icon_query).count == 1 } count = 0 loop do break if visible.call || count == 4; scroll(query, :up) wait_for_none_animating count = count + 1; end expect(query(icon_query).count).to be == 1 end Then(/^I scroll the colors collection to the middle of the purple boxes$/) do query = "UICollectionView marked:'color gallery'" options = wait_options(query) wait_for_element_exists(query, options) options = { :query => query, :scroll_position => :top, :animated => true } scroll_to_collection_view_item(12, 4, options) wait_for_none_animating end Then(/^I scroll the logos table to the steam row by mark$/) do query = "UITableView marked:'logos'" options = wait_options(query) wait_for_element_exists(query, options) options = { :query => query, :scroll_position => :middle, :animate => true } scroll_to_row_with_mark('steam', options) wait_for_none_animating end Then(/^I scroll the logos table to the github row by index$/) do query = "UITableView marked:'logos'" options = wait_options(query) wait_for_element_exists(query, options) options = { :query => query, :scroll_position => :middle, :animate => true } scroll_to_row(query, 13) wait_for_none_animating end Then(/^I scroll up on the logos table to the android row$/) do query = "UITableView marked:'logos'" options = wait_options(query) wait_for_element_exists(query, options) row_query = "UITableViewCell marked:'android'" visible = lambda { query(row_query).count == 1 } count = 0 loop do break if visible.call || count == 3 scroll(query, :up) wait_for_none_animating count = count + 1; end expect(query(row_query).count).to be == 1 end Then(/^I center the cayenne box to the middle$/) do query = "UIScrollView marked:'scroll'" options = wait_options(query) wait_for_element_exists(query, options) query(query, :centerContentToBounds) wait_for_none_animating query = "view marked:'cayenne'" options = wait_options(query) wait_for_element_exists(query, options) end Then(/^I scroll up to the purple box$/) do query = "UIScrollView marked:'scroll'" options = wait_options(query) wait_for_element_exists(query, options) box_query = "view marked:'purple'" visible = lambda { result = query(box_query) if result.empty? false else rect = result.first['rect'] center_y = rect['center_y'] width = rect['width'] center_y + (width/2) > 64 end } count = 0 loop do break if visible.call || count == 3 scroll(query, :up) wait_for_none_animating count = count + 1; end expect(query(box_query).count).to be == 1 end Then(/^I scroll left to the light blue box$/) do query = "UIScrollView marked:'scroll'" options = wait_options(query) wait_for_element_exists(query, options) box_query = "view marked:'light blue'" visible = lambda { query(box_query).count == 1 } count = 0 loop do break if visible.call || count == 3 scroll(query, :left) wait_for_none_animating count = count + 1; end expect(query(box_query).count).to be == 1 end Then(/^I scroll down to the gray box$/) do query = "UIScrollView marked:'scroll'" options = wait_options(query) wait_for_element_exists(query, options) box_query = "view marked:'gray'" visible = lambda { query(box_query).count == 1 } count = 0 loop do break if visible.call || count == 3 scroll(query, :down) wait_for_none_animating count = count + 1; end expect(query(box_query).count).to be == 1 end Then(/^I scroll right to the dark gray box$/) do query = "UIScrollView marked:'scroll'" options = wait_options(query) wait_for_element_exists(query, options) box_query = "view marked:'dark gray'" visible = lambda { query(box_query).count == 1 } count = 0 loop do break if visible.call || count == 3 scroll(query, :right) wait_for_none_animating count = count + 1; end expect(query(box_query).count).to be == 1 end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/features/step_definitions/animations_steps.rb
Then(/^I wait for all animations to stop$/) do timeout = 4 message = "Waited #{timeout} seconds for all animations to stop" options = {timeout: timeout, timeout_message: message} # Test for: https://github.com/calabash/calabash-ios-server/pull/142 # When checking for no animation, ignore animations with trivially short durations wait_for_none_animating(options) end And(/^I have started an animation that lasts (\d+) seconds$/) do |duration| @last_animation_duration = duration.to_i timeout = 4 query = "view marked:'animated view'" message = "Timed out waiting for #{query} after #{timeout} seconds" wait_for({timeout: 4, timeout_message: message}) { !query(query).empty? } backdoor('animateOrangeViewOnDragAndDropController:', duration) end Then(/^I can wait for the animation to stop$/) do timeout = @last_animation_duration + 1 message = "Waited #{timeout} seconds for the animation to stop" options = {timeout: timeout, timeout_message: message} wait_for_none_animating(options) end And(/^I start the network indicator for (\d+) seconds$/) do |duration| @last_animation_duration = duration.to_i backdoor('startNetworkIndicatorForNSeconds:', duration.to_i) end Then(/^I can wait for the indicator to stop$/) do timeout = @last_animation_duration + 1 message = "Waited #{timeout} seconds for the network indicator to stop" options = {timeout: timeout, timeout_message: message } wait_for_no_network_indicator(options) end When(/^I pass an unknown condition to wait_for_condition$/) do options = { condition: 'unknown' } begin wait_for_condition(options) rescue RuntimeError => _ @runtime_error_raised = true end end When(/^I pass an empty query to wait_for_none_animating$/) do options = { query: '' } begin wait_for_none_animating(options) rescue RuntimeError => _ @runtime_error_raised = true end end Then(/^the app should not crash$/) do query('*') end And(/^an error should be raised$/) do expect(@runtime_error_raised).to be == true end
MortenGregersen/ios-smoke-test-app
CalSmokeApp/bin/make/install-test-binaries.rb
#!/usr/bin/env ruby require 'fileutils' cal_app = File.expand_path('Products/app/CalSmoke-cal/CalSmoke-cal.app') cal_ipa = File.expand_path('Products/ipa/CalSmoke-cal/CalSmoke-cal.ipa') app = File.expand_path('Products/app/CalSmoke/no-calabash/CalSmoke.app') ipa = File.expand_path('Products/ipa/CalSmoke/no-calabash/CalSmoke.ipa') # calabash-ios dir = File.expand_path('~/git/calabash/calabash-ios') if !File.exist?(dir) dir = File.expand_path('~/git/calabash-ios') end if !File.exist?(dir) raise 'Expected calabash-ios to be in ~/git/calabash/calabash-ios or ~/git/calabash-ios' end rspec_resources_dir = File.join(dir, 'calabash-cucumber/spec/resources') FileUtils.rm_rf(File.join(rspec_resources_dir, 'CalSmoke.app')) FileUtils.cp_r(app, rspec_resources_dir) FileUtils.mv(File.join(rspec_resources_dir, 'CalSmoke-no-Calabash-dylibs-embedded.app'), File.join(rspec_resources_dir, 'CalSmoke.app')) FileUtils.rm_rf(File.join(rspec_resources_dir, 'CalSmoke-cal.app')) FileUtils.cp_r(cal_app, rspec_resources_dir) #dylib_dir = File.join(dir, 'calabash-cucumber/test/dylib') #FileUtils.cp_r(app, File.join(dylib_dir, 'CalSmoke.app')) xtc_dir = File.join(dir, 'calabash-cucumber/test/xtc') FileUtils.cp_r(cal_ipa, xtc_dir) # run-loop dir = File.expand_path('~/git/calabash/run_loop') if !File.exist?(dir) dir = File.expand_path('~/git/calabash/run-loop') end if !File.exist?(dir) dir = File.expand_path('~/git/run_loop') end if !File.exist?(dir) dir = File.expand_path('~/git/run-loop') end if !File.exist?(dir) raise 'Expected run-loop to be in ~/git/{run_loop | run-loop} or ~/git/calabash/{run_loop | run-loop}' end rspec_resources_dir = File.join(dir, 'spec/resources') FileUtils.cp_r(cal_app, rspec_resources_dir) FileUtils.cp_r(cal_ipa, rspec_resources_dir) FileUtils.cp_r(app, File.join(rspec_resources_dir, 'CalSmoke.app')) FileUtils.cp_r(ipa, File.join(rspec_resources_dir, 'CalSmoke.ipa')) # calabash dir = File.expand_path('~/git/calabash/calabash') if !File.exist?(dir) dir = File.expand_path('~/git/calabash') end if !File.exist?(dir) raise 'Expected calabash to be in ~/git/calabash/calabash or ~/git/calabash' end rspec_resources_dir = File.join(dir, 'spec/resources/ios') FileUtils.cp_r(cal_app, rspec_resources_dir) FileUtils.cp_r(cal_ipa, rspec_resources_dir) FileUtils.cp_r(app, File.join(rspec_resources_dir, 'CalSmoke.app')) FileUtils.cp_r(ipa, File.join(rspec_resources_dir, 'CalSmoke.ipa'))
smartwaivercom/ruby-sdk
lib/smartwaiver-sdk/user_client.rb
<filename>lib/smartwaiver-sdk/user_client.rb # # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/smartwaiver_base' class SmartwaiverUserClient < SmartwaiverSDK::SmartwaiverBase def initialize(api_key, api_endpoint = DEFAULT_API_ENDPOINT) super(api_key, api_endpoint) @rest_endpoints = define_rest_endpoints end def settings() path = @rest_endpoints[:settings] make_api_request(path, HTTP_GET) end private def define_rest_endpoints { :settings => "/v4/settings" } end end
smartwaivercom/ruby-sdk
spec/smartwaiver-sdk/dynamic_template_spec.rb
dir = File.dirname(__FILE__) require "#{dir}/../spec_helper" require "#{dir}/../../lib/smartwaiver-sdk/dynamic_template" describe SmartwaiverDynamicTemplate do before do FakeWeb.allow_net_connect = false end describe "dynamic templates" do it "#initialize" do dt = SmartwaiverDynamicTemplate.new expect(dt).to be_kind_of(SmartwaiverDynamicTemplate) expect(dt.data).to be_kind_of(SmartwaiverDynamicTemplateData) expect(dt.template_config).to be_kind_of(SmartwaiverDynamicTemplateConfig) expect(dt.expiration).to eq(300) end it "#initialize with non default expiration" do dt = SmartwaiverDynamicTemplate.new(30) expect(dt.expiration).to eq(30) end it "to_json default values" do dt = SmartwaiverDynamicTemplate.new json = dt.to_json expect(json).to eq(json_dynamic_template_default) end end end describe SmartwaiverTemplateMeta do describe "dynamic template meta" do it "#initialize" do meta = SmartwaiverTemplateMeta.new expect(meta.title).to be_nil expect(meta.locale).to be_nil a = meta.for_json expect(a).to eq({}) end it "#for_json" do meta = SmartwaiverTemplateMeta.new meta.title = "Test" meta.locale = "fr_FR" a = meta.for_json expect(a).to eq({'title' => 'Test', 'locale' => {"locale"=>"fr_FR"}}) end end end describe SmartwaiverTemplateHeader do describe "dynamic template header" do it "#initialize" do header = SmartwaiverTemplateHeader.new expect(header.text).to be_nil expect(header.image_base_64).to be_nil a = header.for_json expect(a).to eq({}) end it "#format_image_inline" do header = SmartwaiverTemplateHeader.new header.format_image_inline(SmartwaiverTemplateHeader::MEDIA_TYPE_PNG,"image-text-here") expect(header.image_base_64).to eq("data:image/png;base64,image-text-here") end it "#for_json" do header = SmartwaiverTemplateHeader.new header.text = "Ruby SDK Test" header.image_base_64 = "image-text-here" a = header.for_json expect(a).to eq({"text"=>"Ruby SDK Test", "logo"=>{"image"=>"image-text-here"}}) end end end describe SmartwaiverTemplateBody do describe "dynamic template body" do it "#initialize" do body = SmartwaiverTemplateBody.new expect(body.text).to be_nil a = body.for_json expect(a).to eq({}) end it "#for_json" do body = SmartwaiverTemplateBody.new body.text = "Ruby SDK Test" a = body.for_json expect(a).to eq({"text"=>"Ruby SDK Test"}) end end end describe SmartwaiverTemplateParticipants do describe "dynamic template participants" do it "#initialize" do participants = SmartwaiverTemplateParticipants.new expect(participants.adults).to eq(true) expect(participants.minors_enabled).to be_nil expect(participants.allow_multiple_minors).to be_nil expect(participants.allow_without_adults).to be_nil expect(participants.allows_adults_and_minors).to be_nil expect(participants.age_of_majority).to be_nil expect(participants.participant_label).to be_nil expect(participants.participating_text).to be_nil expect(participants.show_middle_name).to be_nil expect(participants.show_phone).to be_nil expect(participants.show_gender).to be_nil expect(participants.dob_type).to be_nil a = participants.for_json expect(a).to eq({"adults"=>true}) end it "#for_json" do participants = SmartwaiverTemplateParticipants.new participants.minors_enabled = true participants.allow_multiple_minors = true participants.allow_without_adults = false participants.allows_adults_and_minors = false participants.age_of_majority = 18 participants.participant_label = "Event Participant" participants.participating_text = "Have fun" participants.show_middle_name = false participants.show_phone = "adults" participants.show_gender = true participants.dob_type = "select" a = participants.for_json a_expected = {"adults"=>true, "minors"=>{"enabled"=>true, "multipleMinors"=>true, "minorsWithoutAdults"=>false, "adultsAndMinors" => false}, "ageOfMajority" => 18, "participantLabel" => "Event Participant", "participatingText" => "Have fun", "config"=>{"middleName"=>false, "phone"=>"adults", "gender"=>true, "dobType"=>"select"} } expect(a).to eq(a_expected) end end end describe SmartwaiverTemplateStandardQuestions do describe "dynamic template standard questions" do it "#initialize" do sq = SmartwaiverTemplateStandardQuestions.new expect(sq.address_enabled).to be_nil expect(sq.address_required).to be_nil expect(sq.default_country_code).to be_nil expect(sq.default_state_code).to be_nil expect(sq.email_verification_enabled).to be_nil expect(sq.email_marketing_enabled).to be_nil expect(sq.marketing_opt_in_text).to be_nil expect(sq.marketing_opt_in_checked).to be_nil expect(sq.emergency_contact_enabled).to be_nil expect(sq.insurance_enabled).to be_nil expect(sq.id_card_enabled).to be_nil a = sq.for_json expect(a).to eq({}) end it "#for_json" do sq = SmartwaiverTemplateStandardQuestions.new sq.address_enabled = false sq.address_required = false sq.default_country_code = 'US' sq.default_state_code = 'CA' sq.email_verification_enabled = true sq.email_marketing_enabled = true sq.marketing_opt_in_text = 'Join the mailing list' sq.marketing_opt_in_checked = true sq.emergency_contact_enabled = true sq.insurance_enabled = false sq.id_card_enabled = true a = sq.for_json a_expected = { "address"=>{"enabled"=>false, "required"=>false, "defaults"=>{"country"=>"US", "state"=>"CA"}}, "email"=>{"verification"=>true, "marketing"=>{"enabled"=>true, "optInText"=>"Join the mailing list", "defaultChecked"=>true}}, "emergencyContact" => {"enabled"=>true}, "insurance"=>{"enabled"=>true}, "idCard"=>{"enabled"=>true} } expect(a).to eq(a_expected) end end end describe SmartwaiverTemplateGuardian do describe "dynamic template guardian" do it "#initialize" do g = SmartwaiverTemplateGuardian.new expect(g.verbiage).to be_nil expect(g.verbiage_participant_addendum).to be_nil expect(g.label).to be_nil expect(g.relationship).to be_nil expect(g.age_verification).to be_nil a = g.for_json expect(a).to eq({}) end it "#for_json" do g = SmartwaiverTemplateGuardian.new g.verbiage = "Guardians are allowed with minors" g.verbiage_participant_addendum = "More legal text here" g.label = "The Guardian" g.relationship = false g.age_verification = true a = g.for_json a_expected = { "verbiage"=>"Guardians are allowed with minors", "verbiageParticipantAddendum"=>"More legal text here", "label"=>"The Guardian", "relationship"=>false, "ageVerification"=>true } expect(a).to eq(a_expected) end end end describe SmartwaiverTemplateElectronicConsent do describe "dynamic template electronic Consent" do it "#initialize" do ec = SmartwaiverTemplateElectronicConsent.new expect(ec.title).to be_nil expect(ec.verbiage).to be_nil a = ec.for_json expect(a).to eq({}) end it "#for_json" do ec = SmartwaiverTemplateElectronicConsent.new ec.title = "Electronic Consent Below" ec.verbiage = "Use the default text" a = ec.for_json a_expected = { "title"=>"Electronic Consent Below", "verbiage"=>"Use the default text" } expect(a).to eq(a_expected) end end end describe SmartwaiverTemplateStyling do describe "dynamic template styling" do it "#initialize" do s = SmartwaiverTemplateStyling.new @style = nil @custom_background_color = nil @custom_border_color = nil @custom_shadow_color = nil expect(s.style).to be_nil expect(s.custom_background_color).to be_nil expect(s.custom_border_color).to be_nil expect(s.custom_shadow_color).to be_nil a = s.for_json expect(a).to eq({}) end it "#for_json" do s = SmartwaiverTemplateStyling.new s.style = 'custom' s.custom_background_color = '#FF0000' s.custom_border_color = '#00FF00' s.custom_shadow_color = '#0000FF' a = s.for_json a_expected = { "style"=>"custom", "custom"=>{"background"=>"#FF0000", "border"=>"#00FF00", "shadow"=>"#0000FF"} } expect(a).to eq(a_expected) end end end describe SmartwaiverTemplateCompletion do describe "dynamic template completion" do it "#initialize" do c = SmartwaiverTemplateCompletion.new expect(c.redirect_success).to be_nil expect(c.redirect_cancel).to be_nil a = c.for_json expect(a).to eq({}) end it "#for_json" do c = SmartwaiverTemplateCompletion.new c.redirect_success = 'http://127.0.0.1/success' c.redirect_cancel = 'http://127.0.0.1/cancel' a = c.for_json a_expected = { "redirect"=>{"success"=>"http://127.0.0.1/success", "cancel"=>"http://127.0.0.1/cancel"} } expect(a).to eq(a_expected) end end end describe SmartwaiverTemplateSignatures do describe "dynamic template signatures" do it "#initialize" do s = SmartwaiverTemplateSignatures.new expect(s.type).to be_nil expect(s.minors).to be_nil expect(s.default_choice).to be_nil a = s.for_json expect(a).to eq({}) end it "#for_json" do s = SmartwaiverTemplateSignatures.new s.type = 'choice' s.minors = false s.default_choice ='type' a = s.for_json a_expected = { "type"=>"choice", "minors"=>false, "defaultChoice"=>"type" } expect(a).to eq(a_expected) end end end describe SmartwaiverTemplateProcessing do describe "dynamic template processing" do it "#initialize" do proc = SmartwaiverTemplateProcessing.new expect(proc.email_business_name).to be_nil expect(proc.email_reply_to).to be_nil expect(proc.email_custom_text_enabled).to be_nil expect(proc.email_custom_text_web).to be_nil expect(proc.email_cc_enabled).to be_nil expect(proc.email_cc_web_completed).to be_nil expect(proc.email_cc_addresses).to be_nil expect(proc.include_bar_codes).to be_nil a = proc.for_json expect(a).to eq({}) end it "#for_json" do proc = SmartwaiverTemplateProcessing.new proc.email_business_name = 'Smartwaiver' proc.email_reply_to = '<EMAIL>' proc.email_custom_text_enabled = true proc.email_custom_text_web = "Thanks!" proc.email_cc_enabled = true proc.email_cc_web_completed = "Online" proc.email_cc_addresses = ['<EMAIL>'] proc.include_bar_codes = true a = proc.for_json a_expected = { "emails"=>{ "businessName"=>"Smartwaiver", "replyTo"=>"<EMAIL>", "customText"=>{"enabled"=>true, "web"=>"Thanks!"}, "cc"=>{"enabled"=>true, "web"=>"Online", "emails"=>["<EMAIL>"]}, "includeBarcodes"=>true} } expect(a).to eq(a_expected) end end end describe SmartwaiverDynamicTemplateConfig do describe "dynamic template config" do it "#initialize" do dtc = SmartwaiverDynamicTemplateConfig.new expect(dtc).to be_kind_of(SmartwaiverDynamicTemplateConfig) expect(dtc.meta).to be_kind_of(SmartwaiverTemplateMeta) expect(dtc.header).to be_kind_of(SmartwaiverTemplateHeader) expect(dtc.body).to be_kind_of(SmartwaiverTemplateBody) expect(dtc.participants).to be_kind_of(SmartwaiverTemplateParticipants) expect(dtc.standard_questions).to be_kind_of(SmartwaiverTemplateStandardQuestions) expect(dtc.guardian).to be_kind_of(SmartwaiverTemplateGuardian) expect(dtc.electronic_consent).to be_kind_of(SmartwaiverTemplateElectronicConsent) expect(dtc.styling).to be_kind_of(SmartwaiverTemplateStyling) expect(dtc.completion).to be_kind_of(SmartwaiverTemplateCompletion) expect(dtc.signatures).to be_kind_of(SmartwaiverTemplateSignatures) expect(dtc.processing).to be_kind_of(SmartwaiverTemplateProcessing) end it "#for_json" do dtc = SmartwaiverDynamicTemplateConfig.new a = dtc.for_json a_expected = { "body" => {}, "completion" => {}, "electronicConsent" => {}, "guardian" => {}, "header" => {}, "meta" => {}, "participants" => {"adults"=>true}, "processing" => {}, "signatures" => {}, "standardQuestions" => {}, "styling" => {} } expect(a).to eq(a_expected) end end end
smartwaivercom/ruby-sdk
examples/search/search_params.rb
<filename>examples/search/search_params.rb # # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/search_client' # The API Key for your account api_key='[INSERT API KEY]' begin client = SmartwaiverSearchClient.new(api_key) template_id='[INSERT TEMPLATE ID]' results = client.search(template_id) # Request all waivers signed for this template after the given date # results = client.search(template_id, '2017-01-01 00:00:00') # Request all waivers signed for this template with a participant name Kyle # results = client.search(template_id, '', '', 'Kyle') # Request all waivers signed for this template with a participant name <NAME> # results = client.search(template_id, '', '', 'Kyle', 'Smith') # Request all waivers signed with a participant name Kyle that have been email verified # results = client.search(template_id, '', '', 'Kyle', '', true) # Request all waivers signed in ascending sorted order # results = client.search(template_id, '', '', '', '', '', false) # Request all waivers with a primary tag of 'testing' # results = client.search(template_id, '', '', '', '', '', true, 'testing') search = results[:search] # Print out some information about the result of the search puts "Search Complete:" puts " Search ID: #{search[:guid]}" puts " Waiver Count: #{search[:count]}" puts " #{search[:pages]} pages of size #{search[:pageSize]}" puts "" rescue SmartwaiverSDK::BadAPIKeyError=>bad puts "API Key error: #{bad.message}" rescue Exception=>e puts "Exception thrown. Error during queue information: #{e.message}" end
smartwaivercom/ruby-sdk
spec/smartwaiver-sdk/user_client_spec.rb
<gh_stars>1-10 dir = File.dirname(__FILE__) require "#{dir}/../spec_helper" require "#{dir}/../../lib/smartwaiver-sdk/user_client" describe SmartwaiverUserClient do attr_reader :client, :api_key before do FakeWeb.allow_net_connect = false @api_key = "apikey" @client = SmartwaiverUserClient.new(@api_key) end describe "user settings" do it "#initialize" do expect(@client).to be_kind_of(SmartwaiverUserClient) end it "#settings" do path="#{API_URL}/v4/settings" FakeWeb.register_uri(:get, path, :body => json_user_settings_results) response = @client.settings() expect(response[:settings][:console][:staticExpiration]).to eq("never") expect(response[:settings][:console][:rollingExpiration]).to eq("never") expect(response[:settings][:console][:rollingExpirationTime]).to eq("signed") end end end
smartwaivercom/ruby-sdk
lib/smartwaiver-sdk/dynamic_template_data.rb
# # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/smartwaiver_base' class SmartwaiverDynamicTemplateData attr_accessor :adult, :participants, :guardian, :address_line_one, :address_line_two, :address_country, :address_state, :address_zip, :email, :emergency_contact_name, :emergency_contact_phone, :insurance_carrier, :insurance_policy_number, :drivers_license_state, :drivers_license_number def initialize(adult = true) @adult = adult @participants = [] @guardian = SmartwaiverGuardian.new @address_line_one = nil @address_line_two = nil @address_country = nil @address_state = nil @address_zip = nil @email = nil @emergency_contact_name = nil @emergency_contact_phone = nil @insurance_carrier = nil @insurance_policy_number = nil @drivers_license_state = nil @drivers_license_number = nil end def add_participant(participant) @participants.push(participant) end def for_json participants_for_json = [] @participants.each do |participant| participants_for_json.push(participant.for_json) end json = {} json['adult'] = @adult json['participants'] = participants_for_json json['guardian'] = @guardian.for_json json['addressLineOne'] = @address_line_one if (!@address_line_one.nil?) json['addressLineTwo'] = @address_line_two if (!@address_line_two.nil?) json['addressCountry'] = @address_country if (!@address_country.nil?) json['addressState'] = @address_state if (!@address_state.nil?) json['addressZip'] = @address_zip if (!@address_zip.nil?) json['email'] = @email if (!@email.nil?) json['emergencyContactName'] = @emergency_contact_name if (!@emergency_contact_name.nil?) json['emergencyContactPhone'] = @emergency_contact_phone if (!@emergency_contact_phone.nil?) json['insuranceCarrier'] = @insurance_carrier if (!@insurance_carrier.nil?) json['insurancePolicyNumber'] = @insurance_policy_number if (!@insurance_policy_number.nil?) json['driversLicenseState'] = @drivers_license_state if (!@drivers_license_state.nil?) json['driversLicenseNumber'] = @drivers_license_number if (!@drivers_license_number.nil?) json end end class SmartwaiverParticipant attr_accessor :first_name, :middle_name, :last_name, :phone, :gender, :dob def initialize() @first_name = nil @middle_name = nil @last_name = nil @phone = nil @gender = nil @dob = nil end def for_json json = {} json['firstName'] = @first_name if (!@first_name.nil?) json['middleName'] = @middle_name if (!@middle_name.nil?) json['lastName'] = @last_name if (!@last_name.nil?) json['phone'] = @phone if (!@phone.nil?) json['gender'] = @gender if (!@gender.nil?) json['dob'] = @dob if (!@dob.nil?) json end end class SmartwaiverGuardian attr_accessor :participant, :first_name, :middle_name, :last_name, :relationship, :phone, :gender, :dob def initialize(participant = false) @participant = participant @first_name = nil @middle_name = nil @last_name = nil @relationship = nil @phone = nil @gender = nil @dob = nil end def for_json json = {} json['participant'] = @participant if (!@participant.nil?) json['firstName'] = @first_name if (!@first_name.nil?) json['middleName'] = @middle_name if (!@middle_name.nil?) json['lastName'] = @last_name if (!@last_name.nil?) json['relationship'] = @relationship if (!@relationship.nil?) json['phone'] = @phone if (!@phone.nil?) json['gender'] = @gender if (!@gender.nil?) json['dob'] = @dob if (!@dob.nil?) json end end
smartwaivercom/ruby-sdk
spec/smartwaiver-sdk/base_spec.rb
dir = File.dirname(__FILE__) require "#{dir}/../spec_helper" require "#{dir}/../../lib/smartwaiver-sdk/smartwaiver_base" class SmartwaiverTest < SmartwaiverSDK::SmartwaiverBase def get_test(path) make_api_request(path, HTTP_GET) end def post_test(path, data) make_api_request(path, HTTP_POST, data) end def put_test(path, data) make_api_request(path, HTTP_PUT, data) end def delete_test(path) make_api_request(path, HTTP_DELETE) end def parse_response_body_test(data) parse_response_body(data) end def check_response_test(response) check_response(response) end def create_query_string_test(params) create_query_string(params) end end describe SmartwaiverSDK::SmartwaiverBase do before do FakeWeb.allow_net_connect = false @api_key = "apikey" end describe "smartwaiver base object set up correctly" do it "has correct headers and accepts a custom endpoint" do test_endpoint = 'https://testapi.smartwaiver.com' client = SmartwaiverSDK::SmartwaiverBase.new(@api_key, test_endpoint) expect(client.instance_eval('@http').address).to eq("testapi.smartwaiver.com") end end describe "#version" do it "retrieves the current version of the API" do FakeWeb.register_uri(:get, "https://api.smartwaiver.com/version", :body => json_api_version_results) client = SmartwaiverSDK::SmartwaiverBase.new(@api_key) version = client.api_version expect(version[:version]).to eq(SmartwaiverSDK::VERSION) end end describe "#make_api_request" do before do @client = SmartwaiverTest.new(@api_key) end it "GET" do path = "#{API_URL}/get_test" FakeWeb.register_uri(:get, path, :body => json_base_results) @client.get_test(path) request = FakeWeb.last_request expect(request.method).to eq("GET") expect(request.body).to eq(nil) request.each_header do |key, value| case key when "user-agent" expect(value).to match(/^SmartwaiverAPI*/) when "sw-api-key" expect(value).to eq(@api_key) end end end it "POST" do path = "#{API_URL}/post_test" data = "{\"json\":\"data\"}" FakeWeb.register_uri(:post, path, :body => json_base_results) @client.post_test(path, data) request = FakeWeb.last_request expect(request.method).to eq("POST") expect(request.body).to eq(data) request.each_header do |key, value| case key when "user-agent" expect(value).to match(/^SmartwaiverAPI*/) when "sw-api-key" expect(value).to eq(@api_key) when "content-type" expect(value).to eq("application/json") end end end it "PUT" do path = "#{API_URL}/put_test" data = "{\"json\":\"data\"}" FakeWeb.register_uri(:put, path, :body => json_base_results) @client.put_test(path, data) request = FakeWeb.last_request expect(request.method).to eq("PUT") expect(request.body).to eq(data) request.each_header do |key, value| case key when "user-agent" expect(value).to match(/^SmartwaiverAPI*/) when "sw-api-key" expect(value).to eq(@api_key) when "content-type" expect(value).to eq("application/json") end end end it "DELETE" do path = "#{API_URL}/delete_test" FakeWeb.register_uri(:delete, path, :body => json_base_results) @client.delete_test(path) request = FakeWeb.last_request expect(request.method).to eq("DELETE") request.each_header do |key, value| case key when "user-agent" expect(value).to match(/^SmartwaiverAPI*/) when "sw-api-key" expect(value).to eq(@api_key) end end end end describe "#parse_response_body" do before do @client = SmartwaiverTest.new(@api_key) end it "parses valid json" do json = '{"version":4, "id":"8e82fa534da14b76a05013644ee735d2", "ts":"2017-01-17T15:46:58+00:00", "type":"test"}' data = @client.parse_response_body_test(json) expect(data[:version]).to eq(4) expect(data[:id]).to eq("8e82fa534da14b76a05013644ee735d2") expect(data[:ts]).to eq("2017-01-17T15:46:58+00:00") expect(data[:type]).to eq("test") end it "returns base parameters if json is invalid" do json = 'bad-json' data = @client.parse_response_body_test(json) expect(data[:version]).to eq(0) expect(data[:id]).to eq("") expect(data[:ts]).to eq("1970-01-01T00:00:00+00:00") expect(data[:type]).to eq("") end end describe "#create_query_string" do before do @client = SmartwaiverTest.new(@api_key) end it "create a valid query string" do params = {:a => "first", :b => "with space"} query_string = @client.create_query_string_test(params) expect(query_string).to eq("a=first&b=with+space") end end describe "#check_response" do it "HTTP 200" do path = "#{API_URL}/get_test" FakeWeb.register_uri(:get, path, :body => json_base_results) uri = URI.parse(path) Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |req| response = req.get('/get_test') @client = SmartwaiverTest.new(@api_key) expect {@client.check_response_test(response)}.to_not raise_error end end it "HTTP Unauthorized" do path = "#{API_URL}/error_test" FakeWeb.register_uri(:get, path, :body => json_base_results, :status => ["401", "Unauthorized"]) uri = URI.parse(path) Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |req| response = req.get('/error_test') @client = SmartwaiverTest.new(@api_key) expect {@client.check_response_test(response)}.to raise_error(SmartwaiverSDK::BadAPIKeyError) end end it "HTTP NotAcceptable" do path = "#{API_URL}/error_test" FakeWeb.register_uri(:get, path, :body => json_base_results, :status => ["406", "Not Acceptable"]) uri = URI.parse(path) Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |req| response = req.get('/error_test') @client = SmartwaiverTest.new(@api_key) expect {@client.check_response_test(response)}.to raise_error(SmartwaiverSDK::BadFormatError) end end it "HTTP Client Error" do path = "#{API_URL}/error_test" FakeWeb.register_uri(:get, path, :body => json_base_results, :status => ["404", "Not Found"]) uri = URI.parse(path) Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |req| response = req.get('/error_test') @client = SmartwaiverTest.new(@api_key) expect {@client.check_response_test(response)}.to raise_error(SmartwaiverSDK::RemoteServerError) end end it "HTTP Server Error" do path = "#{API_URL}/error_test" FakeWeb.register_uri(:get, path, :body => json_base_results, :status => ["500", "Internal Server Error"]) uri = URI.parse(path) Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |req| response = req.get('/error_test') @client = SmartwaiverTest.new(@api_key) expect {@client.check_response_test(response)}.to raise_error(SmartwaiverSDK::RemoteServerError) end end end end
smartwaivercom/ruby-sdk
lib/smartwaiver-sdk/dynamic_template.rb
# # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/smartwaiver_base' require 'smartwaiver-sdk/dynamic_template_data' class SmartwaiverDynamicTemplate EXPIRATION_DEFAULT = 300 attr_accessor :expiration, :template_config, :data def initialize(expiration = EXPIRATION_DEFAULT) @expiration = expiration @template_config = SmartwaiverDynamicTemplateConfig.new @data = SmartwaiverDynamicTemplateData.new end def to_json {:template => @template_config.for_json, :data => @data.for_json}.to_json end end class SmartwaiverDynamicTemplateConfig attr_accessor :meta, :header, :body, :participants, :standard_questions, :guardian, :electronic_consent, :styling, :completion, :signatures, :processing def initialize() @meta = SmartwaiverTemplateMeta.new @header = SmartwaiverTemplateHeader.new @body = SmartwaiverTemplateBody.new @participants = SmartwaiverTemplateParticipants.new @standard_questions = SmartwaiverTemplateStandardQuestions.new @guardian = SmartwaiverTemplateGuardian.new @electronic_consent = SmartwaiverTemplateElectronicConsent.new @styling = SmartwaiverTemplateStyling.new @completion = SmartwaiverTemplateCompletion.new @signatures = SmartwaiverTemplateSignatures.new @processing = SmartwaiverTemplateProcessing.new end def for_json { 'meta' => @meta.for_json, 'header' => @header.for_json, 'body' => @body.for_json, 'participants' => @participants.for_json, 'standardQuestions' => @standard_questions.for_json, 'guardian' => @guardian.for_json, 'electronicConsent' => @electronic_consent.for_json, 'styling' => @styling.for_json, 'completion' => @completion.for_json, 'signatures' => @signatures.for_json, 'processing' => @processing.for_json } end end class SmartwaiverTemplateMeta attr_accessor :title, :locale def initialize() @title = nil @locale = nil end def for_json json = {} json['title'] = @title if (!@title.nil?) json['locale'] = {'locale' => @locale} if (!@locale.nil?) json end end class SmartwaiverTemplateHeader MEDIA_TYPE_PNG = 'image/png' MEDIA_TYPE_JPEG = 'image/jpeg' attr_accessor :text, :image_base_64 def initialize() @text = nil @image_base_64 = nil end def format_image_inline(media_type, encoded_image) @image_base_64 = "data:#{media_type};base64,#{encoded_image}" end def for_json json = {} json['text'] = @text if (!@text.nil?) json['logo'] = {'image' => @image_base_64} if (!@image_base_64.nil?) json end end class SmartwaiverTemplateBody attr_accessor :text def initialize() @text = nil end def for_json json = {} json['text'] = @text if (!@text.nil?) json end end class SmartwaiverTemplateParticipants ADULTS_AND_MINORS = 'adultsAndMinors' MINORS_WITHOUT_ADULTS = 'minorsWithoutAdults' PHONE_ADULTS_ONLY = 'adults' PHOHE_ADULTS_AND_MINORS = 'adultsAndMinors' DOB_CHECKBOX = 'checkbox' DOB_SELECT = 'select' attr_accessor :adults, :minors_enabled, :allow_multiple_minors, :allow_without_adults, :allows_adults_and_minors, :age_of_majority, :participant_label, :participating_text, :show_middle_name, :show_phone, :show_gender, :dob_type def initialize() @adults = true @minors_enabled = nil @allow_multiple_minors = nil @allow_without_adults = nil @allows_adults_and_minors = nil @age_of_majority = nil @participant_label = nil @participating_text = nil @show_middle_name = nil @show_phone = nil @show_gender = nil @dob_type = nil end def for_json json = {} json['adults'] = @adults if (!@adults.nil?) minors = {} minors['enabled'] = @minors_enabled if (!@minors_enabled.nil?) minors['multipleMinors'] = @allow_multiple_minors if (!@allow_multiple_minors.nil?) minors['minorsWithoutAdults'] = @allow_without_adults if (!@allow_without_adults.nil?) minors['adultsAndMinors'] = @allows_adults_and_minors if (!@allows_adults_and_minors.nil?) json['minors'] = minors if (minors != {}) json['ageOfMajority'] = @age_of_majority if (!@age_of_majority.nil?) json['participantLabel'] = @participant_label if (!@participant_label.nil?) json['participatingText'] = @participating_text if (!@participating_text.nil?) config = {} config['middleName'] = @show_middle_name if (!@show_middle_name.nil?) config['phone'] = @show_phone if (!@show_phone.nil?) config['gender'] = @show_gender if (!@show_gender.nil?) config['dobType'] = @dob_type if (!@dob_type.nil?) json['config'] = config if (config != {}) json end end class SmartwaiverTemplateStandardQuestions attr_accessor :address_enabled, :address_required, :default_country_code, :default_state_code, :email_verification_enabled, :email_marketing_enabled, :marketing_opt_in_text, :marketing_opt_in_checked, :emergency_contact_enabled, :insurance_enabled, :id_card_enabled def initialize() @address_enabled = nil @address_required = nil @default_country_code = nil @default_state_code = nil @email_verification_enabled = nil @email_marketing_enabled = nil @marketing_opt_in_text = nil @marketing_opt_in_checked = nil @emergency_contact_enabled = nil @insurance_enabled = nil @id_card_enabled = nil end def for_json json = {} address = {} address['enabled'] = @address_enabled if (!@address_enabled.nil?) address['required'] = @address_required if (!@address_required.nil?) defaults = {} defaults['country'] = @default_country_code if (!@default_country_code.nil?) defaults['state'] = @default_state_code if (!@default_state_code.nil?) address['defaults'] = defaults if (defaults != {}) json['address'] = address if (address != {}) email = {} email['verification'] = @email_verification_enabled if (!@email_verification_enabled.nil?) email_marketing = {} email_marketing['enabled'] = @email_marketing_enabled if (!@email_marketing_enabled.nil?) email_marketing['optInText'] = @marketing_opt_in_text if (!@marketing_opt_in_text.nil?) email_marketing['defaultChecked'] = @marketing_opt_in_checked if (!@marketing_opt_in_checked.nil?) email['marketing'] = email_marketing if (email_marketing != {}) json['email'] = email if (email != {}) emergency_contact = {} emergency_contact['enabled'] = @emergency_contact_enabled if (!@emergency_contact_enabled.nil?) json['emergencyContact'] = emergency_contact if (emergency_contact != {}) insurance = {} insurance['enabled'] = @insurance_enabled if (!@insurance_enabled.nil?) json['insurance'] = emergency_contact if (emergency_contact != {}) id_card = {} id_card['enabled'] = @id_card_enabled if (!@id_card_enabled.nil?) json['idCard'] = id_card if (id_card != {}) json end end class SmartwaiverTemplateGuardian attr_accessor :verbiage, :verbiage_participant_addendum, :label, :relationship, :age_verification def initialize() @verbiage = nil @verbiage_participant_addendum = nil @label = nil @relationship = nil @age_verification = nil end def for_json json = {} json['verbiage'] = @verbiage if (!@verbiage.nil?) json['verbiageParticipantAddendum'] = @verbiage_participant_addendum if (!@verbiage_participant_addendum.nil?) json['label'] = @label if (!@label.nil?) json['relationship'] = @relationship if (!@relationship.nil?) json['ageVerification'] = @age_verification if (!@age_verification.nil?) json end end class SmartwaiverTemplateElectronicConsent attr_accessor :title, :verbiage def initialize() @title = nil @verbiage = nil end def for_json json = {} json['title'] = @title if (!@title.nil?) json['verbiage'] = @verbiage if (!@verbiage.nil?) json end end class SmartwaiverTemplateStyling attr_accessor :style, :custom_background_color, :custom_border_color, :custom_shadow_color def initialize() @style = nil @custom_background_color = nil @custom_border_color = nil @custom_shadow_color = nil end def for_json json = {} json['style'] = @style if (!@style.nil?) custom = {} custom['background'] = @custom_background_color if (!@custom_background_color.nil?) custom['border'] = @custom_border_color if (!@custom_border_color.nil?) custom['shadow'] = @custom_shadow_color if (!@custom_shadow_color.nil?) json['custom'] = custom if (custom != {}) json end end class SmartwaiverTemplateCompletion attr_accessor :redirect_success, :redirect_cancel def initialize() @redirect_success = nil @redirect_cancel = nil end def for_json json = {} redirect = {} redirect['success'] = @redirect_success if (!@redirect_success.nil?) redirect['cancel'] = @redirect_cancel if (!@redirect_cancel .nil?) json['redirect'] = redirect if (redirect != {}) json end end class SmartwaiverTemplateSignatures SIGNATURE_DRAW = 'draw' SIGNATURE_TYPE = 'type' SIGNATURE_CHOICE = 'choice' attr_accessor :type, :minors, :default_choice def initialize() @type = nil @minors = nil @default_choice = nil end def for_json json = {} json['type'] = @type if (!@type.nil?) json['minors'] = @minors if (!@minors.nil?) json['defaultChoice'] = @default_choice if (!@default_choice.nil?) json end end class SmartwaiverTemplateProcessing attr_accessor :email_business_name, :email_reply_to, :email_custom_text_enabled, :email_custom_text_web, :email_cc_enabled, :email_cc_web_completed, :email_cc_addresses, :include_bar_codes def initialize() @email_business_name = nil @email_reply_to = nil @email_custom_text_enabled = nil @email_custom_text_web = nil @email_cc_enabled = nil @email_cc_web_completed = nil @email_cc_addresses = nil @include_bar_codes = nil end def for_json json = {} emails = {} emails['businessName'] = @email_business_name if (!@email_business_name.nil?) emails['replyTo'] = @email_reply_to if (!@email_reply_to.nil?) customText = {} customText['enabled'] = @email_custom_text_enabled if (!@email_custom_text_enabled.nil?) customText['web'] = @email_custom_text_web if (!@email_custom_text_web.nil?) emails['customText'] = customText if (customText != {}) cc = {} cc['enabled'] = @email_cc_enabled if (!@email_cc_enabled.nil?) cc['web'] = @email_cc_web_completed if (!@email_cc_web_completed.nil?) cc['emails'] = @email_cc_addresses if (!@email_cc_addresses.nil?) emails['cc'] = cc if (cc != {}) emails['includeBarcodes'] = @include_bar_codes if (!@include_bar_codes.nil?) json['emails'] = emails if (emails != {}) json end end
smartwaivercom/ruby-sdk
examples/templates/retrieve_single_template.rb
<filename>examples/templates/retrieve_single_template.rb # # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/template_client' # The API Key for your account api_key='[INSERT API KEY]' # The Template ID template_id='[INSERT TEMPLATE ID]' client = SmartwaiverTemplateClient.new(api_key) begin result = client.get(template_id) template = result[:template] puts "List single template:" puts "#{template[:templateId]}: #{template[:title]}" rescue SmartwaiverSDK::BadAPIKeyError=>bad puts "API Key error: #{bad.message}" rescue Exception=>e puts "Exception thrown. Error during template retrieval: #{e.message}" end
smartwaivercom/ruby-sdk
spec/smartwaiver-sdk/webhook_queues_client_spec.rb
dir = File.dirname(__FILE__) require "#{dir}/../spec_helper" require "#{dir}/../../lib/smartwaiver-sdk/webhook_queues_client" describe SmartwaiverWebhookQueuesClient do attr_reader :client, :api_key before do FakeWeb.allow_net_connect = false @api_key = "apikey" @client = SmartwaiverWebhookQueuesClient.new(@api_key) end describe "webhook_queues" do it "#initialize" do expect(@client).to be_kind_of(SmartwaiverWebhookQueuesClient) end it "#information" do path="#{API_URL}/v4/webhooks/queues" FakeWeb.register_uri(:get, path, :body => json_webhook_queues_information_results) response = @client.information expect(response[:type]).to eq('api_webhook_all_queue_message_count') expect(response[:api_webhook_all_queue_message_count][:account][:messagesTotal]).to eq(2) expect(response[:api_webhook_all_queue_message_count][:'template-4fc7d12601941'][:messagesTotal]).to eq(4) end it "#get_message" do path="#{API_URL}/v4/webhooks/queues/account" FakeWeb.register_uri(:get, path, :body => json_webhook_queues_get_message_results) response = @client.get_message expect(response[:type]).to eq('api_webhook_account_message_get') expect(response[:api_webhook_account_message_get][:messageId]).to eq('9d58e8fc-6353-4ceb-b0a3-5412f3d05e28') expect(response[:api_webhook_account_message_get][:payload][:unique_id]).to eq('xyz') expect(response[:api_webhook_account_message_get][:payload][:event]).to eq('new-waiver') end it "#delete_message" do message_id = 'x-y-z' path="#{API_URL}/v4/webhooks/queues/account/#{message_id}" FakeWeb.register_uri(:delete, path, :body => json_webhook_queues_delete_message_results) response = @client.delete_message(message_id) expect(response[:type]).to eq('api_webhook_account_message_delete') expect(response[:api_webhook_account_message_delete][:success]).to eq(true) end it "#get_template_message" do template_id = 't1' path="#{API_URL}/v4/webhooks/queues/template/#{template_id}" FakeWeb.register_uri(:get, path, :body => json_webhook_queues_template_get_message_results) response = @client.get_template_message(template_id) expect(response[:type]).to eq('api_webhook_template_message_get') expect(response[:api_webhook_template_message_get][:messageId]).to eq('9d58e8fc-6353-4ceb-b0a3-5412f3d05e28') expect(response[:api_webhook_template_message_get][:payload][:unique_id]).to eq('xyz') expect(response[:api_webhook_template_message_get][:payload][:event]).to eq('new-waiver') end it "#delete_template_message" do template_id = 't1' message_id = 'x-y-z' path="#{API_URL}/v4/webhooks/queues/template/#{template_id}/#{message_id}" FakeWeb.register_uri(:delete, path, :body => json_webhook_queues_template_delete_message_results) response = @client.delete_template_message(template_id, message_id) expect(response[:type]).to eq('api_webhook_template_message_delete') expect(response[:api_webhook_template_message_delete][:success]).to eq(true) end end end
smartwaivercom/ruby-sdk
spec/smartwaiver-sdk/search_client_spec.rb
<reponame>smartwaivercom/ruby-sdk dir = File.dirname(__FILE__) require "#{dir}/../spec_helper" require "#{dir}/../../lib/smartwaiver-sdk/search_client" describe SmartwaiverSearchClient do attr_reader :client, :api_key before do FakeWeb.allow_net_connect = false @api_key = "apikey" @client = SmartwaiverSearchClient.new(@api_key) end describe "keys" do it "#initialize" do expect(@client).to be_kind_of(SmartwaiverSearchClient) end it "#search empty" do path="#{API_URL}/v4/search" FakeWeb.register_uri(:get, path, :body => json_search_1_results) response = @client.search() expect(response[:search][:guid]).to eq("6jebdfxzvrdkd") expect(response[:search][:count]).to eq(652) expect(response[:search][:pages]).to eq(7) expect(response[:search][:pageSize]).to eq(100) end it "#search all params" do path="#{API_URL}/v4/search?templateId=xyz&fromDts=2018-01-01&toDts=2018-02-01&firstName=Rocky&lastName=RockChuck&verified=true&sort=asc&tag=new+customer" FakeWeb.register_uri(:get, path, :body => json_search_1_results) response = @client.search('xyz','2018-01-01', '2018-02-01','Rocky','RockChuck',true, SmartwaiverSearchClient::SEARCH_SORT_ASC, 'new customer') expect(response[:search][:guid]).to eq("6jebdfxzvrdkd") expect(response[:search][:count]).to eq(652) expect(response[:search][:pages]).to eq(7) expect(response[:search][:pageSize]).to eq(100) end it "#results" do path="#{API_URL}/v4/search/6jebdfxzvrdkd/results?page=1" FakeWeb.register_uri(:get, path, :body => json_search_2_results) response = @client.results('6jebdfxzvrdkd', 1) expect(response[:search_results].length).to eq(1) end end end
smartwaivercom/ruby-sdk
lib/smartwaiver-sdk/search_client.rb
<reponame>smartwaivercom/ruby-sdk # # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/smartwaiver_base' class SmartwaiverSearchClient < SmartwaiverSDK::SmartwaiverBase EMPTY_SEARCH_PARAMETER = '' SEARCH_SORT_ASC = 'asc' SEARCH_SORT_DESC = 'desc' def initialize(api_key, api_endpoint = DEFAULT_API_ENDPOINT) super(api_key, api_endpoint) @rest_endpoints = define_rest_endpoints end def search(template_id = EMPTY_SEARCH_PARAMETER, from_dts = EMPTY_SEARCH_PARAMETER, to_dts = EMPTY_SEARCH_PARAMETER, first_name = EMPTY_SEARCH_PARAMETER, last_name = EMPTY_SEARCH_PARAMETER, verified = EMPTY_SEARCH_PARAMETER, sort = EMPTY_SEARCH_PARAMETER, tag = EMPTY_SEARCH_PARAMETER) qs = {} qs[:templateId] = template_id if (template_id != EMPTY_SEARCH_PARAMETER) qs[:fromDts] = from_dts if (from_dts != EMPTY_SEARCH_PARAMETER) qs[:toDts] = to_dts if (to_dts != EMPTY_SEARCH_PARAMETER) qs[:firstName] = first_name if (first_name != EMPTY_SEARCH_PARAMETER) qs[:lastName] = last_name if (last_name != EMPTY_SEARCH_PARAMETER) qs[:verified] = verified if (verified != EMPTY_SEARCH_PARAMETER) qs[:sort] = sort if (sort != EMPTY_SEARCH_PARAMETER) qs[:tag] = tag if (tag != EMPTY_SEARCH_PARAMETER) path = @rest_endpoints[:search] + (qs != {} ? ('?' + create_query_string(qs)) : '') make_api_request(path, HTTP_GET) end def results(search_guid, page = 0) path = "#{@rest_endpoints[:search]}/#{search_guid}/results?page=#{page}" make_api_request(path, HTTP_GET) end private def define_rest_endpoints { :search => "/v4/search" } end end
smartwaivercom/ruby-sdk
spec/smartwaiver-sdk/webhook_client_spec.rb
dir = File.dirname(__FILE__) require "#{dir}/../spec_helper" require "#{dir}/../../lib/smartwaiver-sdk/webhook_client" describe SmartwaiverWebhookClient do attr_reader :client, :api_key before do FakeWeb.allow_net_connect = false @api_key = "apikey" @client = SmartwaiverWebhookClient.new(@api_key) end describe "webhooks" do it "#initialize" do expect(@client).to be_kind_of(SmartwaiverWebhookClient) end it "#configuration" do path="#{API_URL}/v4/webhooks/configure" FakeWeb.register_uri(:get, path, :body => json_webhook_configuration_results) response = @client.configuration expect(response[:webhooks].length).to eq(2) end it "#configure" do endpoint="http://requestb.in/1ajthro1" email_validation_required="yes" path="#{API_URL}/v4/webhooks/configure" FakeWeb.register_uri(:put, path, :body => json_webhook_configuration_results) response = @client.configure(endpoint, email_validation_required) expect(response[:webhooks][:endpoint]).to eq(endpoint) expect(response[:webhooks][:emailValidationRequired]).to eq(email_validation_required) end it "#delete" do path="#{API_URL}/v4/webhooks/configure" FakeWeb.register_uri(:delete, path, :body => json_webhook_delete_results) response = @client.delete expect(response[:webhooks]).to eq({}) end it "#resend" do waiver_id = 'xyz' path="#{API_URL}/v4/webhooks/resend/#{waiver_id}" FakeWeb.register_uri(:put, path, :body => json_webhook_resend_results) response = @client.resend(waiver_id) expect(response[:webhooks_resend][:success]).to eq(true) end end end
smartwaivercom/ruby-sdk
examples/queues/retrieve_account_message.rb
# # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/webhook_queues_client' # The API Key for your account api_key='<API_KEY>' client = SmartwaiverWebhookQueuesClient.new(api_key) begin result = client.get_message message = result[:api_webhook_account_message_get] if (message.nil?) puts "No messages in account queue" Kernel.exit(1) end puts "Message in Account Queue" puts " Message ID: #{message[:messageId]}" puts " Message Payload" puts " Waiver ID: #{message[:payload][:unique_id]}" puts " Event : #{message[:payload][:event]}" # # Now that we have retrieved the message we can delete it delete_result = client.delete_message(message[:messageId]) puts "Delete Success:" + (delete_result[:api_webhook_account_message_delete][:success] ? "true" : "false") rescue SmartwaiverSDK::BadAPIKeyError=>bad puts "API Key error: #{bad.message}" rescue SystemExit => se puts "" rescue Exception=>e puts "Exception thrown. Error during queue information: #{e.message}" end
smartwaivercom/ruby-sdk
lib/smartwaiver-sdk/template_client.rb
<filename>lib/smartwaiver-sdk/template_client.rb # # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/smartwaiver_base' class SmartwaiverTemplateClient < SmartwaiverSDK::SmartwaiverBase def initialize(api_key, api_endpoint = DEFAULT_API_ENDPOINT) super(api_key, api_endpoint) @rest_endpoints = define_rest_endpoints end def list path = @rest_endpoints[:configure] make_api_request(path, HTTP_GET) end def get(template_id) path = "#{@rest_endpoints[:configure]}/#{template_id}" make_api_request(path, HTTP_GET) end private def define_rest_endpoints { :configure => "/v4/templates" } end end
smartwaivercom/ruby-sdk
lib/smartwaiver-sdk/dynamic_template_client.rb
# # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/smartwaiver_base' class SmartwaiverDynamicTemplateClient < SmartwaiverSDK::SmartwaiverBase def initialize(api_key, api_endpoint = DEFAULT_API_ENDPOINT) super(api_key, api_endpoint) @rest_endpoints = define_rest_endpoints end def create(template) path = @rest_endpoints[:create] json = {:dynamic => {:expiration => template.expiration, :template => template.template_config.for_json, :data => template.data.for_json}}.to_json make_api_request(path, HTTP_POST, json) end def process(transaction_id) path = "#{@rest_endpoints[:process]}/#{transaction_id}" json = {}.to_json make_api_request(path, HTTP_POST, json) end private def define_rest_endpoints { :create => "/v4/dynamic/templates", :process => "/v4/dynamic/process" } end end
smartwaivercom/ruby-sdk
examples/queues/retrieve_webhook_queues.rb
<reponame>smartwaivercom/ruby-sdk # # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/webhook_queues_client' # The API Key for your account api_key='<API_KEY>' client = SmartwaiverWebhookQueuesClient.new(api_key) begin result = client.information queue_information = result[:api_webhook_all_queue_message_count] if (queue_information.nil?) puts "Account Queue: N/A" else puts "Account Queue" puts " Total Messages : #{queue_information[:account][:messagesTotal]}" puts " Messages Not Visible: #{queue_information[:account][:messagesNotVisible]}" puts " Messages Delayed : #{queue_information[:account][:messagesDelayed]}" queue_information.keys.each do |k| if k.match(/^template/) template_queue_info = queue_information[k] puts "Template Queue (#{k}):" puts " Total Messages : #{template_queue_info[:messagesTotal]}" puts " Messages Not Visible: #{template_queue_info[:messagesNotVisible]}" puts " Messages Delayed : #{template_queue_info[:messagesDelayed]}" end end end rescue SmartwaiverSDK::BadAPIKeyError=>bad puts "API Key error: #{bad.message}" rescue Exception=>e puts "Exception thrown. Error during queue information: #{e.message}" end
smartwaivercom/ruby-sdk
lib/smartwaiver-sdk/webhook_client.rb
<reponame>smartwaivercom/ruby-sdk<gh_stars>1-10 # # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/smartwaiver_base' class SmartwaiverWebhookClient < SmartwaiverSDK::SmartwaiverBase WEBHOOK_AFTER_EMAIL_ONLY = 'yes' WEBHOOK_BEFORE_EMAIL_ONLY = 'no' WEBHOOK_BEFORE_AND_AFTER_EMAIL = 'both' def initialize(api_key, api_endpoint = DEFAULT_API_ENDPOINT) super(api_key, api_endpoint) @rest_endpoints = define_rest_endpoints end def configuration path = @rest_endpoints[:configure] make_api_request(path, HTTP_GET) end def configure(endpoint, email_validation_required) path = @rest_endpoints[:configure] json = {:endpoint => endpoint, :emailValidationRequired => email_validation_required}.to_json make_api_request(path, HTTP_PUT, json) end def delete path = @rest_endpoints[:configure] make_api_request(path, HTTP_DELETE) end def resend(waiver_id) path = "#{@rest_endpoints[:resend]}/#{waiver_id}" json = {}.to_json make_api_request(path, HTTP_PUT, json) end private def define_rest_endpoints { :configure => "/v4/webhooks/configure", :resend => "/v4/webhooks/resend" } end end
smartwaivercom/ruby-sdk
lib/smartwaiver-sdk.rb
<gh_stars>1-10 dir = File.dirname(__FILE__) require 'net/https' require 'uri' require 'cgi' require "#{dir}/smartwaiver-sdk/smartwaiver_errors" require "#{dir}/smartwaiver-sdk/smartwaiver_base" require "#{dir}/smartwaiver-sdk/smartwaiver_version"
smartwaivercom/ruby-sdk
lib/smartwaiver-sdk/smartwaiver_errors.rb
# # Copyright 2018 Smartwaiver # # 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. module SmartwaiverSDK class SmartwaiverError < StandardError attr_reader :result def initialize(message, result={}) super(message) @result = result end end class BadAPIKeyError < SmartwaiverError end class BadFormatError < SmartwaiverError end class RemoteServerError < SmartwaiverError end end
smartwaivercom/ruby-sdk
spec/smartwaiver-sdk/dynamic_template_data_spec.rb
<reponame>smartwaivercom/ruby-sdk dir = File.dirname(__FILE__) require "#{dir}/../spec_helper" require "#{dir}/../../lib/smartwaiver-sdk/dynamic_template_data" describe SmartwaiverDynamicTemplateData do before do FakeWeb.allow_net_connect = false end describe "dynamic template data" do it "#initialize" do td = SmartwaiverDynamicTemplateData.new expect(td).to be_kind_of(SmartwaiverDynamicTemplateData) expect(td.adult).to eq(true) expect(td.participants).to eq([]) expect(td.guardian).to be_kind_of(SmartwaiverGuardian) expect(td.address_line_one).to be_nil expect(td.address_line_two).to be_nil expect(td.address_country).to be_nil expect(td.address_state).to be_nil expect(td.address_zip).to be_nil expect(td.email).to be_nil expect(td.emergency_contact_name).to be_nil expect(td.emergency_contact_phone).to be_nil expect(td.insurance_carrier).to be_nil expect(td.insurance_policy_number).to be_nil expect(td.drivers_license_state).to be_nil expect(td.drivers_license_number).to be_nil end it "#initialize with non default adult" do td = SmartwaiverDynamicTemplateData.new(false) expect(td.adult).to eq(false) end it "#add_participant" do td = SmartwaiverDynamicTemplateData.new p = SmartwaiverParticipant.new p.first_name = "Rocky" p.last_name = "RockChuck" td.add_participant(p) expect(td.participants).to eq([p]) end it "#for_json minimal" do td = SmartwaiverDynamicTemplateData.new p = SmartwaiverParticipant.new p.first_name = "Rocky" p.last_name = "RockChuck" td.add_participant(p) a = td.for_json a_expected = { "adult"=>true, "participants"=>[{"firstName"=>"Rocky", "lastName"=>"RockChuck"}], "guardian"=>{"participant"=>false} } expect(a).to eq(a_expected) end it "#for_json all fields" do td = SmartwaiverDynamicTemplateData.new(false) p = SmartwaiverParticipant.new p.first_name = "Rocky" p.last_name = "RockChuck" p.gender = "M" p.dob = "2010-01-01" td.add_participant(p) td.address_line_one = "123 Main St." td.address_line_two = "Apt A" td.address_country = "US" td.address_state = "OR" td.address_zip = "97703" td.email = "<EMAIL>" td.emergency_contact_name = "<NAME>" td.emergency_contact_phone = "800-555-1212" td.insurance_carrier = "Aetna" td.insurance_policy_number = "H01" td.drivers_license_state = "OR" td.drivers_license_number = "010101" a = td.for_json a_expected = { "adult"=>false, "participants"=>[{"firstName"=>"Rocky", "lastName"=>"RockChuck", "gender" => "M", "dob" => "2010-01-01"}], "guardian"=>{"participant"=>false}, "addressLineOne" => "123 Main St.", "addressLineTwo" => "Apt A", "addressCountry" => "US", "addressState" => "OR", "addressZip" => "97703", "email" => "<EMAIL>", "emergencyContactName" => "<NAME>", "emergencyContactPhone" => "800-555-1212", "insuranceCarrier" => "Aetna", "insurancePolicyNumber" => "H01", "driversLicenseState" => "OR", "driversLicenseNumber" => "010101" } expect(a).to eq(a_expected) end end end describe SmartwaiverParticipant do describe "Participant Data" do it "#initialize" do p = SmartwaiverParticipant.new expect(p.first_name).to be_nil expect(p.middle_name).to be_nil expect(p.last_name).to be_nil expect(p.phone).to be_nil expect(p.gender).to be_nil expect(p.dob).to be_nil a = p.for_json expect(a).to eq({}) end it "#for_json" do p = SmartwaiverParticipant.new p.first_name = "Rocky" p.middle_name = "R" p.last_name = "RockChuck" p.phone = "800-555-1212" p.gender = "M" p.dob = '1970-01-01' a = p.for_json a_expected = { "firstName"=>"Rocky", "middleName"=>"R", "lastName"=>"RockChuck", "phone"=>"800-555-1212", "gender"=>"M", "dob"=>"1970-01-01" } expect(a).to eq(a_expected) end end end describe SmartwaiverGuardian do describe "Guardian Data" do it "#initialize" do g = SmartwaiverGuardian.new expect(g.participant).to eq(false) expect(g.first_name).to be_nil expect(g.middle_name).to be_nil expect(g.last_name).to be_nil expect(g.relationship).to be_nil expect(g.phone).to be_nil expect(g.gender).to be_nil expect(g.dob).to be_nil a = g.for_json expect(a).to eq({"participant" => false}) end it "#for_json" do g = SmartwaiverGuardian.new g.participant = false g.first_name = "Rocky" g.middle_name = "R" g.last_name = "RockChuck" g.phone = "800-555-1212" g.gender = "M" g.dob = '1970-01-01' a = g.for_json a_expected = { "participant"=>false, "firstName"=>"Rocky", "middleName"=>"R", "lastName"=>"RockChuck", "phone"=>"800-555-1212", "gender"=>"M", "dob"=>"1970-01-01" } expect(a).to eq(a_expected) end end end
smartwaivercom/ruby-sdk
examples/webhooks/set_webhooks.rb
<filename>examples/webhooks/set_webhooks.rb # # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/webhook_client' # The API Key for your account api_key='[INSERT API KEY]' client = SmartwaiverWebhookClient.new(api_key) end_point = 'http://example.org' send_after_email_only = SmartwaiverWebhookClient::WEBHOOK_AFTER_EMAIL_ONLY begin result = client.configure(end_point, send_after_email_only) webhook = result[:webhooks] puts "Successfully set new configuration." puts "Endpoint: #{webhook[:endpoint]}" puts "EmailValidationRequired: #{webhook[:emailValidationRequired]}" rescue SmartwaiverSDK::BadAPIKeyError=>bad puts "API Key error: #{bad.message}" rescue SmartwaiverSDK::BadFormatError=>bfe puts "Request or Data not correct: #{bfe.message}" rescue Exception=>e puts "Exception thrown. Error during webhook configuration: #{e.message}" end
smartwaivercom/ruby-sdk
examples/waivers/list_all_waivers.rb
<reponame>smartwaivercom/ruby-sdk<gh_stars>1-10 # # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/waiver_client' # The API Key for your account api_key='[INSERT API KEY]' client = SmartwaiverWaiverClient.new(api_key) begin # use default parameters result = client.list puts "List all waivers:" result[:waivers].each do |waiver| puts "#{waiver[:waiverId]}: #{waiver[:title]}" end # Specifiy non default parameters limit = 5 verified = true template_id = "586ffe15134bd" from_dts = '2017-01-01T00:00:00Z' to_dts = '2017-02-01T00:00:00Z' result = client.list(limit, verified, template_id, from_dts, to_dts) puts "List all waivers:" result[:waivers].each do |waiver| puts "#{waiver[:waiverId]}: #{waiver[:title]}" end rescue SmartwaiverSDK::BadAPIKeyError=>bad puts "API Key error: #{bad.message}" rescue Exception=>e puts "Exception thrown. Error during waiver listing: #{e.message}" end
smartwaivercom/ruby-sdk
examples/waivers/waiver_properties.rb
<reponame>smartwaivercom/ruby-sdk # # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/waiver_client' # The API Key for your account api_key='[INSERT API KEY]' # The unique ID of the signed waiver to be retrieved waiver_id='[INSERT WAIVER ID]' client = SmartwaiverWaiverClient.new(api_key) begin result = client.get(waiver_id, true) waiver = result[:waiver] puts "Waiver ID: #{waiver[:waiverId]}" puts "Template Id: #{waiver[:templateId]}" puts "Title: #{waiver[:title]}" puts "Created On: #{waiver[:createdOn]}" puts "Expiration Date: #{waiver[:expirationDate]}" puts "Expired: #{waiver[:expired]}" puts "Verified: #{waiver[:verified]}" puts "Kiosk: #{waiver[:kiosk]}" puts "First Name: #{waiver[:firstName]}" puts "Middle Name: #{waiver[:middleName]}" puts "Last Name: #{waiver[:lastName]}" puts "Dob: #{waiver[:dob]}" puts "Is Minor: #{waiver[:isMinor]}" puts "Tags: " waiver[:tags].each do |tag| puts " #{tag}" end puts "Participants:" waiver[:participants].each do |p| puts " First Name: #{p[:firstName]}" puts " Middle Name: #{p[:middleName]}" puts " Last Name: #{p[:lastName]}" puts " DOB: #{p[:dob]}" puts " Is Minor: #{p[:isMinor]}" puts " Gender: #{p[:gender]}" puts " Tags: #{p[:tags]}" puts " Custom Participant Fields: (GUID, Display Text, Value)" p[:customParticipantFields].each do |k,v| puts " #{k}, #{v[:value]}, #{v[:displayText]}" end end puts "Custom Waiver Fields: (GUID, Display Text, Value)" waiver[:customWaiverFields].each do |k,v| puts " #{k}, #{v[:value]}, #{v[:displayText]}" end puts "Email: #{waiver[:email]}" puts "Marketing Allowed: #{waiver[:marketingAllowed]}" puts "Address Line One: #{waiver[:addressLineOne]}" puts "Address Line Two: #{waiver[:addressLineTwo]}" puts "Address City: #{waiver[:addressCity]}" puts "Address State: #{waiver[:addressState]}" puts "Address Zip Code: #{waiver[:addressZipCode]}" puts "Address Country: #{waiver[:addressCountry]}" puts "Emergency Contanct Name: #{waiver[:emergencyContactName]}" puts "Emergency Contanct Phone: #{waiver[:emergencyContactPhone]}" puts "Insurance Carrier: #{waiver[:insuranceCarrier]}" puts "Insurance Policy Number: #{waiver[:insurancePolicyNumber]}" puts "Drivers License Number: #{waiver[:driversLicenseNumber]}" puts "Drivers License State: #{waiver[:driversLicenseState]}" puts "Client IP: #{waiver[:clientIP]}" puts "PDF: #{waiver[:pdf]}" rescue SmartwaiverSDK::BadAPIKeyError=>bad puts "API Key error: #{bad.message}" rescue Exception=>e puts "Exception thrown. Error during waiver properties: #{e.message}" end
smartwaivercom/ruby-sdk
spec/smartwaiver-sdk/waiver_client_spec.rb
<filename>spec/smartwaiver-sdk/waiver_client_spec.rb dir = File.dirname(__FILE__) require "#{dir}/../spec_helper" require "#{dir}/../../lib/smartwaiver-sdk/waiver_client" describe SmartwaiverWaiverClient do attr_reader :client, :api_key before do FakeWeb.allow_net_connect = false @api_key = "apikey" @client = SmartwaiverWaiverClient.new(@api_key) end describe "waivers" do it "#initialize" do expect(@client).to be_kind_of(SmartwaiverWaiverClient) end it "#list all default values" do path = "#{API_URL}/v4/waivers?limit=20" FakeWeb.register_uri(:get, path, :body => json_waiver_list_results) result = @client.list expect(result[:waivers].length).to eq(3) end it "#list with all values specified" do limit = 3 verified = true template_id = "586ffe15134bd" from_dts = '2017-01-01T00:00:00Z' to_dts = '2017-02-01T00:00:00Z' path = "#{API_URL}/v4/waivers?limit=#{limit}&verified=#{verified}&templateId=#{template_id}&fromDts=#{from_dts}&toDts=#{to_dts}" FakeWeb.register_uri(:get, path, :body => json_waiver_list_results) @client.list(limit, verified, template_id, from_dts, to_dts) end it "#get without pdf" do waiver_id = "Vzy8f6gnCWVcQBURdydwPT" path = "#{API_URL}/v4/waivers/#{waiver_id}?pdf=false" FakeWeb.register_uri(:get, path, :body => json_waiver_single_results) result = @client.get(waiver_id) expect(result[:waiver][:waiverId]).to eq(waiver_id) expect(result[:waiver][:participants].length).to eq(2) expect(result[:waiver][:customWaiverFields][:"58458759da897"][:value]).to eq ("Testing") end it "#get with pdf" do waiver_id = "Vzy8f6gnCWVcQBURdydwPT" path = "#{API_URL}/v4/waivers/#{waiver_id}?pdf=true" FakeWeb.register_uri(:get, path, :body => json_waiver_single_results) @client.get(waiver_id, true) end it "#photos" do waiver_id = "6jebdfxzvrdkd" path = "#{API_URL}/v4/waivers/#{waiver_id}/photos" FakeWeb.register_uri(:get, path, :body => json_waiver_photos_results) result = @client.photos(waiver_id) expect(result[:photos][:waiverId]).to eq(waiver_id) expect(result[:photos][:templateId]).to eq("sprswrvh2keeh") expect(result[:photos][:title]).to eq("Smartwaiver Demo Waiver") expect(result[:photos][:photos].length).to eq(1) expect(result[:photos][:photos][0][:type]).to eq("kiosk") expect(result[:photos][:photos][0][:tag]).to eq("IP: 192.168.2.0") expect(result[:photos][:photos][0][:fileType]).to eq("jpg") expect(result[:photos][:photos][0][:photoId]).to eq("CwLeDjffgDoGHua") expect(result[:photos][:photos][0][:photo]).to eq("BASE64 ENCODED PHOTO") end it "#signatures" do waiver_id = "6jebdfxzvrdkd" path = "#{API_URL}/v4/waivers/#{waiver_id}/signatures" FakeWeb.register_uri(:get, path, :body => json_waiver_signatures_results) result = @client.signatures(waiver_id) expect(result[:signatures][:waiverId]).to eq(waiver_id) expect(result[:signatures][:templateId]).to eq("sprswrvh2keeh") expect(result[:signatures][:title]).to eq("Smartwaiver Demo Waiver") expect(result[:signatures][:signatures][:participants].length).to eq(1) expect(result[:signatures][:signatures][:guardian].length).to eq(1) expect(result[:signatures][:signatures][:bodySignatures].length).to eq(1) expect(result[:signatures][:signatures][:bodyInitials].length).to eq(1) end end end
smartwaivercom/ruby-sdk
spec/smartwaiver-sdk/keys_client_spec.rb
dir = File.dirname(__FILE__) require "#{dir}/../spec_helper" require "#{dir}/../../lib/smartwaiver-sdk/keys_client" describe SmartwaiverKeysClient do attr_reader :client, :api_key before do FakeWeb.allow_net_connect = false @api_key = "apikey" @client = SmartwaiverKeysClient.new(@api_key) end describe "keys" do it "#initialize" do expect(@client).to be_kind_of(SmartwaiverKeysClient) end it "#create" do label = 'Ruby SDK' path="#{API_URL}/v4/keys/published" FakeWeb.register_uri(:post, path, :body => json_keys_create_results) response = @client.create(label) expect(response[:published_keys][:newKey][:key]).to eq("<KEY>") expect(response[:published_keys][:newKey][:label]).to eq(label) expect(response[:published_keys][:keys].length).to eq(1) end it "#list" do path="#{API_URL}/v4/keys/published" FakeWeb.register_uri(:get, path, :body => json_keys_list_results) response = @client.list expect(response[:published_keys][:keys].length).to eq(1) expect(response[:published_keys][:keys][0][:key]).to eq("<KEY>") expect(response[:published_keys][:keys][0][:label]).to eq("Ruby SDK") end end end
smartwaivercom/ruby-sdk
examples/dynamic-templates/create_dynamic_template.rb
<gh_stars>1-10 # # Copyright 2018 Smartwaiver # # 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. # Create Dynamic Template Sample Code # # export RUBYLIB=<path>/sw-sdk-ruby/lib # require 'smartwaiver-sdk/dynamic_template' require 'smartwaiver-sdk/dynamic_template_data' require 'smartwaiver-sdk/dynamic_template_client' # The API Key for your account api_key='<API_KEY>' # Create data object for pre-fill data = SmartwaiverDynamicTemplateData.new # Create a participant and then add to data object participant = SmartwaiverParticipant.new participant.first_name='Rocky' participant.last_name='Chuck' participant.dob = '1986-01-02' data.add_participant(participant) # Fill in email data.email = '<EMAIL>' # Create Template Configuration object c = SmartwaiverDynamicTemplateConfig.new # Text for Template Header th = SmartwaiverTemplateHeader.new th.text = 'Sample Dynamic Waiver from Ruby SDK' c.header = th # Text for Template Body tb = SmartwaiverTemplateBody.new tb.text = 'This template is <b>only</b> for testing!' c.body = tb # Participants section configuration tp = SmartwaiverTemplateParticipants.new tp.show_middle_name = false c.participants = tp # Redirect configuration (required but not enforced) comp = SmartwaiverTemplateCompletion.new comp.redirect_success = 'https://localhost/done?tid=[transactionId]' comp.redirect_cancel = 'https://localhost/cancel' c.completion = comp # Standard Questions - only show one email address sc = SmartwaiverTemplateStandardQuestions.new sc.email_verification_enabled = false c.standard_questions = sc # Create the Dyanmic Template Object and assign the data and config t = SmartwaiverDynamicTemplate.new t.data = data t.template_config = c # Create the Dynamic Template Client and then create the dynamic template. Return information includes URL for template dtc = SmartwaiverDynamicTemplateClient.new(api_key) begin result = dtc.create(t) puts "Dynamic Template Information" puts " Type: #{result[:type]}" puts " URL : #{result[:dynamic][:url]}" puts " UUID: #{result[:dynamic][:uuid]}" puts " Exp : #{result[:dynamic][:expiration]}" rescue SmartwaiverSDK::BadAPIKeyError=>bad puts "API Key error: #{bad.message}" rescue Exception=>e puts "Exception thrown. Error during waiver properties: #{e.message}" end
smartwaivercom/ruby-sdk
examples/search/basic_search.rb
# # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/search_client' # The API Key for your account api_key='[INSERT API KEY]' begin client = SmartwaiverSearchClient.new(api_key) puts "Performing search for all waiver signed after 2018-01-01 00:00:00..." # Request all waivers signed in 2018 results = client.search('', '2018-01-01 00:00:00') search = results[:search] # Print out some information about the result of the search puts "Search Complete:" puts " Search ID: #{search[:guid]}" puts " Waiver Count: #{search[:count]}" puts " #{search[:pages]} pages of size #{search[:pageSize]}" puts "" # We're going to create a list of all the first names on all the waivers name_list = []; pages = search[:pages] current_page = 0 search_guid = search[:guid] while current_page < pages puts "Requesting page: #{current_page}/#{pages} ..." waivers = client.results(search_guid, current_page) puts "Processing page: #{current_page}/#{pages} ..." waivers[:search_results].each do |waiver| name_list.push(waiver[:firstName]) end current_page = current_page + 1 end puts "Finished processing..." puts name_list.join(',') rescue SmartwaiverSDK::BadAPIKeyError=>bad puts "API Key error: #{bad.message}" rescue Exception=>e puts "Exception thrown. Error during queue information: #{e.message}" end
smartwaivercom/ruby-sdk
examples/dynamic-templates/process_dynamic_template.rb
# # Copyright 2018 Smartwaiver # # 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. # Process Dynamic Template Sample Code # # export RUBYLIB=<path>/sw-sdk-ruby/lib # require 'smartwaiver-sdk/dynamic_template' require 'smartwaiver-sdk/dynamic_template' require 'smartwaiver-sdk/dynamic_template_data' require 'smartwaiver-sdk/dynamic_template_client' # The API Key for your account api_key='<API_KEY>' # Put Transaction ID here transaction_id='<TRANSACTION_ID>' dtc = SmartwaiverDynamicTemplateClient.new(api_key) begin result = dtc.process(transaction_id) puts "#{result[:type]}" puts "#{result[:dynamic_process][:transactionId]}" puts "#{result[:dynamic_process][:waiverId]}" rescue SmartwaiverSDK::BadAPIKeyError=>bad puts "API Key error: #{bad.message}" rescue Exception=>e puts "Exception thrown. Error during waiver properties: #{e.message}" end
smartwaivercom/ruby-sdk
lib/smartwaiver-sdk/smartwaiver_version.rb
<filename>lib/smartwaiver-sdk/smartwaiver_version.rb # # Copyright 2018 Smartwaiver # # 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. module SmartwaiverSDK VERSION = "4.2.1" class Info @@ClientVersion = SmartwaiverSDK::VERSION @@RubyVersion = RUBY_VERSION @@UserAgent = "SmartwaiverAPI:#{@@ClientVersion}-Ruby:#{@@RubyVersion}"; def self.get_user_agent return @@UserAgent end end end
smartwaivercom/ruby-sdk
examples/dynamic-templates/create_dynamic_template_advanced.rb
# # Copyright 2018 Smartwaiver # # 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. # Create Dynamic Template Sample Code # # export RUBYLIB=<path>/sw-sdk-ruby/lib # require 'smartwaiver-sdk/dynamic_template' require 'smartwaiver-sdk/dynamic_template_data' require 'smartwaiver-sdk/dynamic_template_client' require 'base64' # The API Key for your account api_key='<API_KEY>' def sample_legal_text txt = <<SAMPLE_LEGAL_TEXT <p style="text-align:center;"><strong>SAMPLE LEGAL TEXT</strong><br /><strong>All text , form fields, and signature elements can be customized on your waiver.</strong></p> <p style="text-align:justify;">In consideration of the services of Demo Company, LLC, their agents, owners, officers, volunteers, participants, employees, and all other persons or entities acting in any capacity on their behalf (hereinafter collectively referred to as "DC"), I hereby agree to release and discharge DC, on behalf of myself, my children, my parents, my heirs, assigns, personal representative and estate as follows:</p> <p style="text-align:justify;">1. I acknowledge that the activities involved in the use of any of DC’s services or facilities entail significant risks, both known and unknown, which could result in physical or emotional injury, paralysis, death, or damage to myself, to property, or to third parties.</p> <p style="text-align:justify;">2. I expressly agree and promise to accept and assume all of the risks existing in these activities, both known and unknown, whether caused or alleged to be caused by the negligent acts or omissions of DC. My participation in this activity is purely voluntary, and I elect to participate in spite of the risks.</p> <p style="text-align:justify;">3. I hereby voluntarily release, forever discharge, and agree to indemnify and hold harmless DF from any and all claims, demands, or causes of action, which are in any way connected with my participation in this activity or my use of DC equipment or facilities, including any such claims which allege negligent acts or omissions of DC.</p> <p style="text-align:justify;">4. Should DC or anyone acting on their behalf, be required to incur attorney's fees and costs to enforce this agreement, I agree to indemnify and hold them harmless for all such fees and costs.</p> <p style="text-align:justify;">5. I certify that I have adequate insurance to cover any injury or damage I may cause or suffer while participating, or else I agree to bear the costs of such injury or damage myself. I further certify that I have no medical or physical conditions which could interfere with my safety in this activity, or else I am willing to assume - and bear the costs of -- all risks that may be created, directly or indirectly, by any such condition.</p> <p style="text-align:justify;">6. I agree to abide by the rules of the facility. <strong>[initial]</strong></p> <p style="text-align:justify;">By signing this document, I acknowledge that if anyone is hurt or property is damaged during my participation in this activity, I may be found by a court of law to have waived my right to maintain a lawsuit against DC on the basis of any claim from which I have released them herein.</p> <p style="text-align:justify;"> </p> <p style="text-align:justify;"><strong>I HAVE HAD SUFFICIENT OPPORTUNITY TO READ THIS ENTIRE DOCUMENT. I HAVE READ AND UNDERSTAND IT, AND I AGREE TO BE BOUND BY ITS TERMS. </strong></p> <p style="text-align:justify;"><strong>Today's Date: </strong>[date]</p> SAMPLE_LEGAL_TEXT txt end # Create data object for pre-fill data = SmartwaiverDynamicTemplateData.new # Create a participant and then add to data object participant = SmartwaiverParticipant.new participant.first_name='Rocky' participant.last_name='Chuck' participant.dob = '1986-01-02' data.add_participant(participant) # Create Template Configuration object c = SmartwaiverDynamicTemplateConfig.new # Text for Template Header th = SmartwaiverTemplateHeader.new th.text = 'Trail Treks Demo Waiver' # read in image file and convert to base64 current_directory = File.expand_path(__dir__) logo_file = "#{current_directory}/trail_treks_logo.png" img_in_base64 = Base64.encode64(File.open(logo_file, "rb").read) # image must be prefixed correctly to make it an inline image th.format_image_inline(SmartwaiverTemplateHeader::MEDIA_TYPE_PNG,img_in_base64) c.header = th # Text for Template Body tb = SmartwaiverTemplateBody.new tb.text = sample_legal_text c.body = tb # Participants section configuration tp = SmartwaiverTemplateParticipants.new tp.show_middle_name = true tp.participant_label = "Adventurer's" c.participants = tp # Typed Signature only sig = SmartwaiverTemplateSignatures.new sig.type = SmartwaiverTemplateSignatures::SIGNATURE_TYPE sig.default_choice = SmartwaiverTemplateSignatures::SIGNATURE_TYPE c.signatures = sig # Redirect configuration (required but not enforced) comp = SmartwaiverTemplateCompletion.new comp.redirect_success = 'https://localhost/done?tid=[transactionId]' comp.redirect_cancel = 'https://localhost/cancel' c.completion = comp # Standard Questions - only show one email address sc = SmartwaiverTemplateStandardQuestions.new sc.address_enabled = true sc.default_state_code = 'OR' sc.email_verification_enabled = false sc.email_marketing_enabled = true sc.marketing_opt_in_checked = true c.standard_questions = sc # Create the Dyanmic Template Object and assign the data and config expiration = 10 * 60 # 10 minutes t = SmartwaiverDynamicTemplate.new(expiration) t.data = data t.template_config = c # Create the Dynamic Template Client and then create the dynamic template. Return information includes URL for template dtc = SmartwaiverDynamicTemplateClient.new(api_key) begin result = dtc.create(t) puts "Dynamic Template Information" puts " Type: #{result[:type]}" puts " URL : #{result[:dynamic][:url]}" puts " UUID: #{result[:dynamic][:uuid]}" puts " Exp : #{result[:dynamic][:expiration]}" rescue SmartwaiverSDK::BadAPIKeyError=>bad puts "API Key error: #{bad.message}" rescue Exception=>e puts "Exception thrown. Error during waiver properties: #{e.message}" end
smartwaivercom/ruby-sdk
examples/waivers/waiver_summary_properties.rb
<filename>examples/waivers/waiver_summary_properties.rb # # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/waiver_client' # The API Key for your account api_key='[INSERT API KEY]' client = SmartwaiverWaiverClient.new(api_key) begin result = client.list if result[:waivers].length > 1 waiver = result[:waivers][0] puts "Waiver ID: #{waiver[:waiverId]}" puts "Template Id: #{waiver[:templateId]}" puts "Title: #{waiver[:title]}" puts "Created On: #{waiver[:createdOn]}" puts "Expiration Date: #{waiver[:expirationDate]}" puts "Expired: #{waiver[:expired]}" puts "Verified: #{waiver[:verified]}" puts "Kiosk: #{waiver[:kiosk]}" puts "First Name: #{waiver[:firstName]}" puts "Middle Name: #{waiver[:middleName]}" puts "Last Name: #{waiver[:lastName]}" puts "Dob: #{waiver[:dob]}" puts "Is Minor: #{waiver[:isMinor]}" puts "Tags: #{waiver[:tags]}" end rescue SmartwaiverSDK::BadAPIKeyError=>bad puts "API Key error: #{bad.message}" rescue Exception=>e puts "Exception thrown. Error during waiver summary: #{e.message}" end
smartwaivercom/ruby-sdk
lib/smartwaiver-sdk/smartwaiver_base.rb
# # Copyright 2018 Smartwaiver # # 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 'json' require 'net/http' require 'smartwaiver-sdk/smartwaiver_version' require 'smartwaiver-sdk/smartwaiver_errors' module SmartwaiverSDK class SmartwaiverBase DEFAULT_API_ENDPOINT = 'https://api.smartwaiver.com' HEADER_API_KEY = 'sw-api-key' HTTP_READ_TIMEOUT = 60 HTTP_GET = "GET" HTTP_POST = "POST" HTTP_PUT = "PUT" HTTP_DELETE = "DELETE" def initialize(api_key, api_endpoint = DEFAULT_API_ENDPOINT) @api_endpoint = api_endpoint @api_key = api_key @http = nil @http_read_timeout = HTTP_READ_TIMEOUT init_http_connection(@api_endpoint) end def api_version make_api_request("/version") end def format_iso_time(time) time.strftime("%Y-%m-%dT%H:%M:%SZ") end def read_timeout(s) if s > 0 and s < 600 @http_read_timeout = s end end private def init_http_connection(target_server) if (@http and @http.started?) @http.finish end @last_init_time = Time.now.utc endpoint_url = URI.parse(target_server) @http = Net::HTTP.start(endpoint_url.host, endpoint_url.port, {:use_ssl => true, :read_timeout => @http_read_timeout}) @http end def common_http_headers {'User-Agent' => SmartwaiverSDK::Info.get_user_agent, HEADER_API_KEY => @api_key} end def rest_post_headers {"Content-Type" => "application/json"} end def make_api_request(path, request_type=HTTP_GET, data='') if (@last_init_time < Time.now.utc - 60) init_http_connection(@api_endpoint) end headers = common_http_headers case request_type when HTTP_GET response = @http.request_get(path, headers) when HTTP_PUT headers = common_http_headers.merge(rest_post_headers) response = @http.request_put(path, data, headers) when HTTP_POST headers = common_http_headers.merge(rest_post_headers) response = @http.request_post(path, data, headers) when HTTP_DELETE headers = common_http_headers.merge(rest_post_headers) response = @http.delete(path, headers) end check_response(response) end def check_response(response) response_data = parse_response_body(response.body) case response when Net::HTTPSuccess return response_data when Net::HTTPUnauthorized raise SmartwaiverSDK::BadAPIKeyError.new("#{response.code.to_s}:#{response_data[:message]}", response_data) when Net::HTTPNotAcceptable raise SmartwaiverSDK::BadFormatError.new("#{response.code.to_s}:#{response_data[:message]}", response_data) when Net::HTTPClientError, Net::HTTPServerError raise SmartwaiverSDK::RemoteServerError.new("#{response.code.to_s}:#{response_data[:message]}", response_data) else raise SmartwaiverSDK::RemoteServerError.new("#{response_data[:message]}", response_data) end end def parse_response_body(body) begin return JSON.parse(body, :symbolize_names => :symbolize_names) rescue JSON::ParserError => e return base_response_params.merge!({:message => e.message}) end end def base_response_params {:version => 0, :id => "", :ts => "1970-01-01T00:00:00+00:00", :type => "" } end def create_query_string(params) URI.encode_www_form(params) end end end
smartwaivercom/ruby-sdk
spec/spec_helper.rb
dir = File.dirname(__FILE__) require 'rubygems' require 'fakeweb' require 'rr' require 'json' $LOAD_PATH << "#{dir}/../lib/smartwaiver-sdk" require 'smartwaiver_base' require 'smartwaiver_errors' API_URL = 'https://api.smartwaiver.com' def json_parse(data) JSON.parse(data, :symbolize_names => true) end def json_api_version_results json = <<JAVASCRIPT {"version": "4.2.1"} JAVASCRIPT json end def json_base_results json = <<JAVASCRIPT {"version":4, "id":"8e82fa534da14b76a05013644ee735d2", "ts":"2017-01-17T15:46:58+00:00", "type":""} JAVASCRIPT end def json_webhook_configuration_results json = <<JAVASCRIPT {"version":4, "id":"8e82fa534da14b76a05013644ee735d2", "ts":"2017-01-17T15:46:58+00:00", "type":"webhooks", "webhooks":{"endpoint":"http://requestb.in/1ajthro1", "emailValidationRequired":"yes"}} JAVASCRIPT end def json_webhook_configure_results json = <<JAVASCRIPT {"version":4, "id":"8e82fa534da14b76a05013644ee735d2", "ts":"2017-01-17T15:46:58+00:00", "type":"webhooks", "webhooks":{"endpoint":"http://requestb.in/1ajthro2", "emailValidationRequired":"yes"}} JAVASCRIPT end def json_webhook_delete_results json = <<JAVASCRIPT {"version":4, "id":"8e82fa534da14b76a05013644ee735d2", "ts":"2017-01-17T15:46:58+00:00", "type":"webhooks", "webhooks":{}} JAVASCRIPT end def json_webhook_resend_results json = <<JAVASCRIPT {"version":4, "id":"8e82fa534da14b76a05013644ee735d2", "ts":"2017-01-17T15:46:58+00:00", "type":"webhooks_resend", "webhooks_resend":{"success":true}} JAVASCRIPT end def json_webhook_queues_information_results json = <<JAVASCRIPT { "version" : 4, "id" : "a0256461ca244278b412ab3238f5efd2", "ts" : "2017-01-24T11:14:25+00:00", "type" : "api_webhook_all_queue_message_count", "api_webhook_all_queue_message_count" : { "account": { "messagesTotal": 2, "messagesNotVisible": 0, "messagesDelayed": 0 }, "template-4fc7d12601941": { "messagesTotal": 4, "messagesNotVisible": 2, "messagesDelayed": 0 } } } JAVASCRIPT end def json_webhook_queues_get_message_results json = <<JAVASCRIPT { "version" : 4, "id" : "a0256461ca244278b412ab3238f5efd2", "ts" : "2017-01-24T11:14:25+00:00", "type" : "api_webhook_account_message_get", "api_webhook_account_message_get" : { "messageId": "9d58e8fc-6353-4ceb-b0a3-5412f3d05e28", "payload": { "unique_id": "xyz", "event": "new-waiver" } } } JAVASCRIPT end def json_webhook_queues_delete_message_results json = <<JAVASCRIPT { "version" : 4, "id" : "a0256461ca244278b412ab3238f5efd2", "ts" : "2017-01-24T11:14:25+00:00", "type" : "api_webhook_account_message_delete", "api_webhook_account_message_delete" : { "success": true } } JAVASCRIPT end def json_webhook_queues_template_get_message_results json = <<JAVASCRIPT { "version" : 4, "id" : "a0256461ca244278b412ab3238f5efd2", "ts" : "2017-01-24T11:14:25+00:00", "type" : "api_webhook_template_message_get", "api_webhook_template_message_get" : { "messageId": "9d58e8fc-6353-4ceb-b0a3-5412f3d05e28", "payload": { "unique_id": "xyz", "event": "new-waiver" } } } JAVASCRIPT end def json_webhook_queues_template_delete_message_results json = <<JAVASCRIPT { "version" : 4, "id" : "a0256461ca244278b412ab3238f5efd2", "ts" : "2017-01-24T11:14:25+00:00", "type" : "api_webhook_template_message_delete", "api_webhook_template_message_delete" : { "success": true } } JAVASCRIPT end def json_template_list_results json = <<JAVASCRIPT {"version":4,"id":"05928f4b1b3849c9a73aca257808f1d5","ts":"2017-01-17T22:33:56+00:00","type":"templates","templates": [{"templateId":"586ffe15134bc","title":"Template 1","publishedVersion":1,"publishedOn":"2017-01-06 20:33:35","webUrl":"https:\/\/www.smartwaiver.com\/w\/586ffe15134bc\/web\/","kioskUrl":"https:\/\/www.smartwaiver.com\/w\/586ffe15134bc\/kiosk\/"}, {"templateId":"5845e3a0add4d","title":"Template 2","publishedVersion":3,"publishedOn":"2017-01-05 20:33:35","webUrl":"https:\/\/www.smartwaiver.com\/w\/5845e3a0add4d\/web\/","kioskUrl":"https:\/\/www.smartwaiver.com\/w\/5845e3a0add4d\/kiosk\/"}, {"templateId":"56ce3bb69c748","title":"Template 3","publishedVersion":4,"publishedOn":"2016-02-24 23:34:37","webUrl":"https:\/\/www.smartwaiver.com\/w\/56ce3bb69c748\/web\/","kioskUrl":"https:\/\/www.smartwaiver.com\/w\/56ce3bb69c748\/kiosk\/"} ] } JAVASCRIPT end def json_template_single_results json = <<JAVASCRIPT {"version":4,"id":"81b24d6b6c364ead9af037c5652b897e","ts":"2017-01-19T01:02:36+00:00","type":"template","template":{"templateId":"586ffe15134bc","title":"Template 1","publishedVersion":1,"publishedOn":"2017-01-06 20:33:35","webUrl":"https:\/\/www.smartwaiver.com\/w\/586ffe15134bc\/web\/","kioskUrl":"https:\/\/www.smartwaiver.com\/w\/586ffe15134bc\/kiosk\/"}} JAVASCRIPT end def json_waiver_list_results json = <<JAVASCRIPT {"version":4,"id":"f73838873a6b470d804ff2cfe002e0de","ts":"2017-01-19T01:18:42+00:00","type":"waivers","waivers": [{"waiverId":"Vzy8f6gnCWVcQBURdydwPT","templateId":"586ffe15134bc","title":"Template 1","createdOn":"2017-01-06 21:28:13","expirationDate":"","expired":false,"verified":true,"kiosk":true,"firstName":"John","middleName":"","lastName":"Doe","dob":"1987-06-09","isMinor":false,"tags":[]}, {"waiverId":"ko4C4rcUvHe3VnfKJ2Cmr6","templateId":"586ffe15134bc","title":"Template 1","createdOn":"2017-01-06 21:25:26","expirationDate":"","expired":false,"verified":true,"kiosk":true,"firstName":"Jane","middleName":"","lastName":"Doe","dob":"1983-07-01","isMinor":false,"tags":[]}, {"waiverId":"VUey8JHxC4ED2r7jiWszNE","templateId":"586ffe15134bc","title":"Template 1","createdOn":"2017-01-06 20:39:03","expirationDate":"","expired":false,"verified":true,"kiosk":true,"firstName":"Jimmy","middleName":"","lastName":"Smith","dob":"1980-03-07","isMinor":false,"tags":[]} ]} JAVASCRIPT end def json_waiver_single_results json = <<JAVASCRIPT {"version":4,"id":"7730a96154874baca44ec7ac3444ebee","ts":"2017-01-19T01:22:50+00:00","type":"waiver","waiver": {"waiverId":"Vzy8f6gnCWVcQBURdydwPT", "templateId":"586ffe15134bc", "title":"Template 1", "createdOn":"2016-12-05 19:58:42", "expirationDate":"", "expired":false, "verified":true, "kiosk":false, "firstName":"Jane", "middleName":"L", "lastName":"Smith", "dob":"2004-07-01", "isMinor":true, "tags":[], "participants":[ {"firstName":"Jane", "middleName":"L", "lastName":"Smith", "dob":"2004-07-01", "isMinor":true, "gender":"Female", "phone":"888-555-1214", "tags":[], "customParticipantFields":{"58458713a384a":{"value":"Short","displayText":"Custom text for minor"}} }, {"firstName":"Joe", "middleName":"", "lastName":"Smith", "dob":"1969-02-02", "isMinor":false, "gender":"Male", "phone":"888-555-1213", "tags":[], "customParticipantFields":{"58458713a384a":{"value":"Hello World","displayText":"Custom text for minor"}}} ], "customWaiverFields":{"58458759da897":{"value":"Testing","displayText":"Question at waiver fields"}}, "guardian":null, "email":"<EMAIL>", "marketingAllowed":true, "addressLineOne":"123 Main St", "addressLineTwo":"", "addressCity":"Bend", "addressState":"OR", "addressZip":"97703", "addressCountry":"US", "emergencyContactName":"<NAME>", "emergencyContactPhone":"888-555-1212", "insuranceCarrier":"BlueCross", "insurancePolicyNumber":"X001234", "driversLicenseNumber":"C1234324", "driversLicenseState":"CA", "clientIP":"127.0.0.1", "pdf":""} } JAVASCRIPT end def json_waiver_photos_results json = <<JAVASCRIPT { "version" : 4, "id" : "a0256461ca244278b412ab3238f5efd2", "ts" : "2017-01-24T11:14:25+00:00", "type" : "photos", "photos" : { "waiverId": "6jebdfxzvrdkd", "templateId": "sprswrvh2keeh", "title": "Smartwaiver Demo Waiver", "createdOn": "2017-01-24 13:12:29", "photos": [ { "type": "kiosk", "date": "2017-01-01 00:00:00", "tag": "IP: 192.168.2.0", "fileType": "jpg", "photoId": "CwLeDjffgDoGHua", "photo": "BASE64 ENCODED PHOTO" } ] } } JAVASCRIPT json end def json_waiver_signatures_results json = <<JAVASCRIPT { "version" : 4, "id" : "a0256461ca244278b412ab3238f5efd2", "ts" : "2017-01-24T11:14:25+00:00", "type" : "signatures", "signatures" : { "waiverId": "6jebdfxzvrdkd", "templateId": "sprswrvh2keeh", "title": "Smartwaiver Demo Waiver", "createdOn": "2017-01-24 13:12:29", "signatures": { "participants": [ "BASE64 ENCODED IMAGE STRING" ], "guardian": [ "BASE64 ENCODED IMAGE STRING" ], "bodySignatures": [ "BASE64 ENCODED IMAGE STRING" ], "bodyInitials": [ "BASE64 ENCODED IMAGE STRING" ] } } } JAVASCRIPT json end def json_dynamic_template_default '{"template":{"meta":{},"header":{},"body":{},"participants":{"adults":true},"standardQuestions":{},"guardian":{},"electronicConsent":{},"styling":{},"completion":{},"signatures":{},"processing":{}},"data":{"adult":true,"participants":[],"guardian":{"participant":false}}}' end def json_keys_create_results json = <<JAVASCRIPT {"version" : 4,"id" : "a0256461ca244278b412ab3238f5efd2","ts" : "2017-01-24T11:14:25+00:00","type" : "published_keys", "published_keys" : { "newKey": { "createdAt": "2017-01-24T11:14:25Z", "key" : "<KEY>", "label" : "Ruby SDK" }, "keys" : [ { "createdAt": "<KEY>", "key" : "<KEY>", "label" : "demo" } ] } } JAVASCRIPT json end def json_keys_list_results json = <<JAVASCRIPT { "version" : 4,"id" : "a0256461ca244278b412ab3238f5efd2","ts" : "2017-01-24T11:14:25Z","type" : "published_keys", "published_keys" : { "keys" : [ { "createdAt": "<KEY>", "key" : "<KEY>", "label" : "Ruby SDK" } ] } } JAVASCRIPT json end def json_search_1_results json = <<JAVASCRIPT { "version" : 4, "id" : "a0256461ca244278b412ab3238f5efd2", "ts" : "2017-01-24T11:14:25+00:00", "type" : "search", "search" : { "guid": "6jebdfxzvrdkd", "count": 652, "pages": 7, "pageSize": 100 } } JAVASCRIPT json end def json_search_2_results json = <<JAVASCRIPT { "version" : 4, "id" : "a0256461ca244278b412ab3238f5efd2", "ts" : "2017-01-24T11:14:25+00:00", "type" : "search_results", "search_results" : [ { "waiverId": "6jebdfxzvrdkd", "templateId": "sprswrvh2keeh", "title": "Smartwaiver Demo Waiver", "createdOn": "2017-01-24 13:12:29", "expirationDate": "", "expired": false, "verified": true, "kiosk": true, "firstName": "Kyle", "middleName": "", "lastName": "<NAME>", "dob": "2008-12-25", "clientIP": "192.0.2.0", "email":"<EMAIL>", "marketingAllowed": false, "addressLineOne": "626 NW Arizona Ave.", "addressLineTwo": "Suite 2", "addressCity": "Bend", "addressState": "OR", "addressZip": "97703", "addressCountry": "US", "emergencyContactName": "<NAME>", "emergencyContactPhone": "111-111-1111", "insuranceCarrier": "My Insurance", "insurancePolicyNumber": "1234567", "driversLicenseNumber": "9876543", "driversLicenseState": "OR", "tags": [ "Green Team" ], "flags": { "displayText": "Have you received our orientation?", "reason": "was not selected" }, "participants": [ { "firstName": "Kyle", "middleName": "", "lastName": "<NAME>", "dob": "2008-12-25", "isMinor": true, "gender": "Male", "phone": "", "tags": ["YES"], "customParticipantFields" : { "bk3xydss4e9dy" : { "value" : "YES", "displayText" : "Is this participant ready to have fun?" } }, "flags": [ { "displayText": "Are you excited?", "reason": "was not selected" } ] } ], "pdf": "Base64 Encoded PDF", "photos": 1, "guardian": { "firstName": "Kyle", "middleName": "", "lastName": "<NAME>", "phone": "555-555-5555", "dob": "1970-12-25" }, "customWaiverFields" : { "ha5bs1jy5wdop" : { "value" : "A friend", "displayText" : "How did you hear about Smartwaiver?" } } } ] } JAVASCRIPT json end def json_user_settings_results json = <<JAVASCRIPT { "version" : 4, "id" : "a0256461ca244278b412ab3238f5efd2", "ts" : "2017-01-24T11:14:25Z", "type" : "settings", "settings" : { "console" : { "staticExpiration" : "never", "rollingExpiration" : "never", "rollingExpirationTime" : "signed" } } } JAVASCRIPT json end
smartwaivercom/ruby-sdk
examples/waivers/retrieve_single_waiver.rb
# # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/waiver_client' # The API Key for your account api_key='[INSERT API KEY]' # The unique ID of the signed waiver to be retrieved waiver_id='[INSERT WAIVER ID]' client = SmartwaiverWaiverClient.new(api_key) begin # use default parameters result = client.get(waiver_id) waiver = result[:waiver] puts "List single waiver:" puts "#{waiver[:waiverId]}: #{waiver[:title]}" result = client.get(waiver_id, true) waiver = result[:waiver] puts "PDF:" puts "#{waiver[:pdf]}" rescue SmartwaiverSDK::BadAPIKeyError=>bad puts "API Key error: #{bad.message}" rescue SmartwaiverSDK::RemoteServerError=>rse puts "Remote Server error: #{rse.message}" rescue Exception=>e puts "Exception thrown. Error during waiver retrieval: #{e.message}" end
smartwaivercom/ruby-sdk
examples/waivers/retrieve_waiver_photos.rb
<filename>examples/waivers/retrieve_waiver_photos.rb # # Copyright 2018 Smartwaiver # # 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 'smartwaiver-sdk/waiver_client' # The API Key for your account api_key='[INSERT API KEY]' # The unique ID of the signed waiver to be retrieved waiver_id='[INSERT WAIVER ID]' client = SmartwaiverWaiverClient.new(api_key) begin result = client.photos(waiver_id) photos = result[:photos] puts "Waiver Photos for: #{photos[:title]}" photos[:photos].each do |photo| puts "#{photo[:photoId]}: #{photo[:date]}" end rescue SmartwaiverSDK::BadAPIKeyError=>bad puts "API Key error: #{bad.message}" rescue SmartwaiverSDK::RemoteServerError=>rse puts "Remote Server error: #{rse.message}" rescue Exception=>e puts "Exception thrown. Error during waiver retrieval: #{e.message}" end
smartwaivercom/ruby-sdk
spec/smartwaiver-sdk/template_client_spec.rb
<reponame>smartwaivercom/ruby-sdk dir = File.dirname(__FILE__) require "#{dir}/../spec_helper" require "#{dir}/../../lib/smartwaiver-sdk/template_client" describe SmartwaiverTemplateClient do attr_reader :client, :api_key before do FakeWeb.allow_net_connect = false @api_key = "apikey" @client = SmartwaiverTemplateClient.new(@api_key) end describe "templates" do it "#initialize" do expect(@client).to be_kind_of(SmartwaiverTemplateClient) end it "#list" do path = "#{API_URL}/v4/templates" FakeWeb.register_uri(:get, path, :body => json_template_list_results) result = @client.list expect(result[:templates].length).to eq(3) end it "#get" do template_id = "586ffe15134bc" path = "#{API_URL}/v4/templates/#{template_id}" FakeWeb.register_uri(:get, path, :body => json_template_single_results) result = @client.get(template_id) expect(result[:template][:templateId]).to eq(template_id) end end end
junara/kindle_stocker
lib/kindle_stocker/config.rb
# frozen_string_literal: true require 'yaml' require 'active_support/all' module KindleStocker class Config extend Forwardable attr_reader :yaml def initialize(lang = 'ja') common_hash = HashWithIndifferentAccess.new(YAML.load_file(File.join(__dir__, 'config', common_filename))) custom_hash = HashWithIndifferentAccess.new(YAML.load_file(File.join(__dir__, 'config', custom_filename(lang.to_s)))) @yaml = common_hash.deep_merge(custom_hash) end def sign_in yaml[:sign_in] end def book yaml[:book] end def books yaml[:books] end private def common_filename 'common.yml' end def custom_filename(lang) "#{lang}.yml" end end end
junara/kindle_stocker
lib/kindle_stocker/base.rb
<reponame>junara/kindle_stocker # frozen_string_literal: true require 'forwardable' module KindleStocker class Base extend Forwardable delegate %i[sign_in sign_out] => :sign_in_browser attr_reader :browser, :sign_in_browser, :lang def initialize(browser_path: nil, system: :mac, lang: :ja) @browser = KindleStocker::Browser.new(browser_path: browser_path, system: system) @sign_in_browser = KindleStocker::SignIn.new(@browser, lang) @kindle_stocker_books = KindleStocker::Books.new @lang = lang end def cache_clear browser.cookies.clear end def load_books pp "Start loading highlighted book list at #{Time.now}" @kindle_stocker_books.load(@browser, @lang) pp "End loading highlighted book list at #{Time.now}" end def load_highlights pp "Start loading highlights for each books at #{Time.now}" @kindle_stocker_books.collection.each do |book| pp "Getting #{book.asin} #{book.title} highlights at #{Time.now}" book.load(@browser, @lang) end pp "End loading highlights for each books at #{Time.now}" end def books @kindle_stocker_books.collection end end end
junara/kindle_stocker
lib/kindle_stocker/browser.rb
# frozen_string_literal: true require 'forwardable' require 'ferrum' require_relative 'sign_in' module KindleStocker class Browser extend Forwardable delegate %i[goto at_css screenshot cookies css] => :browser attr_reader :browser def initialize(browser_path: nil, system: :mac) config_path = KindleStocker::Config.new.yaml[:google_chrome][:path] @browser = Ferrum::Browser.new( browser_path: browser_path || browser_path_by_system(system, config_path), browser_options: { 'no-sandbox': nil } # active only docker env ) end private def browser_path_by_system(system, config_path) case system.to_sym when :mac_os, :mac, :macos, :apple config_path[:mac] when :ubuntu, :linux config_path[:linux] end end end end
junara/kindle_stocker
lib/kindle_stocker/books.rb
# frozen_string_literal: true module KindleStocker class Books attr_reader :browser, :base_url, :collection def initialize @collection = [] end def load(browser, lang) @collection = [] config = KindleStocker::Config.new(lang) browser.goto(config.books[:url]) sleep(1) nodes = browser.css(config.books[:books_css]) sleep(1) return nil if nodes.nil? nodes.map do |node| book = KindleStocker::Book.new book.assign_params( asin: node.attribute(config.books[:book][:asin_css]), title: node.at_css(config.books[:book][:title_css])&.text, authors: node.at_css(config.books[:book][:authors_css])&.text ) add_book(book) end end def add_book(book) raise 'Only KindleStocker::Book' unless book.is_a?(KindleStocker::Book) @collection << book end end end
junara/kindle_stocker
lib/kindle_stocker/sign_in.rb
# frozen_string_literal: true module KindleStocker class SignIn attr_reader :browser, :email_input_css, :password_input_css, :url, :sign_in_submit_css, :config def initialize(browser, lang) @config = KindleStocker::Config.new(lang) @browser = browser @url = config.sign_in[:url] @email_input_css = config.sign_in[:email_input_css] @password_input_css = config.sign_in[:password_input_css] @sign_in_submit_css = config.sign_in[:sign_in_submit_css] end def sign_in(email, password) browser.goto(url) sleep(1) fill_and_submit(browser, email, password) sleep(1) wait_for_sign_in(browser) end def sign_out browser.goto(url) sleep(1) click_sign_out(browser) if sign_in?(browser) end private def sign_in?(browser) browser.goto(url) unless sign_in_url?(browser) browser.screenshot(path: "./tmp/#{Time.now}.png") browser.at_css(config.sign_in[:signed_in_css]).present? end def sign_in_url?(browser) URI.parse(browser.browser.current_url).host == URI.parse(@url).host end def click_sign_out(browser) browser.at_css('#kp-notebook-head > div > div.a-column.a-span3.a-text-right.a-spacing-top-mini.a-span-last > span > a').click browser.at_css('#a-popover-content-1 > table > tbody > tr:nth-child(5) > td > a').click end def fill_and_submit(browser, email, password) browser.at_css(email_input_css).focus.type(email) browser.at_css(password_input_css).focus.type(password) browser.at_css(sign_in_submit_css).click end def wait_for_sign_in(browser, max_num = 60) max_num.times do |i| pp "wait #{i} sec (max #{max_num} sec)" sleep(1) if sign_in?(browser) pp 'signed in !' break end end end end end
junara/kindle_stocker
lib/kindle_stocker/highlight.rb
# frozen_string_literal: true module KindleStocker class Highlight attr_accessor :id, :location, :note, :highlight def initialize(id:, location: nil, note: nil, highlight: nil) @id = id @location = location @note = note @highlight = highlight end end end
junara/kindle_stocker
lib/kindle_stocker/book.rb
# frozen_string_literal: true module KindleStocker class Book attr_accessor :asin, :img_src, :title, :authors, :last_accessed_date, :highlights def initialize @highlights = [] end def assign_params(asin:, img_src: nil, title: nil, authors: nil, last_accessed_date: nil) @asin = asin @img_src = img_src @title = title @authors = authors @last_accessed_date = last_accessed_date end def load(browser, lang) sleep(0.5) load_book(browser, lang) sleep(0.5) load_highlights(browser, lang) end def book_url(asin, base_url) base_url + URI.encode_www_form([['asin', asin], ['contentLimitState', '']]) end def add_highlight(highlight) @highlights << highlight end private def load_book(browser, lang) config = KindleStocker::Config.new(lang) base_url = config.book[:base_url] browser.goto(book_url(@asin, base_url)) assign_params( asin: @asin, img_src: browser.at_css('img')&.attribute('src'), title: browser.at_css('h3.kp-notebook-metadata')&.text, authors: browser.at_css('p.a-spacing-none.a-spacing-top-micro.a-size-base.a-color-secondary.kp-notebook-selectable.kp-notebook-metadata')&.text ) end def load_highlights(browser, lang) config = KindleStocker::Config.new(lang) base_url = config.book[:base_url] browser.goto(book_url(@asin, base_url)) nodes = browser.at_css('#kp-notebook-annotations').css('div.a-row.a-spacing-base') nodes.each do |node| highlight = KindleStocker::Highlight.new( id: node.attribute('id'), highlight: node.at_css('#highlight')&.text, note: node.at_css('#note')&.text ) add_highlight(highlight) end end end end
junara/kindle_stocker
lib/kindle_stocker.rb
# frozen_string_literal: true require_relative 'kindle_stocker/version' require_relative 'kindle_stocker/sign_in' require_relative 'kindle_stocker/browser' require_relative 'kindle_stocker/config' require_relative 'kindle_stocker/base' require_relative 'kindle_stocker/books' require_relative 'kindle_stocker/book' require_relative 'kindle_stocker/highlight' module KindleStocker class Error < StandardError; end end
pre/apila
spec/species_spec.rb
<reponame>pre/apila<filename>spec/species_spec.rb require "#{File.dirname(__FILE__)}/spec_helper" describe 'Species' do before(:each) do end specify 'should have translated names' do species = Factory.create(:species) species.names.first(:language => 'S').should_not be_blank end specify 'should return a filtered array of species' do code = "GAVS" valid = [] ["#{code}AA", code, "#{code}CC", "#{code}1"].each do |matched_code| valid << Factory.create(:species, :code => matched_code) end matched = Species.filter_by_code(code) valid.each do |m| matched.should include(m) end end specify 'should return only the requested municipalities' do code = "GAVS" invalid = [] valid = Factory.create(:species, :code => "#{code}A") ["AABC", "A#{code}", "CC", "AA"].each do |unmatched_code| invalid << Factory.create(:species, :code => unmatched_code) end matched = Species.filter_by_code(code) matched.should include(valid) invalid.each do |m| matched.should_not include(m) end end specify 'should query with all when code is empty' do Species.should_receive(:all).with(no_args()) Species.filter_by_code("") end end
pre/apila
spec/application_spec.rb
require "#{File.dirname(__FILE__)}/spec_helper" describe 'Application' do include Rack::Test::Methods def app Sinatra::Application.new end specify 'should show the default index page' do get '/' last_response.should be_ok end describe 'API XML responses' do specify 'should return 404 when requesting one entry which is not found' do ["/ringers/1.xml", "/municipalities/abc.xml"].each do |uri| get uri last_response.status.should be(404) end end specify 'should return ringer xml' do id = 10000 ringer = Factory.build(:ringer, :id => id) Ringer.stub!(:first).and_return(ringer) get "/ringers/#{id}.xml" last_response.should be_ok last_response.body.should include("<email>#{ringer.email}</email>") last_response.body.should include("<name>#{ringer.name}</name>") end describe 'for municipalities' do specify 'should include environment centre in municipality xml' do xml_response = "<xml lol='cat'>" municipality = Factory.build(:municipality) municipality.should_receive(:to_xml).with(:methods => [:environment_centre], :only => Municipality.shared_attributes).and_return(xml_response) Municipality.stub!(:first).and_return(municipality) get "/municipalities/#{municipality.code}.xml" last_response.body.should == xml_response end specify 'should produce an xml set of all municipalities' do xml_response = "lolcat" municipalities = mock(Object) municipalities.should_receive(:to_xml).and_return(xml_response) Municipality.should_receive(:filter_by_code).and_return(municipalities) get "/municipalities.xml" last_response.body.should == xml_response end specify 'should return code 200 when filtered resultset is empty' do get "/municipalities.xml?code=DOES_NOT_EXIST" last_response.status.should be(200) end end describe 'for species' do specify 'should produce an xml set of all species' do species = mock(DataMapper::Collection) species.should_receive(:to_xml) Species.should_receive(:filter_by_code).and_return(species) get "/species.xml" last_response.should be_ok end specify 'should include species name in the response' do finnish = Factory.build(:lexicon, :content => "Haikara") english = Factory.build(:lexicon, :content => "Stork", :language => "E") species = Factory.build(:species, :names => [finnish, english]) Species.stub!(:filter_by_code).and_return(species) get "/species.xml" last_response.should be_ok last_response.body.should include("Haikara", "Stork") end specify 'should return code 200 when filtered resultset is empty' do get "/species.xml?code=DOES_NOT_EXIST" last_response.status.should be(200) end end end end
pre/apila
lib/lexicon.rb
class Lexicon include DataMapper::Resource storage_names[:default] = 'sanasto' property :category, Integer, :field => 'satunnus', :required => true, :key => true property :language, String, :field => 'sakieli', :required => true, :key => true property :code, String, :field => 'sakoodi', :key => true property :abbreviation, String, :field => 'salyh' property :content, String, :field => 'sateksti' has n, :species, :parent_key => :code, :child_key => :id end
pre/apila
lib/ringer.rb
<filename>lib/ringer.rb class Ringer include DataMapper::Resource storage_names[:default] = 'rengastaja' property :id, Serial, :field => 'renro' property :email, String, :field => 'reemail' property :first_name, String, :field => 'reetunimi' property :last_name, String, :field => 'resukunimi' def name self.first_name + " " + self.last_name end def self.shared_attributes @@shared_attributes ||= [:id, :email, :name] end end
pre/apila
lib/species.rb
class Species include DataMapper::Resource storage_names[:default] = 'laji' property :id, String, :field => 'lanro', :key => true property :code, String, :field => 'lalyh', :required => true has n, :names, 'Lexicon', :parent_key => :id, :child_key => :code, :category => 8 def self.filter_by_code(code) if code.blank? all else all :code.like => "#{code.to_s.upcase}%" end end def self.shared_attributes @@shared_attributes ||= [:id, :code] end end
pre/apila
config.ru
require 'application' set :run, false set :environment, ENV['RACK_ENV'].to_sym FileUtils.mkdir_p AppConfig.log.directory unless File.exists?(AppConfig.log.directory) log = File.new(File.join(AppConfig.log.directory, AppConfig.log.filename), "a+") $stdout.reopen(log) $stderr.reopen(log) run Sinatra::Application
pre/apila
lib/environment_centre.rb
<reponame>pre/apila<filename>lib/environment_centre.rb class EnvironmentCentre include DataMapper::Resource storage_names[:default] = 'ympkesk' property :id, Serial, :field => 'ympk_numero', :required => true, :key => true property :name, String, :field => 'ympk_nimi', :required => true has n, :municipalities end
pre/apila
lib/municipality.rb
class Municipality include DataMapper::Resource storage_names[:default] = 'kunta' property :id, Serial, :field => 'kunro', :key => true property :code, String, :field => 'kulyh', :required => true property :name, String, :field => 'kunimi' property :latitude, Float, :field => 'kudeslev' property :longitude, Float, :field => 'kudespit' property :radius, Integer, :field => 'kusade' property :environment_centre_id, Integer, :field => 'ku_ympkesk' belongs_to :environment_centre, :required => false def self.filter_by_code(code) if code.blank? all else all :code.like => "#{code.to_s.upcase}%" end end def self.shared_attributes @@shared_attributes ||= [:id, :code, :name, :latitude, :longitude, :radius] end def self.find_by_code(code) first :code => code.to_s.upcase end end
pre/apila
spec/ringer_spec.rb
<filename>spec/ringer_spec.rb require "#{File.dirname(__FILE__)}/spec_helper" describe 'Ringer' do before(:each) do @ringer = Ringer.new(:id => "10000", :first_name => 'Pekka', :last_name => 'Sormisuu', :email => "<EMAIL>") end specify 'should have a name composed of first and last name' do @ringer.name.should == "<NAME>" end end
pre/apila
spec/z_factories.rb
require 'factory_girl' Factory.sequence :email do |n| "<EMAIL>" end Factory.define :ringer do |f| f.first_name "Jouni" f.last_name "Kemppainen" f.email Factory.next(:email) f.sequence(:id) { |n| "#{n}" } end Factory.define :municipality do |f| f.code "AHLAIN" f.name "AHLAINEN" f.longitude 21.6666698 f.latitude 61.6666718 f.radius 20 f.association :environment_centre f.sequence(:id) { |n| "#{n}" } end Factory.define :environment_centre do |f| f.sequence(:name) { |n| "Yleismaailmallinen ymparistokeskus nro #{n}" } f.sequence(:id) { |n| "#{n}" } end Factory.define :species do |f| f.sequence(:id) { |n| "#{n}"} f.sequence(:code) { |n| "GAVS#{n}"} f.names { |names| [names.association(:lexicon)] } end Factory.define :lexicon do |f| f.sequence(:content) { |n| "Harmaahaikara #{n}" } f.sequence(:code) { |n| n } f.category 8 f.language "S" end
pre/apila
environment.rb
<reponame>pre/apila require 'rubygems' require 'dm-core' require 'app_config' require 'json' require 'nokogiri' require 'dm-migrations' require 'dm-serializer' require 'sinatra' unless defined?(Sinatra) configure do # load models $LOAD_PATH.unshift("#{File.dirname(__FILE__)}/lib") Dir.glob("#{File.dirname(__FILE__)}/lib/*.rb") { |lib| require File.basename(lib, '.*') } if Sinatra::Application.environment == :development DataMapper::Logger.new(File.join(AppConfig.log.directory, AppConfig.log.filename), :debug) end DataMapper.setup(:default, AppConfig.database_url) end
pre/apila
spec/municipality_spec.rb
require "#{File.dirname(__FILE__)}/spec_helper" describe Municipality do specify 'should return a filtered array of municipalities' do code = "AABB" valid = [] ["#{code}AA", code, "#{code}CC", "#{code}1"].each do |matched_code| valid << Factory.create(:municipality, :code => matched_code) end matched = Municipality.filter_by_code(code) valid.each do |m| matched.should include(m) end end specify 'should return only the requested municipalities' do code = "AABB" invalid = [] valid = Factory.create(:municipality, :code => "#{code}AWER") ["AABC", "A#{code}", "CC", "AA"].each do |unmatched_code| invalid << Factory.create(:municipality, :code => unmatched_code) end matched = Municipality.filter_by_code(code) matched.should include(valid) invalid.each do |m| matched.should_not include(m) end end specify 'should query with all when code is empty' do Municipality.should_receive(:all).with(no_args()) Municipality.filter_by_code("") end specify 'should find by downcase code' do code = "AITOLA" municipality = Factory.create(:municipality, :code => code) Municipality.find_by_code(code.downcase).should == municipality end end
pre/apila
application.rb
require 'rubygems' require 'sinatra' require 'environment' configure do set :views, "#{File.dirname(__FILE__)}/views" end error do e = request.env['sinatra.error'] Kernel.puts e.backtrace.join("\n") 'Application error' end helpers do end not_found do content_type :text "404 Not Found" end before do content_type :xml end get '/' do "It works! Please request something." end get '/ringers/:id.xml' do respond_with(Ringer.first(:id => params[:id]), { :methods => [:name], :only => Ringer.shared_attributes }) end get '/municipalities/:code.xml' do respond_with(Municipality.find_by_code(params[:code]), { :methods => [:environment_centre], :only => Municipality.shared_attributes }) end get '/municipalities.xml' do municipalities = Municipality.filter_by_code(params[:code]) municipalities.to_xml(:methods => [:environment_centre], :only => Municipality.shared_attributes) end get '/species.xml' do species = Species.filter_by_code(params[:code]) species.to_xml(:methods => [:names]) end private def respond_with(object, opts = {}) if object object.to_xml(opts) else halt 404 end end
arthurdandrea/sequel-activemodel
lib/sequel-activemodel.rb
<reponame>arthurdandrea/sequel-activemodel require 'sequel/activemodel'
arthurdandrea/sequel-activemodel
lib/sequel/plugins/active_model_callbacks.rb
require 'active_model' module Sequel module Plugins module ActiveModelCallbacks def self.apply(model, *args) model.plugin :active_model model.extend ::ActiveModel::Callbacks model.define_model_callbacks(:save, :create, :update, :destroy) model.define_callbacks(:validation, terminator: ->(_,result) { result == false }, skip_after_callbacks_if_terminated: true, scope: [:kind, :name]) end module InstanceMethods def around_save run_callbacks(:save) do super end end def around_create run_callbacks(:create) do super end end def around_update run_callbacks(:update) do super end end def around_validation run_callbacks(:validation) do super end end def around_destroy run_callbacks(:destroy) do super end end end # InstanceMethods module ClassMethods # Defines a callback that will get called right before validation # happens. # # class Person < Sequel::Model # plugin :active_model_callbacks # plugin :active_model_validations # # validates_length_of :name, maximum: 6 # # before_validation :remove_whitespaces # # private # # def remove_whitespaces # name.strip! # end # end # # person = Person.new # person.name = ' bob ' # person.valid? # => true # person.name # => "bob" def before_validation(*args, &block) options = args.last if options.is_a?(Hash) && options[:on] options[:if] = Array(options[:if]) options[:on] = Array(options[:on]) options[:if].unshift lambda { |o| options[:on].include? o.validation_context } end set_callback(:validation, :before, *args, &block) end # Defines a callback that will get called right after validation # happens. # # class Person < Sequel::Model # plugin :active_model_callbacks # plugin :active_model_validations # validates_presence_of :name # # after_validation :set_status # # private # # def set_status # self.status = errors.empty? # end # end # # person = Person.new # person.name = '' # person.valid? # => false # person.status # => false # person.name = 'bob' # person.valid? # => true # person.status # => true def after_validation(*args, &block) options = args.extract_options! options[:prepend] = true options[:if] = Array(options[:if]) if options[:on] options[:on] = Array(options[:on]) options[:if].unshift("#{options[:on]}.include? self.validation_context") end set_callback(:validation, :after, *(args << options), &block) end end # ClassMethods end # ActiveModelCallbacks end # Plugins end # Sequel
arthurdandrea/sequel-activemodel
spec/spec_helper.rb
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'sequel' require 'sequel/activemodel' require 'sequel/plugins/active_model' # preload require 'sequel/plugins/active_model_callbacks' require 'sequel/plugins/active_model_translations' require 'sequel/plugins/active_model_validations'
arthurdandrea/sequel-activemodel
sequel-activemodel.gemspec
<reponame>arthurdandrea/sequel-activemodel<filename>sequel-activemodel.gemspec # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'sequel/activemodel/version' Gem::Specification.new do |spec| spec.name = 'sequel-activemodel' spec.version = Sequel::ActiveModel::VERSION spec.authors = ["<NAME>"] spec.email = ['<EMAIL>'] spec.summary = %q{Provides Sequel::Model plugins that expose ActiveModel::Callbacks, ActiveModel::Translation and ActiveModel::Validations features to Sequel::Model} spec.homepage = 'https://github.com/arthurdandrea/sequel-activemodel' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_runtime_dependency 'sequel' spec.add_runtime_dependency 'activemodel' spec.add_development_dependency 'bundler', '~> 1.10' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec' spec.add_development_dependency 'sqlite3' end
arthurdandrea/sequel-activemodel
lib/sequel/plugins/active_model_validations.rb
require 'active_model' module Sequel::Validations def self.const_missing(name) begin const = ActiveModel::Validations.const_get(name) rescue NameError const = super end const_set(name, const) const end class UniquenessValidator < ActiveModel::EachValidator def initialize(options) super(options.reverse_merge(case_sensitive: true)) end def validate_each(record, attribute, value) arr = Array.wrap(attribute) arr.concat Array.wrap(options[:scope]) return if options[:only_if_modified] && !record.new? && !arr.any? { |x| record.changed_columns.include?(x) } ds = record.model.filter(arr.map { |x| [x, record.send(x)] }) ds = ds.exclude(record.pk_hash) unless record.new? if ds.count > 0 record.errors.add(attribute, :taken, options.except(:case_sensitive, :scope).merge(value: value)) end end end end module Sequel::Plugins::ActiveModelValidations def self.apply(model, *args) model.plugin :active_model_callbacks model.plugin :active_model_translations model.define_callbacks :validate, scope: :name model.class_eval do @validation_reflections = Hash.new { |h,k| h[k] = [] } end model.extend ::ActiveModel::Validations::HelperMethods end module InstanceMethods def errors @errors ||= ::ActiveModel::Errors.new(self) end def validate super run_callbacks :validate end def invalid? !valid? end def read_attribute_for_validation(attr) send(attr) end end module ClassMethods Sequel::Plugins.inherited_instance_variables(self, :@validation_reflections => proc { |oldval| newval = Hash.new { |h, k| h[k] = [] } oldval.each { |k,v| newval[k] = v.map(&:dup) } newval }) attr_reader :validation_reflections # Adds a validation method or block to the class. This is useful when # overriding the +validate+ instance method becomes too unwieldy and # you're looking for more descriptive declaration of your validations. # # This can be done with a symbol pointing to a method: # # class Comment # include ActiveModel::Validations # # validate :must_be_friends # # def must_be_friends # errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee) # end # end # # With a block which is passed with the current record to be validated: # # class Comment # include ActiveModel::Validations # # validate do |comment| # comment.must_be_friends # end # # def must_be_friends # errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee) # end # end # # Or with a block where self points to the current record to be validated: # # class Comment # include ActiveModel::Validations # # validate do # errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee) # end # end # def validate(*args, &block) options = args.extract_options! if options.key?(:on) options = options.dup options[:if] = Array.wrap(options[:if]) options[:if].unshift("validation_context == :#{options[:on]}") end args << options set_callback(:validate, *args, &block) end def validates_with(*args, &block) options = args.extract_options! args.each do |klass| options[:class] = self validator = klass.new(options, &block) validator.setup(self) if validator.respond_to?(:setup) if validator.respond_to?(:attributes) && !validator.attributes.empty? validator.attributes.each do |attribute| @validation_reflections[attribute.to_sym] << validator end else @validation_reflections[nil] << validator end validate(validator, options) end end # Validates whether the value of the specified attributes are unique across the system. # Useful for making sure that only one user # can be named "davidhh". # # class Person < Sequel::Model # plugin :active_model_validations # validates_uniqueness_of :user_name # end # # It can also validate whether the value of the specified attributes are unique based on a scope parameter: # # class Person < Sequel::Model # plugin :active_model_validations # validates_uniqueness_of :user_name, :scope => :account_id # end # # Or even multiple scope parameters. For example, making sure that a teacher can only be on the schedule once # per semester for a particular class. # # class TeacherSchedule < Sequel::Model # plugin :active_model_validations # validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id] # end # # When the record is created, a check is performed to make sure that no record exists in the database # with the given value for the specified attribute (that maps to a column). When the record is updated, # the same check is made but disregarding the record itself. # # Configuration options: # * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken"). # * <tt>:scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint. # * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (+true+ by default). # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+). # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+). # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). # The method, proc or string should return or evaluate to a true or false value. # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should # not occur (e.g. <tt>:unless => :skip_validation</tt>, or # <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The method, proc or string should # return or evaluate to a true or false value. # def validates_uniqueness_of(*attr_names) validates_with Sequel::Validations::UniquenessValidator, _merge_attributes(attr_names) end # This method is a shortcut to all default validators and any custom # validator classes ending in 'Validator'. Note that Rails default # validators can be overridden inside specific classes by creating # custom validator classes in their place such as PresenceValidator. # # Examples of using the default rails validators: # # validates :terms, :acceptance => true # validates :password, :confirmation => true # validates :username, :exclusion => { :in => %w(admin superuser) } # validates :email, :format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create } # validates :age, :inclusion => { :in => 0..9 } # validates :first_name, :length => { :maximum => 30 } # validates :age, :numericality => true # validates :username, :presence => true # validates :username, :uniqueness => true # # The power of the +validates+ method comes when using custom validators # and default validators in one call for a given attribute e.g. # # class EmailValidator < ActiveModel::EachValidator # def validate_each(record, attribute, value) # record.errors[attribute] << (options[:message] || "is not an email") unless # value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i # end # end # # class Person < Sequel::Model # plugin :active_model_validations # attr_accessor :name, :email # # validates :name, :presence => true, :uniqueness => true, :length => { :maximum => 100 } # validates :email, :presence => true, :email => true # end # # Validator classes may also exist within the class being validated # allowing custom modules of validators to be included as needed e.g. # # class Film < Sequel::Model # plugin :active_model_validations # # class TitleValidator < ActiveModel::EachValidator # def validate_each(record, attribute, value) # record.errors[attribute] << "must start with 'the'" unless value =~ /\Athe/i # end # end # # validates :name, :title => true # end # # Additionally validator classes may be in another namespace and still used within any class. # # validates :name, :'file/title' => true # # The validators hash can also handle regular expressions, ranges, # arrays and strings in shortcut form, e.g. # # validates :email, :format => /@/ # validates :gender, :inclusion => %w(male female) # validates :password, :length => 6..20 # # When using shortcut form, ranges and arrays are passed to your # validator's initializer as +options[:in]+ while other types including # regular expressions and strings are passed as +options[:with]+ # # Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+ and +:allow_nil+ can be given # to one specific validator, as a hash: # # validates :password, :presence => { :if => :password_required? }, :confirmation => true # # Or to all at the same time: # # validates :password, :presence => true, :confirmation => true, :if => :password_required? # def validates(*attributes) defaults = attributes.extract_options! validations = defaults.slice!(*_validates_default_keys) raise ArgumentError, "You need to supply at least one attribute" if attributes.empty? raise ArgumentError, "You need to supply at least one validation" if validations.empty? defaults.merge!(attributes: attributes) validations.each do |key, options| key = "#{key.to_s.camelize}Validator" begin validator = key.include?('::') ? key.constantize : Sequel::Validations.const_get(key) rescue NameError raise ArgumentError, "Unknown validator: '#{key}'" end validates_with(validator, defaults.merge(_parse_validates_options(options))) end end protected # When creating custom validators, it might be useful to be able to specify # additional default keys. This can be done by overwriting this method. def _validates_default_keys [ :if, :unless, :on, :allow_blank, :allow_nil ] end def _parse_validates_options(options) #:nodoc: case options when TrueClass {} when Hash options when Range, Array { in: options } else { with: options } end end end end
arthurdandrea/sequel-activemodel
spec/sequel/plugins/active_model_callbacks_spec.rb
<reponame>arthurdandrea/sequel-activemodel require 'spec_helper' describe Sequel::Plugins::ActiveModelCallbacks do let(:db) do db = Sequel.sqlite db.execute "CREATE TABLE tablename(a,b);" db end let(:model) do model = Class.new(Sequel.Model(db[:tablename])) model.plugin :active_model_callbacks model end # filter out the Sequel::Model from the plugins Array # it is causing trouble with rspec beautiful error generation let(:plugins) do model.plugins.select do |plugin| plugin != Sequel::Model end end it 'loads :active_model plugin' do expect(plugins).to include Sequel::Plugins::ActiveModel end describe 'before_save' do it "calls the block when #save is called" do callback = double("callback") model.before_save do callback.call end expect(callback).to receive(:call).once model.new.save end it "calls the method when #save is called" do callback = double("callback") model.send :define_method, :before_save_callback do callback.call end model.before_save :before_save_callback expect(callback).to receive(:call).once model.new.save end end describe 'after_save' do it "calls the block when #save is called" do callback = double("callback") model.after_save do callback.call end expect(callback).to receive(:call).once model.new.save end it "calls the method when #save is called" do callback = double("callback") model.send :define_method, :after_save_callback do callback.call end model.after_save :after_save_callback expect(callback).to receive(:call).once model.new.save end end end
arthurdandrea/sequel-activemodel
lib/sequel/plugins/active_model_translations.rb
require 'active_model' module Sequel module Plugins module ActiveModelTranslations def self.apply(model) model.plugin :active_model end module ClassMethods include ::ActiveModel::Translation # Set the i18n scope to overwrite ActiveModel. def i18n_scope #:nodoc: :sequel end def lookup_ancestors #:nodoc: self.ancestors.select do |x| x.respond_to?(:model_name) end end end end end end
arthurdandrea/sequel-activemodel
lib/sequel/activemodel/version.rb
module Sequel module ActiveModel VERSION = '0.1.0' end end
arthurdandrea/sequel-activemodel
spec/sequel/plugins/active_model_translations_spec.rb
<gh_stars>1-10 require 'spec_helper' describe Sequel::Plugins::ActiveModelTranslations do let(:model) do model = Class.new(Sequel::Model) model.plugin :active_model_translations model end # filter out the Sequel::Model from the plugins Array # it is causing trouble with rspec beautiful error generation let(:plugins) do model.plugins.select do |plugin| plugin != Sequel::Model end end it 'loads the :active_model plugin' do expect(plugins).to include(Sequel::Plugins::ActiveModel) end end