CombinedText stringlengths 4 3.42M |
|---|
cask 'noraswitch' do
version '1.0.0'
sha256 '974fdf4a2d3920b85fadf22e238442414081d332ab41b090718785af9cc9d6e4'
url "https://noraswitch.com/dmg/noraSwitch%20#{version}.dmg"
appcast 'https://noraswitch.com/appcast.xml'
name 'noraSwitch'
homepage 'https://noraswitch.com/'
depends_on macos: '>= :mojave'
app 'noraSwitch.app'
uninstall quit: 'com.trrn.noraSwitch',
launchctl: 'com.trrn.noraSwitch-LaunchAtLoginHelper'
zap trash: [
'~/Library/Application Support/com.trrn.noraSwitch',
'~/Library/Caches/com.trrn.noraSwitch',
'~/Library/Preferences/com.trrn.noraSwitch.plist',
]
end
Update noraswitch from 1.0.0 to 1.0.1 (#83622)
cask 'noraswitch' do
version '1.0.1'
sha256 '4027f96ad1ad2f95720eefb72a02e3d9cabd67558074fca515275a9c7205a224'
url "https://noraswitch.com/dmg/noraSwitch%20#{version}.dmg"
appcast 'https://noraswitch.com/appcast.xml'
name 'noraSwitch'
homepage 'https://noraswitch.com/'
depends_on macos: '>= :mojave'
app 'noraSwitch.app'
uninstall quit: 'com.trrn.noraSwitch',
launchctl: 'com.trrn.noraSwitch-LaunchAtLoginHelper'
zap trash: [
'~/Library/Application Support/com.trrn.noraSwitch',
'~/Library/Caches/com.trrn.noraSwitch',
'~/Library/Preferences/com.trrn.noraSwitch.plist',
]
end
|
cask 'one-switch' do
version '1.9.1,216'
sha256 '7165f18c7e201ace33c8aa43eed7a78051c2cb050fe782da862243f96813c96c'
url "https://fireball.studio/api/release_manager/downloads/studio.fireball.OneSwitch/#{version.after_comma}.zip"
appcast 'https://fireball.studio/api/release_manager/studio.fireball.OneSwitch.xml'
name 'One Switch'
homepage 'https://fireball.studio/oneswitch'
depends_on macos: '>= :mojave'
app 'One Switch.app'
end
Update one-switch from 1.9.1,216 to 1.9.2,221 (#75561)
cask 'one-switch' do
version '1.9.2,221'
sha256 '923b6d2022c2f2e604f652d651e6e9f111bae3bc3552a66d7a6646e7bb67725a'
url "https://fireball.studio/api/release_manager/downloads/studio.fireball.OneSwitch/#{version.after_comma}.zip"
appcast 'https://fireball.studio/api/release_manager/studio.fireball.OneSwitch.xml'
name 'One Switch'
homepage 'https://fireball.studio/oneswitch'
depends_on macos: '>= :mojave'
app 'One Switch.app'
end
|
cask "opera-beta" do
version "79.0.4143.15"
sha256 "e281c4575b5e8fedf936262b7523b366fa95d69d5c5d9f865197358b67ee0aaa"
url "https://get.geo.opera.com/pub/opera-beta/#{version}/mac/Opera_beta_#{version}_Setup.dmg"
name "Opera Beta"
desc "Web browser"
homepage "https://www.opera.com/computer/beta"
livecheck do
url "https://get.geo.opera.com/pub/opera-beta/"
regex(%r{href=["']?v?(\d+(?:\.\d+)+)/?["' >]}i)
end
auto_updates true
app "Opera Beta.app"
end
Update opera-beta from 79.0.4143.15 to 79.0.4143.19 (#11907)
cask "opera-beta" do
version "79.0.4143.19"
sha256 "53d761a132476b437e3e11cdabdb5065b0142231259d3e7608e095024c8b9d00"
url "https://get.geo.opera.com/pub/opera-beta/#{version}/mac/Opera_beta_#{version}_Setup.dmg"
name "Opera Beta"
desc "Web browser"
homepage "https://www.opera.com/computer/beta"
livecheck do
url "https://get.geo.opera.com/pub/opera-beta/"
regex(%r{href=["']?v?(\d+(?:\.\d+)+)/?["' >]}i)
end
auto_updates true
app "Opera Beta.app"
end
|
cask "pdf-expert" do
version "2.5.10,714"
sha256 "fd8d1b3f147cdfe8fa79f66d9be4ce9907e2f302e82ece6b172ef7d797d82eef"
# d1ke680phyeohy.cloudfront.net/ was verified as official when first introduced to the cask
url "https://d1ke680phyeohy.cloudfront.net/versions/#{version.after_comma}/PDFExpert.dmg"
appcast "https://d1ke680phyeohy.cloudfront.net/release/appcast.xml"
name "PDF Expert"
homepage "https://pdfexpert.com/"
auto_updates true
depends_on macos: ">= :sierra"
app "PDF Expert.app"
end
Update pdf-expert from 2.5.10,714 to 2.5.11,716 (#88071)
cask "pdf-expert" do
version "2.5.11,716"
sha256 "1a8d76f5cd454b55dfc183143603df3add757c79ee9dded31478a95eff9e5b03"
# d1ke680phyeohy.cloudfront.net/ was verified as official when first introduced to the cask
url "https://d1ke680phyeohy.cloudfront.net/versions/#{version.after_comma}/PDFExpert.dmg"
appcast "https://d1ke680phyeohy.cloudfront.net/release/appcast.xml"
name "PDF Expert"
homepage "https://pdfexpert.com/"
auto_updates true
depends_on macos: ">= :sierra"
app "PDF Expert.app"
end
|
cask "qt-creator" do
version "5.0.3"
sha256 "ff3a341500f7de7d5e4129651db64c2b8464a56aac91f43db3ed375f6ea8f371"
url "https://download.qt.io/official_releases/qtcreator/#{version.major_minor}/#{version}/qt-creator-opensource-mac-x86_64-#{version}.dmg"
name "Qt Creator"
desc "IDE for application development"
homepage "https://www.qt.io/developers/"
# It's necessary to check within a major/minor version directory
# (fetching an additional page) to obtain the full version.
livecheck do
url "https://download.qt.io/official_releases/qtcreator/?C=M;O=D"
strategy :page_match do |page|
# These version directories can sometimes be empty, so this will check
# directory pages until it finds versions
page.scan(%r{href=["']?v?(\d+(?:\.\d+)+)/?["' >]}i).lazy.map do |match|
version_page = Homebrew::Livecheck::Strategy.page_content(url.sub("/?", "/#{match[0]}/?"))
next if version_page[:content].blank?
versions = version_page[:content].scan(%r{href=["']?v?(\d+(?:\.\d+)+)/?["' >]}i).map(&:first)
next if versions.blank?
versions
end.reject(&:nil?).first
end
end
depends_on macos: ">= :sierra"
app "Qt Creator.app"
zap trash: [
"~/Library/Preferences/com.qtproject.QtCreator.plist",
"~/Library/Preferences/org.qt-project.qtcreator.plist",
"~/Library/Saved Application State/org.qt-project.qtcreator.savedState",
]
end
Update qt-creator from 5.0.3 to 6.0.0 (#115262)
cask "qt-creator" do
version "6.0.0"
sha256 "ce3e314f965d527937f146b71549cba250f3a919b1838dbd79e40a4141a3fc12"
url "https://download.qt.io/official_releases/qtcreator/#{version.major_minor}/#{version}/qt-creator-opensource-mac-x86_64-#{version}.dmg"
name "Qt Creator"
desc "IDE for application development"
homepage "https://www.qt.io/developers/"
# It's necessary to check within a major/minor version directory
# (fetching an additional page) to obtain the full version.
livecheck do
url "https://download.qt.io/official_releases/qtcreator/?C=M;O=D"
strategy :page_match do |page|
# These version directories can sometimes be empty, so this will check
# directory pages until it finds versions
page.scan(%r{href=["']?v?(\d+(?:\.\d+)+)/?["' >]}i).lazy.map do |match|
version_page = Homebrew::Livecheck::Strategy.page_content(url.sub("/?", "/#{match[0]}/?"))
next if version_page[:content].blank?
versions = version_page[:content].scan(%r{href=["']?v?(\d+(?:\.\d+)+)/?["' >]}i).map(&:first)
next if versions.blank?
versions
end.reject(&:nil?).first
end
end
depends_on macos: ">= :sierra"
app "Qt Creator.app"
zap trash: [
"~/Library/Preferences/com.qtproject.QtCreator.plist",
"~/Library/Preferences/org.qt-project.qtcreator.plist",
"~/Library/Saved Application State/org.qt-project.qtcreator.savedState",
]
end
|
cask "rescuetime" do
version "2.15.0.1"
sha256 "4df6804e31ee27df280aa6b20f80e7d2cf0c5e94e42a0659c2bd2e434d26bd7d"
url "https://www.rescuetime.com/installers/RescueTimeInstaller.pkg"
appcast "https://www.rescuetime.com/installers/appcast"
name "RescueTime"
homepage "https://www.rescuetime.com/"
pkg "RescueTimeInstaller.pkg"
uninstall pkgutil: "com.rescuetime.RescueTime"
zap trash: [
"~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.rescuetime.rescuetime.sfl*",
"~/Library/Caches/com.rescuetime.RescueTime",
"~/Library/Preferences/com.rescuetime.RescueTime.plist",
"~/Library/RescueTime.com",
]
end
Update rescuetime (#86937)
cask "rescuetime" do
version "2.15.0.1"
sha256 "c04bc4ff880317ce5558687a8d396c67a7d5ef8d163f2dc1da4c8b8669e34922"
url "https://www.rescuetime.com/installers/RescueTimeInstaller.pkg"
appcast "https://www.rescuetime.com/installers/appcast"
name "RescueTime"
homepage "https://www.rescuetime.com/"
pkg "RescueTimeInstaller.pkg"
uninstall pkgutil: "com.rescuetime.RescueTime"
zap trash: [
"~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.rescuetime.rescuetime.sfl*",
"~/Library/Caches/com.rescuetime.RescueTime",
"~/Library/Preferences/com.rescuetime.RescueTime.plist",
"~/Library/RescueTime.com",
]
end
|
cask 'screenflow' do
version '6.0'
sha256 '13bb451c96f08cc6bc1d542d71e3a39126f92ecd8cebb0c05101429504e8530c'
url "https://www.telestream.net/download-files/screenflow/#{version.dots_to_hyphens}/ScreenFlow-#{version}.dmg"
appcast 'https://www.telestream.net/updater/screenflow/appcast.xml',
checkpoint: '3be8f24b6237d929e2d94d735e6129dfd8162d885523a275bef4b30efd0e97de'
name 'ScreenFlow'
homepage 'https://www.telestream.net/screenflow/'
license :commercial
auto_updates true
depends_on macos: '>= :yosemite'
app 'ScreenFlow.app'
end
updated screenflow (6.1) (#24052)
cask 'screenflow' do
version '6.1'
sha256 'bb32f1f2eaff52e39d2f2fb9cef623cc2390af0606c9bd6497c12c91a4a6ec24'
url "https://www.telestream.net/download-files/screenflow/#{version.dots_to_hyphens}/ScreenFlow-#{version}.dmg"
appcast 'https://www.telestream.net/updater/screenflow/appcast.xml',
checkpoint: 'aa20375740264cf5ecf4e6ed56a0f258f91631fc95f0e71783793840604ed2b9'
name 'ScreenFlow'
homepage 'https://www.telestream.net/screenflow/'
license :commercial
auto_updates true
depends_on macos: '>= :yosemite'
app 'ScreenFlow.app'
end
|
cask 'screenflow' do
version '6.2.2'
sha256 '93d82f6e52db68b41c899e3221e08620df8c2bee8b82ffd07f384a8c1deaea96'
url "https://www.telestream.net/download-files/screenflow/#{version.major_minor.dots_to_hyphens}/ScreenFlow-#{version}.dmg"
appcast 'https://www.telestream.net/updater/screenflow/appcast.xml',
checkpoint: 'd4f5505fab9e422c897ee659aff793d023130c7de5e004d2ca9746668f6c0e8c'
name 'ScreenFlow'
homepage 'https://www.telestream.net/screenflow/'
auto_updates true
depends_on macos: '>= :yosemite'
app 'ScreenFlow.app'
end
Update screenflow to 7.0 (#38309)
cask 'screenflow' do
version '7.0'
sha256 '25b010fe9bf1c8f7721fb7950619c2cdaf68ae448b4da90464ed2e4c37207e5b'
url "https://www.telestream.net/download-files/screenflow/#{version.major_minor.dots_to_hyphens}/ScreenFlow-#{version}.dmg"
appcast 'https://www.telestream.net/updater/screenflow/appcast.xml',
checkpoint: '9b5177fa05ec22ef90bd78f0e43fae0da4722df250c897b33ea12fa9d3990bc1'
name 'ScreenFlow'
homepage 'https://www.telestream.net/screenflow/'
auto_updates true
depends_on macos: '>= :yosemite'
app 'ScreenFlow.app'
end
|
cask 'sidneys-pb' do
version '6.3.1'
sha256 '6cf111cccab7f25bcd053cbed30e4c95fd9e8a8060bafed0f0a75a7e42bb83d5'
url "https://github.com/sidneys/pb-for-desktop/releases/download/v#{version}/pb-for-desktop-#{version}.dmg"
appcast 'https://github.com/sidneys/pb-for-desktop/releases.atom',
checkpoint: 'b41a00d18ace2654c1a99442d1fc17d68cdff8b34f39993702f361b84d6dd80a'
name 'PB for Desktop'
homepage 'https://github.com/sidneys/pb-for-desktop'
app 'PB for Desktop.app'
zap trash: [
'~/Library/Application Support/PB for Desktop',
'~/Library/Caches/de.sidneys.pb-for-desktop',
'~/Library/Logs/pb-for-desktop',
'~/Library/Preferences/de.sidneys.pb-for-desktop.plist',
'~/Library/Preferences/de.sidneys.pb-for-desktop.helper.plist',
'~/Library/Saved Application State/de.sidneys.pb-for-desktop.savedState',
]
end
Update sidneys-pb to 6.8.1 (#43516)
cask 'sidneys-pb' do
version '6.8.1'
sha256 '78e1fe47b5b789f45840c7dcf5cbbb94dc5c4ebbdfec7cc0d9c2053edd204e73'
url "https://github.com/sidneys/pb-for-desktop/releases/download/v#{version}/pb-for-desktop-#{version}.dmg"
appcast 'https://github.com/sidneys/pb-for-desktop/releases.atom',
checkpoint: 'c96e3636b5095f2df7780243ce6312000dd3af653d4dc24449d9065864b65fc7'
name 'PB for Desktop'
homepage 'https://github.com/sidneys/pb-for-desktop'
app 'PB for Desktop.app'
zap trash: [
'~/Library/Application Support/PB for Desktop',
'~/Library/Caches/de.sidneys.pb-for-desktop',
'~/Library/Logs/pb-for-desktop',
'~/Library/Preferences/de.sidneys.pb-for-desktop.plist',
'~/Library/Preferences/de.sidneys.pb-for-desktop.helper.plist',
'~/Library/Saved Application State/de.sidneys.pb-for-desktop.savedState',
]
end
|
Add cask for Silverback
class Silverback < Cask
url 'http://silverback.s3.amazonaws.com/silverback2.zip'
homepage 'http://silverbackapp.com/'
version 'latest'
no_checksum
link 'Silverback.app'
end
|
# encoding: UTF-8
class Sogouinput < Cask
version '3.0.0'
sha256 'a11ef502efc364cce4191a0d2e6fb375fe9636438045b522431ac8829b40eae5'
url 'http://download.ime.sogou.com/1409894725/sogou_mac_30.dmg?st=SEx0_y78FJKFl1c6-uEEnA&e=1410158966&fn=sogou_mac_30.dmg'
homepage 'http://pinyin.sogou.com/mac/'
license :unknown
installer :manual => '安装搜狗输入法.app'
uninstall :delete => '/Library/Input Methods/SogouInput.app'
end
re-use version in sogouinput
# encoding: UTF-8
class Sogouinput < Cask
version '3.0.0'
sha256 'a11ef502efc364cce4191a0d2e6fb375fe9636438045b522431ac8829b40eae5'
url "http://download.ime.sogou.com/1409894725/sogou_mac_#{version.sub(%r{^(\d+)\.(\d+).*},'\1\2')}.dmg?st=SEx0_y78FJKFl1c6-uEEnA&e=1410158966&fn=sogou_mac_#{version.sub(%r{^(\d+)\.(\d+).*},'\1\2')}.dmg"
homepage 'http://pinyin.sogou.com/mac/'
license :unknown
installer :manual => '安装搜狗输入法.app'
uninstall :delete => '/Library/Input Methods/SogouInput.app'
end
|
cask 'sourcetree' do
if MacOS.version <= :sierra
version '2.7.6a'
sha256 'd60614e9ab603e0ed158b6473c36e7944b2908d9943e332c505eba03dc1d829e'
# atlassian.com/software/sourcetree/ was verified as official when first introduced to the cask
url "https://downloads.atlassian.com/software/sourcetree/Sourcetree_#{version}.zip"
elsif MacOS.version <= :high_sierra
version '3.2.1_225'
sha256 '4bd82affa3402814c3d07ff613fbc8f45da8b0cda294d498ffbb0667bf729c9f'
# atlassian.com/software/sourcetree/ was verified as official when first introduced to the cask
url "https://product-downloads.atlassian.com/software/sourcetree/ga/Sourcetree_#{version}.zip"
else
version '4.0.1_234'
sha256 'b6b059b6d1c91729bf6c44dac09d79c8ae6e22fefd1bee705c7814a2099c3131'
# atlassian.com/software/sourcetree/ was verified as official when first introduced to the cask
url "https://product-downloads.atlassian.com/software/sourcetree/ga/Sourcetree_#{version}.zip"
end
appcast 'https://product-downloads.atlassian.com/software/sourcetree/Appcast/SparkleAppcastGroup0.xml'
name 'Atlassian SourceTree'
homepage 'https://www.sourcetreeapp.com/'
auto_updates true
depends_on macos: '>= :el_capitan'
app 'Sourcetree.app'
binary "#{appdir}/Sourcetree.app/Contents/Resources/stree"
uninstall launchctl: 'com.atlassian.SourceTreePrivilegedHelper2',
quit: 'com.torusknot.SourceTreeNotMAS'
zap trash: [
'~/Library/Application Support/SourceTree',
'~/Library/Caches/com.torusknot.SourceTreeNotMAS',
'~/Library/Preferences/com.torusknot.SourceTreeNotMAS.plist',
'~/Library/Preferences/com.torusknot.SourceTreeNotMAS.LSSharedFileList.plist',
'~/Library/Saved Application State/com.torusknot.SourceTreeNotMAS.savedState',
]
end
updated zap stanza for Atlassian SourceTree 4.0.1_234 (#83953)
cask 'sourcetree' do
if MacOS.version <= :sierra
version '2.7.6a'
sha256 'd60614e9ab603e0ed158b6473c36e7944b2908d9943e332c505eba03dc1d829e'
# atlassian.com/software/sourcetree/ was verified as official when first introduced to the cask
url "https://downloads.atlassian.com/software/sourcetree/Sourcetree_#{version}.zip"
elsif MacOS.version <= :high_sierra
version '3.2.1_225'
sha256 '4bd82affa3402814c3d07ff613fbc8f45da8b0cda294d498ffbb0667bf729c9f'
# atlassian.com/software/sourcetree/ was verified as official when first introduced to the cask
url "https://product-downloads.atlassian.com/software/sourcetree/ga/Sourcetree_#{version}.zip"
else
version '4.0.1_234'
sha256 'b6b059b6d1c91729bf6c44dac09d79c8ae6e22fefd1bee705c7814a2099c3131'
# atlassian.com/software/sourcetree/ was verified as official when first introduced to the cask
url "https://product-downloads.atlassian.com/software/sourcetree/ga/Sourcetree_#{version}.zip"
end
appcast 'https://product-downloads.atlassian.com/software/sourcetree/Appcast/SparkleAppcastGroup0.xml'
name 'Atlassian SourceTree'
homepage 'https://www.sourcetreeapp.com/'
auto_updates true
depends_on macos: '>= :el_capitan'
app 'Sourcetree.app'
binary "#{appdir}/Sourcetree.app/Contents/Resources/stree"
uninstall launchctl: 'com.atlassian.SourceTreePrivilegedHelper2',
quit: 'com.torusknot.SourceTreeNotMAS'
zap trash: [
'~/Library/Application Support/SourceTree',
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.torusknot.sourcetreenotmas.sfl2',
'~/Library/Caches/com.torusknot.SourceTreeNotMAS',
'~/Library/Preferences/com.torusknot.SourceTreeNotMAS.plist',
'~/Library/Preferences/com.torusknot.SourceTreeNotMAS.LSSharedFileList.plist',
'~/Library/Saved Application State/com.torusknot.SourceTreeNotMAS.savedState',
]
end
|
cask 'spaceradar' do
version '4.4.0'
sha256 'de93d62bb2845fa815b7010a5f42960ce849487489370fae3636177944b083ff'
url "https://github.com/zz85/space-radar/releases/download/v#{version}/SpaceRadar-darwin-x64.zip"
appcast 'https://github.com/zz85/space-radar/releases.atom',
:sha256 => '86c8908866031b0ef56b4a4d57005e5f267ccb616c678803a10e14a818c5ba15'
name 'SpaceRadar'
homepage 'https://github.com/zz85/space-radar'
license :mit
app 'SpaceRadar.app'
uninstall :quit => 'com.electron.spaceradar'
zap :delete => [
'~/Library/Application Support/space-radar',
'~/Library/Caches/space-radar',
'~/Library/Preferences/com.electron.spaceradar.plist',
'~/Library/Saved Application State/com.electron.spaceradar.savedState'
]
end
spaceradar.rb: RuboCop (master), RuboCop-cask (master) auto-correct
cask 'spaceradar' do
version '4.4.0'
sha256 'de93d62bb2845fa815b7010a5f42960ce849487489370fae3636177944b083ff'
url "https://github.com/zz85/space-radar/releases/download/v#{version}/SpaceRadar-darwin-x64.zip"
appcast 'https://github.com/zz85/space-radar/releases.atom',
:sha256 => '86c8908866031b0ef56b4a4d57005e5f267ccb616c678803a10e14a818c5ba15'
name 'SpaceRadar'
homepage 'https://github.com/zz85/space-radar'
license :mit
app 'SpaceRadar.app'
uninstall :quit => 'com.electron.spaceradar'
zap :delete => [
'~/Library/Application Support/space-radar',
'~/Library/Caches/space-radar',
'~/Library/Preferences/com.electron.spaceradar.plist',
'~/Library/Saved Application State/com.electron.spaceradar.savedState',
]
end
|
cask "starsector" do
version "0.95a-RC15"
sha256 "355c36a6bd7f027c6b719429c985074ce347c3daddeee1ecf6eabb69a5937ae6"
url "https://s3.amazonaws.com/fractalsoftworks/starsector/starsector_mac-#{version}.zip",
verified: "s3.amazonaws.com/fractalsoftworks/"
name "Starsector"
desc "Open-world single-player space combat and trading RPG"
homepage "https://fractalsoftworks.com/"
livecheck do
url "https://fractalsoftworks.com/preorder/"
strategy :page_match
regex(%r{href=.*?/starsector_mac-(\d+(?:\.\d+)*a-RC\d+)\.zip}i)
end
app "Starsector.app"
end
Update starsector from 0.95a-RC15 to 0.95.1a-RC6 (#116895)
* Update starsector from 0.95a-RC15 to 0.95.1a-RC6
* starsector: tweak livecheck regex
cask "starsector" do
version "0.95.1a-RC6"
sha256 "fac284c08fe3905f6a1f37cefcb24c790c7450d2ebc6468bc138f4e47262fcc9"
url "https://s3.amazonaws.com/fractalsoftworks/starsector/starsector_mac-#{version}.zip",
verified: "s3.amazonaws.com/fractalsoftworks/"
name "Starsector"
desc "Open-world single-player space combat and trading RPG"
homepage "https://fractalsoftworks.com/"
livecheck do
url "https://fractalsoftworks.com/preorder/"
regex(/href=.*?starsector_mac[._-]v?(\d+(?:\.\d+)+[\w._-]+)\.zip/i)
end
app "Starsector.app"
end
|
cask "subnetcalc" do
if MacOS.version <= :el_capitan
version "1.1"
sha256 "19157baacac0cede6849356cb305a0ed2e4290e1e9e8ac4b691fd1d7ce1920cf"
else
version "2.0"
sha256 "e698878755ea95ffb08b3c1e21cfc20c5dc75396c4c3be318ac54b5bfa2a7727"
end
url "http://subnetcalc.free.fr/download/subnetcalc-#{version}.dmg"
name "SubnectCalc"
desc "Tool to calculate IP subnets"
homepage "http://subnetcalc.free.fr/"
livecheck do
url :homepage
strategy :page_match
regex(%r{href=.*?/subnetcalc-(\d+(?:\.\d+)*)\.dmg}i)
end
app "SubnetCalc.app"
end
Update subnetcalc from 2.0 to 2.1 (#108876)
cask "subnetcalc" do
if MacOS.version <= :el_capitan
version "1.1"
sha256 "19157baacac0cede6849356cb305a0ed2e4290e1e9e8ac4b691fd1d7ce1920cf"
else
version "2.1"
sha256 "5b471b70c53e1b162922f8bc3f337da35224dcc38bd38424e4ed00c1a83fec0d"
end
url "http://subnetcalc.free.fr/download/subnetcalc-#{version}.dmg"
name "SubnectCalc"
desc "Tool to calculate IP subnets"
homepage "http://subnetcalc.free.fr/"
livecheck do
url :homepage
strategy :page_match
regex(%r{href=.*?/subnetcalc-(\d+(?:\.\d+)*)\.dmg}i)
end
app "SubnetCalc.app"
end
|
cask 'toptracker' do
version '1.6.1.6521'
sha256 '2dab586d95fd0b853b23ead7c4ad2752c53adb09a80e76e28e8be232dc80c0ea'
# d101nvfmxunqnl.cloudfront.net was verified as official when first introduced to the cask
url "https://d101nvfmxunqnl.cloudfront.net/desktop/builds/mac/toptracker_#{version}.dmg"
appcast 'https://tracker-api.toptal.com/desktop/updates/mac'
name 'TopTracker'
homepage 'https://tracker.toptal.com/tracker/'
depends_on macos: '>= :sierra'
app 'TopTracker.app'
end
Update toptracker from 1.6.1.6521 to 1.6.2.6524 (#80852)
cask 'toptracker' do
version '1.6.2.6524'
sha256 '3b626f3a4761b6fd8678da4dfed5beabdf1ea198478a8a5f3a06585de56804b0'
# d101nvfmxunqnl.cloudfront.net was verified as official when first introduced to the cask
url "https://d101nvfmxunqnl.cloudfront.net/desktop/builds/mac/toptracker_#{version}.dmg"
appcast 'https://tracker-api.toptal.com/desktop/updates/mac'
name 'TopTracker'
homepage 'https://tracker.toptal.com/tracker/'
depends_on macos: '>= :sierra'
app 'TopTracker.app'
end
|
cask "tortoisehg" do
version "5.6.1"
sha256 "6bd5106bbd34ee0e381f912fbfb0f66231808721cd73d226f4742f1e0d7c303d"
url "https://www.mercurial-scm.org/release/tortoisehg/macos/TortoiseHg-#{version}-mac-x64-qt5.dmg",
verified: "mercurial-scm.org/release/tortoisehg/"
appcast "https://www.mercurial-scm.org/release/tortoisehg/macos/"
name "TortoiseHg"
homepage "https://tortoisehg.bitbucket.io/"
app "TortoiseHg.app"
end
Update tortoisehg from 5.6.1 to 5.7.1 (#104660)
* Update tortoisehg from 5.6.1 to 5.7.1
* Update tortoisehg.rb
cask "tortoisehg" do
version "5.7.1"
sha256 "5844907c752259918c4563b8d4924ff5b75831dceaf75889caf5b1b868086195"
url "https://www.mercurial-scm.org/release/tortoisehg/macos/TortoiseHg-#{version}-mac-x64-qt5.dmg",
verified: "mercurial-scm.org/release/tortoisehg/"
name "TortoiseHg"
desc "Tools for the Mercurial distributed revision control system"
homepage "https://tortoisehg.bitbucket.io/"
livecheck do
url "https://www.mercurial-scm.org/release/tortoisehg/macos/"
strategy :page_match
regex(/TortoiseHg-(\d+(?:\.\d+)*)-mac-x64-qt5\.dmg/i)
end
app "TortoiseHg.app"
end
|
cask 'virtualc64' do
# note: "64" is not a version number, but an intrinsic part of the product name
version '3.0'
sha256 '1ea9c232aea4aa962174d972c19f2e1fca1699ac94e8241f1ac9cec310064d5d'
url "http://www.dirkwhoffmann.de/virtualc64/VirtualC64_#{version}.zip"
appcast 'http://dirkwhoffmann.de/virtualc64/VirtualC64Appcast.xml'
name 'Virtual C64'
homepage 'http://www.dirkwhoffmann.de/virtualc64/'
app 'VirtualC64.app'
end
Update virtualc64 to 3.0.1 (#53892)
cask 'virtualc64' do
# note: "64" is not a version number, but an intrinsic part of the product name
version '3.0.1'
sha256 'a09c21213f6abf955994ca075ee8feec9c3f9fb913650aa47eac78a2373c9a73'
url "http://www.dirkwhoffmann.de/virtualc64/VirtualC64_#{version}.zip"
appcast 'http://dirkwhoffmann.de/virtualc64/VirtualC64Appcast.xml'
name 'Virtual C64'
homepage 'http://www.dirkwhoffmann.de/virtualc64/'
app 'VirtualC64.app'
end
|
cask "vnc-viewer" do
version "6.22.315"
sha256 "dbecdcbad947529a7770a7bae374e2c2313ea4379636a6e36c3c54ac6a7b4b30"
url "https://www.realvnc.com/download/file/viewer.files/VNC-Viewer-#{version}-MacOSX-x86_64.dmg"
name "Real VNC Viewer"
desc "Remote desktop application focusing on security"
homepage "https://www.realvnc.com/"
livecheck do
url "https://www.realvnc.com/en/connect/download/viewer/macos/"
regex(%r{href=.*?/VNC-Viewer-(\d+(?:\.\d+)+)-MacOSX-x86_64\.dmg}i)
end
app "VNC Viewer.app"
zap trash: [
"~/Library/Preferences/com.realvnc.vncviewer.plist",
"~/Library/Saved Application State/com.realvnc.vncviewer.savedState",
]
end
vnc-viewer 6.22.515
Update vnc-viewer from 6.22.315 to 6.22.515
Closes #126904.
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
cask "vnc-viewer" do
version "6.22.515"
sha256 "14a1bb207e8c9d68c0c8a0377b2ae9c5fa4b51c841c0c5ef5fdf9014f7b5881f"
url "https://www.realvnc.com/download/file/viewer.files/VNC-Viewer-#{version}-MacOSX-x86_64.dmg"
name "Real VNC Viewer"
desc "Remote desktop application focusing on security"
homepage "https://www.realvnc.com/"
livecheck do
url "https://www.realvnc.com/en/connect/download/viewer/macos/"
regex(%r{href=.*?/VNC-Viewer-(\d+(?:\.\d+)+)-MacOSX-x86_64\.dmg}i)
end
app "VNC Viewer.app"
zap trash: [
"~/Library/Preferences/com.realvnc.vncviewer.plist",
"~/Library/Saved Application State/com.realvnc.vncviewer.savedState",
]
end
|
cask 'webcatalog' do
version '19.4.4'
sha256 '75cd36f506027388049ceecce1389a11c9ace7c0fb3b11e46849870eeac4b849'
# github.com/quanglam2807/webcatalog was verified as official when first introduced to the cask
url "https://github.com/quanglam2807/webcatalog/releases/download/v#{version}/WebCatalog-#{version}-mac.zip"
appcast 'https://github.com/quanglam2807/webcatalog/releases.atom'
name 'WebCatalog'
homepage 'https://getwebcatalog.com/'
auto_updates true
app 'WebCatalog.app'
zap trash: [
'~/Library/Application Support/WebCatalog',
'~/Library/Caches/com.webcatalog.jordan',
'~/Library/Caches/com.webcatalog.jordan.ShipIt',
'~/Library/Preferences/com.webcatalog.jordan.plist',
'~/Library/Saved Application State/com.webcatalog.jordan.savedState',
]
end
Update webcatalog from 19.4.4 to 19.5.0 (#78685)
cask 'webcatalog' do
version '19.5.0'
sha256 'a334a87715faf1c933b9eb5029b7dee09295f01872b34d3cedb7b0c7b40006ef'
# github.com/quanglam2807/webcatalog was verified as official when first introduced to the cask
url "https://github.com/quanglam2807/webcatalog/releases/download/v#{version}/WebCatalog-#{version}-mac.zip"
appcast 'https://github.com/quanglam2807/webcatalog/releases.atom'
name 'WebCatalog'
homepage 'https://getwebcatalog.com/'
auto_updates true
app 'WebCatalog.app'
zap trash: [
'~/Library/Application Support/WebCatalog',
'~/Library/Caches/com.webcatalog.jordan',
'~/Library/Caches/com.webcatalog.jordan.ShipIt',
'~/Library/Preferences/com.webcatalog.jordan.plist',
'~/Library/Saved Application State/com.webcatalog.jordan.savedState',
]
end
|
cask "webcatalog" do
version "28.4.0"
sha256 "820d8766751853f8c5f7a44ae65f2f17e24671a2a56b9f8c7822c82a0b0b03a2"
url "https://github.com/webcatalog/webcatalog-app/releases/download/v#{version}/WebCatalog-#{version}.dmg",
verified: "github.com/webcatalog/webcatalog-app/"
appcast "https://github.com/webcatalog/webcatalog-app/releases.atom"
name "WebCatalog"
desc "Tool to run web apps like desktop apps"
homepage "https://webcatalog.app/"
auto_updates true
app "WebCatalog.app"
zap trash: [
"~/Library/Application Support/WebCatalog",
"~/Library/Caches/com.webcatalog.jordan",
"~/Library/Caches/com.webcatalog.jordan.ShipIt",
"~/Library/Preferences/com.webcatalog.jordan.plist",
"~/Library/Saved Application State/com.webcatalog.jordan.savedState",
]
end
Update webcatalog (#99873)
cask "webcatalog" do
version "28.5.0"
sha256 "ad1c03323041d66b9df70717003709c650555f16eed6cdef879adbf99eb8d23f"
url "https://github.com/webcatalog/webcatalog-app/releases/download/v#{version}/WebCatalog-#{version}.dmg",
verified: "github.com/webcatalog/webcatalog-app/"
appcast "https://github.com/webcatalog/webcatalog-app/releases.atom"
name "WebCatalog"
desc "Tool to run web apps like desktop apps"
homepage "https://webcatalog.app/"
auto_updates true
app "WebCatalog.app"
zap trash: [
"~/Library/Application Support/WebCatalog",
"~/Library/Caches/com.webcatalog.jordan",
"~/Library/Caches/com.webcatalog.jordan.ShipIt",
"~/Library/Preferences/com.webcatalog.jordan.plist",
"~/Library/Saved Application State/com.webcatalog.jordan.savedState",
]
end
|
cask 'webcatalog' do
version '20.12.1'
sha256 '131759b0d49c7f521168d6f701d030f689eff1ef1447480d0cb2bde2cd2ac40d'
# github.com/quanglam2807/webcatalog/ was verified as official when first introduced to the cask
url "https://github.com/quanglam2807/webcatalog/releases/download/v#{version}/WebCatalog-#{version}-mac.zip"
appcast 'https://github.com/quanglam2807/webcatalog/releases.atom'
name 'WebCatalog'
homepage 'https://getwebcatalog.com/'
auto_updates true
app 'WebCatalog.app'
zap trash: [
'~/Library/Application Support/WebCatalog',
'~/Library/Caches/com.webcatalog.jordan',
'~/Library/Caches/com.webcatalog.jordan.ShipIt',
'~/Library/Preferences/com.webcatalog.jordan.plist',
'~/Library/Saved Application State/com.webcatalog.jordan.savedState',
]
end
Update webcatalog from 20.12.1 to 20.12.2 (#81929)
Co-authored-by: runner <63a5fd3bc5f45a0490e4deca178d288050e26803@Mac-1454.local>
cask 'webcatalog' do
version '20.12.2'
sha256 'bbe49f6b032fc3aaa7eb173b1585b6ca7de52135074b653055fe22845a4bfe09'
# github.com/quanglam2807/webcatalog/ was verified as official when first introduced to the cask
url "https://github.com/quanglam2807/webcatalog/releases/download/v#{version}/WebCatalog-#{version}-mac.zip"
appcast 'https://github.com/quanglam2807/webcatalog/releases.atom'
name 'WebCatalog'
homepage 'https://getwebcatalog.com/'
auto_updates true
app 'WebCatalog.app'
zap trash: [
'~/Library/Application Support/WebCatalog',
'~/Library/Caches/com.webcatalog.jordan',
'~/Library/Caches/com.webcatalog.jordan.ShipIt',
'~/Library/Preferences/com.webcatalog.jordan.plist',
'~/Library/Saved Application State/com.webcatalog.jordan.savedState',
]
end
|
cask 'webcatalog' do
version '3.4.4'
sha256 '7bb7e3d58b0ab68d3a0be117d16b2d03349f91b00e242ca21dbfd42002507082'
# github.com/webcatalog/desktop/releases/download/ was verified as official when first introduced to the cask
url "https://github.com/webcatalog/desktop/releases/download/v#{version}/WebCatalog-#{version}.dmg"
appcast 'https://github.com/webcatalog/desktop/releases.atom',
checkpoint: '041280020e5a1d1eeedc8ca6d1483a81e59fe564db74ad97869dff056ebd48c7'
name 'WebCatalog'
homepage 'https://getwebcatalog.com/'
app 'WebCatalog.app'
zap delete: [
'~/Library/Application Support/WebCatalog',
'~/Library/Cookies/com.webcatalog.app.binarycookies',
'~/Library/Preferences/WebCatalog_Alt.plist',
'~/Library/Preferences/com.webcatalog.app.helper.plist',
'~/Library/Preferences/com.webcatalog.app.plist',
'~/Library/Saved Application State/com.webcatalog.app.savedState',
]
end
Update webcatalog.rb (#31878)
* Update webcatalog.rb
* Update webcatalog.rb
cask 'webcatalog' do
version '4.0.3'
sha256 'a358654ebc8d8217bd88c3273ed266aa6d1badfc91a3849f53e9a6c3990baf21'
# github.com/webcatalog/desktop/releases/download/ was verified as official when first introduced to the cask
url "https://github.com/webcatalog/desktop/releases/download/v#{version}/WebCatalog-#{version}.dmg"
appcast 'https://github.com/webcatalog/desktop/releases.atom',
checkpoint: '928b31348b933ed9bef88bb1250141ae0548b6b048d80286e04987e09ad35d56'
name 'WebCatalog'
homepage 'https://getwebcatalog.com/'
app 'WebCatalog.app'
zap delete: [
'~/Library/Application Support/WebCatalog',
'~/Library/Cookies/com.webcatalog.app.binarycookies',
'~/Library/Preferences/WebCatalog_Alt.plist',
'~/Library/Preferences/com.webcatalog.app.helper.plist',
'~/Library/Preferences/com.webcatalog.app.plist',
'~/Library/Saved Application State/com.webcatalog.app.savedState',
]
end
|
cask 'wechatwork' do
version '3.0.8.2074'
sha256 '06bf5d6d7f939d8bfa863ba033ac243d4e2ea6a172cc8a7b55c525264cb6efe0'
url "https://dldir1.qq.com/wework/work_weixin/WXWork_#{version}.dmg"
appcast 'https://www.macupdater.net/cgi-bin/check_urls/check_url_redirect.cgi?url=https://work.weixin.qq.com/wework_admin/commdownload?platform=mac'
name 'WeChat Work'
name '企业微信'
homepage 'https://work.weixin.qq.com/'
app '企业微信.app'
uninstall quit: 'com.tencent.WeWorkMac'
end
Update wechatwork from 3.0.8.2074 to 3.0.8.2080 (#77306)
cask 'wechatwork' do
version '3.0.8.2080'
sha256 '2fac3e3b6b6fb7b1a933dd69e8df62cc213fac555d03298bfec4a515f137f035'
url "https://dldir1.qq.com/wework/work_weixin/WXWork_#{version}.dmg"
appcast 'https://www.macupdater.net/cgi-bin/check_urls/check_url_redirect.cgi?url=https://work.weixin.qq.com/wework_admin/commdownload?platform=mac'
name 'WeChat Work'
name '企业微信'
homepage 'https://work.weixin.qq.com/'
app '企业微信.app'
uninstall quit: 'com.tencent.WeWorkMac'
end
|
cask "wechatwork" do
version "3.0.36.2330"
sha256 "c0230b0e292456d38856850f06575bff105e7e47c7464b54b4ad80e031958fc2"
url "https://dldir1.qq.com/wework/work_weixin/WXWork_#{version}.dmg"
appcast "https://www.macupdater.net/cgi-bin/check_urls/check_url_redirect.cgi?url=https://work.weixin.qq.com/wework_admin/commdownload?platform=mac"
name "WeChat Work"
name "企业微信"
homepage "https://work.weixin.qq.com/"
app "企业微信.app"
uninstall quit: "com.tencent.WeWorkMac"
end
Update wechatwork from 3.0.36.2330 to 3.0.40.2346 (#95640)
cask "wechatwork" do
version "3.0.40.2346"
sha256 "ddeed7293c8251dfca8c4ba5d017498681053ca023707f59d3d903e1505b3a37"
url "https://dldir1.qq.com/wework/work_weixin/WeCom_#{version}.dmg"
appcast "https://www.macupdater.net/cgi-bin/check_urls/check_url_redirect.cgi?url=https://work.weixin.qq.com/wework_admin/commdownload?platform=mac"
name "WeChat Work"
name "企业微信"
homepage "https://work.weixin.qq.com/"
app "企业微信.app"
uninstall quit: "com.tencent.WeWorkMac"
end
|
cask 'wintertime' do
version '0.0.5'
sha256 '2c71c3f4b5939f69a8932ff4c9360a47eff96051140c15adaf26c1203ca0902e'
url "https://github.com/actuallymentor/wintertime-mac-background-freezer/releases/download/#{version}/Wintertime-#{version}.dmg"
appcast 'https://github.com/actuallymentor/wintertime-mac-background-freezer/releases.atom'
name 'Wintertime'
homepage 'https://github.com/actuallymentor/wintertime-mac-background-freezer'
app 'Wintertime.app'
end
Wintertime 0.0.7 (#61011)
cask 'wintertime' do
version '0.0.7'
sha256 'b7cb5b25172e3450982d673533931e721e009677e711fffa320b5e42abee3ff3'
url "https://github.com/actuallymentor/wintertime-mac-background-freezer/releases/download/#{version}/Wintertime-#{version}.dmg"
appcast 'https://github.com/actuallymentor/wintertime-mac-background-freezer/releases.atom'
name 'Wintertime'
homepage 'https://github.com/actuallymentor/wintertime-mac-background-freezer'
app 'Wintertime.app'
end
|
add deleted Cask wunderlist
# coding: utf-8
# Sat Apr 5 17:54:03 2014 +0100 https://github.com/caskroom/homebrew-cask/commit/3773bd4 removed wunderlist [Vítor Galvão]
cask :v1 => 'wunderlist' do
url 'https://www.macupdate.com/download/35862/Wunderlist.zip'
homepage 'https://www.wunderlist.com/en/'
version '2.3.2'
sha256 'd7adf0cb3b9ab0cd4265ccc7c1e757cd38e74dbcf8c56017baf443dd2abec1b8'
app 'Wunderlist.app'
end
|
class Yandexdisk < Cask
version 'latest'
sha256 :no_check
url 'https://disk.yandex.com/download/Yandex.Disk.Mac.dmg'
homepage 'https://disk.yandex.com/'
link 'Yandex.Disk.app'
end
app stanza in yandexdisk.rb
class Yandexdisk < Cask
version 'latest'
sha256 :no_check
url 'https://disk.yandex.com/download/Yandex.Disk.Mac.dmg'
homepage 'https://disk.yandex.com/'
app 'Yandex.Disk.app'
end
|
require 'test_helper'
require 'docsplit'
require 'seek/download_handling/http_streamer' # Needed to load exceptions that are tested later
class ContentBlobTest < ActiveSupport::TestCase
fixtures :content_blobs
test 'search terms' do
blob = ContentBlob.new
blob.url = 'http://fish.com'
assert_includes blob.search_terms, 'fish'
assert_includes blob.search_terms, 'http://fish.com'
refute_includes blob.search_terms, 'http'
refute_includes blob.search_terms, 'com'
blob = Factory(:txt_content_blob)
assert_includes blob.search_terms, 'txt_test.txt'
assert_includes blob.search_terms, 'txt'
end
test 'max indexable text size' do
blob = Factory :large_txt_content_blob
size = blob.file_size
assert size > 1.megabyte
assert size < 2.megabyte
assert blob.is_text?
with_config_value :max_indexable_text_size, 1 do
refute blob.is_indexable_text?
end
with_config_value :max_indexable_text_size, 2 do
assert blob.is_indexable_text?
end
with_config_value :max_indexable_text_size, '2' do
assert blob.is_indexable_text?
end
end
test 'md5sum_on_demand' do
blob = Factory :rightfield_content_blob
assert_not_nil blob.md5sum
assert_equal '01788bca93265d80e8127ca0039bb69b', blob.md5sum
end
test 'sha1 sum on demand' do
blob = Factory :rightfield_content_blob
assert_not_nil blob.sha1sum
assert_equal 'ffd634ac7564083ab7b66bc3eb2053cbc3d608f5', blob.sha1sum
end
test 'detects it is a webpage' do
as_not_virtualliver do
mock_remote_file "#{Rails.root}/test/fixtures/files/html_file.html", 'http://webpage.com', 'Content-Type' => 'text/html'
blob = ContentBlob.create url: 'http://webpage.com', original_filename: nil, content_type: nil, external_link: true
assert blob.is_webpage?
assert_equal 'text/html', blob.content_type
end
end
test 'detectes webpage if content-type includes charset info' do
as_not_virtualliver do
mock_remote_file "#{Rails.root}/test/fixtures/files/html_file.html", 'http://webpage.com', 'Content-Type' => 'text/html; charset=ascii'
blob = ContentBlob.create url: 'http://webpage.com', original_filename: nil, content_type: nil, external_link: true
assert blob.is_webpage?
assert_equal 'text/html', blob.content_type
end
end
test 'only overrides url content-type if not already known' do
as_not_virtualliver do
mock_remote_file "#{Rails.root}/test/fixtures/files/html_file.html", 'http://webpage.com', 'Content-Type' => 'text/html'
mock_remote_file "#{Rails.root}/test/fixtures/files/file_picture.png", 'http://webpage.com/piccy.png', 'Content-Type' => 'image/png'
blob = ContentBlob.create url: 'http://webpage.com', original_filename: nil, content_type: nil, external_link: true
assert_equal 'text/html', blob.content_type
blob = ContentBlob.create url: 'http://webpage.com/piccy.png', original_filename: nil, content_type: nil
assert_equal 'image/png', blob.content_type
blob = ContentBlob.create url: 'http://webpage.com/piccy.png', original_filename: nil, content_type: 'application/x-download'
assert_equal 'image/png', blob.content_type
blob = ContentBlob.create url: 'http://webpage.com/piccy.png', original_filename: nil, content_type: 'application/pdf'
assert_equal 'application/pdf', blob.content_type
end
end
test "detects it isn't a webpage" do
as_not_virtualliver do
mock_remote_file "#{Rails.root}/test/fixtures/files/file_picture.png", 'http://webpage.com/piccy.png', 'Content-Type' => 'image/png'
blob = ContentBlob.create url: 'http://webpage.com/piccy.png', original_filename: nil, content_type: nil
assert !blob.is_webpage?
assert_equal 'image/png', blob.content_type
end
end
test 'handles an unavailable url when checking for a webpage' do
mock_remote_file "#{Rails.root}/test/fixtures/files/file_picture.png", 'http://webpage.com/piccy.png', { 'Content-Type' => 'image/png' }, 500
blob = ContentBlob.create url: 'http://webpage.com/piccy.png', original_filename: nil, content_type: nil
assert !blob.is_webpage?
end
test "content type for url type with binary doesn't try read file" do
mock_remote_file "#{Rails.root}/test/fixtures/files/file_picture.png", 'http://webpage.com/binary-file', { 'Content-Type' => 'application/octet-stream' }, 500
blob = ContentBlob.create url: 'http://webpage.com/binary-file', original_filename: nil, content_type: 'application/octet-stream'
assert_equal 'application/octet-stream', blob.content_type
end
def test_cache_key
blob = Factory :rightfield_content_blob
assert_equal "content_blobs/#{blob.id}-ffd634ac7564083ab7b66bc3eb2053cbc3d608f5", blob.cache_key
end
def test_uuid_doesnt_change
blob = content_blobs(:picture_blob)
blob.uuid = 'zzz'
assert_equal 'zzz', blob.uuid
blob.save!
assert_equal 'zzz', blob.uuid
end
def test_uuid_doesnt_change2
blob = content_blobs(:picture_blob)
blob.uuid = 'zzz'
blob.save!
blob = ContentBlob.find(blob.id)
assert_equal 'zzz', blob.uuid
blob.save!
blob = ContentBlob.find(blob.id)
assert_equal 'zzz', blob.uuid
end
def test_regenerate_uuid
pic = content_blobs(:picture_blob)
uuid = pic.uuid
pic.regenerate_uuid
assert_not_equal uuid, pic.uuid
end
def test_file_dump
pic = content_blobs(:picture_blob)
blob = ContentBlob.new(data: pic.data_io_object.read, original_filename: 'piccy.jpg')
blob.save!
assert_not_nil blob.filepath
data = nil
File.open(blob.filepath, 'rb') do |f|
data = f.read
end
assert_not_nil data
assert_equal data_for_test('file_picture.png'), data
end
# checks that the data is assigned through the new method, stored to a file, and not written to the old data_old field
def test_data_assignment
pic = content_blobs(:picture_blob)
pic.save! # to trigger callback to save to file
blob = ContentBlob.new(data: pic.data_io_object.read, original_filename: 'piccy.jpg')
blob.save!
blob = ContentBlob.find(blob.id)
assert_equal data_for_test('file_picture.png'), blob.data_io_object.read
assert_not_nil blob.filepath
data = nil
File.open(blob.filepath, 'rb') do |f|
data = f.read
end
assert_not_nil data
assert_equal data_for_test('file_picture.png'), data
end
# simply checks that get and set data returns the same thing
def test_data_assignment2
pic = content_blobs(:picture_blob)
pic.data = data_for_test('little_file.txt')
pic.save!
assert_equal data_for_test('little_file.txt'), pic.data_io_object.read
# put it back, otherwise other tests fail
pic.data = data_for_test('file_picture.png')
pic.save!
end
#
def test_will_overwrite_if_data_changes
pic = content_blobs(:picture_blob)
pic.save!
assert_equal data_for_test('file_picture.png'), File.open(pic.filepath, 'rb').read
pic.data = data_for_test('little_file.txt')
pic.save!
assert_equal data_for_test('little_file.txt'), File.open(pic.filepath, 'rb').read
end
def test_uuid
pic = content_blobs(:picture_blob)
blob = ContentBlob.new(data: pic.data_io_object.read, original_filename: 'piccy.jpg')
blob.save!
assert_not_nil blob.uuid
assert_not_nil ContentBlob.find(blob.id).uuid
end
def data_for_test(filename)
file = "#{Rails.root}/test/fixtures/files/#{filename}"
File.open(file, 'rb').read
end
def test_tmp_io_object
io_object = Tempfile.new('tmp_io_object_test')
io_object.write("blah blah\nmonkey_business")
blob = ContentBlob.new(tmp_io_object: io_object, original_filename: 'monkey.txt')
assert_difference('ContentBlob.count') do
blob.save!
end
blob.reload
assert_not_nil blob.filepath
assert File.exist?(blob.filepath)
data = nil
File.open(blob.filepath, 'rb') do |f|
data = f.read
end
assert_not_nil data
assert_equal "blah blah\nmonkey_business", data.to_s
end
def test_string_io_object
io_object = StringIO.new('frog')
blob = ContentBlob.new(tmp_io_object: io_object, original_filename: 'frog.txt')
assert_difference('ContentBlob.count') do
blob.save!
end
blob.reload
assert_not_nil blob.filepath
assert File.exist?(blob.filepath)
data = nil
File.open(blob.filepath, 'rb') do |f|
data = f.read
end
assert_not_nil data
assert_equal 'frog', data.to_s
end
test 'validates by content blob or url' do
blob = ContentBlob.new
refute blob.valid?
blob.original_filename = 'fish'
assert blob.valid?
blob.original_filename = nil
blob.url = 'http://google.com'
assert blob.valid?
end
def test_data_io
io_object = StringIO.new('frog')
blob = ContentBlob.new(tmp_io_object: io_object, original_filename: 'frog.txt')
blob.save!
blob.reload
assert_equal 'frog', blob.data_io_object.read
f = Tempfile.new('seek-data-io-test')
f << 'fish'
f.close
io_object = File.new(f.path, 'r')
blob = ContentBlob.new(tmp_io_object: io_object, original_filename: 'seek-data-io-test')
blob.save!
blob.reload
io_object.rewind
assert_equal io_object.read, blob.data_io_object.read
mock_remote_file "#{Rails.root}/test/fixtures/files/file_picture.png", 'http://www.webpage.com/image.png'
blob = ContentBlob.new(url: 'http://www.webpage.com/image.png')
blob.save!
blob.reload
assert_nil blob.data_io_object
blob = ContentBlob.new original_filename: 'nil'
assert_nil blob.data_io_object
blob.save!
assert_nil blob.data_io_object
end
def test_filesize
cb = Factory :content_blob, data: 'z'
assert_equal 1, cb.file_size
File.delete(cb.filepath)
assert_equal 1, cb.file_size
cb = Factory :rightfield_content_blob
assert_not_nil cb.file_size
assert_equal 9216, cb.file_size
end
def test_exception_when_both_data_and_io_object
io_object = StringIO.new('frog')
blob = ContentBlob.new(tmp_io_object: io_object, data: 'snake', original_filename: 'snake.txt')
assert_raise Exception do
blob.save
end
end
test 'storage_directory and filepath' do
content_blob = Factory(:content_blob)
storage_directory = content_blob.data_storage_directory
converted_storage_directory = content_blob.converted_storage_directory
assert_equal "#{Rails.root}/tmp/testing-filestore/assets", storage_directory
assert_equal "#{Rails.root}/tmp/testing-filestore/converted-assets", converted_storage_directory
assert_equal (storage_directory + '/' + content_blob.uuid + '.dat'), content_blob.filepath
assert_equal (converted_storage_directory + '/' + content_blob.uuid + '.pdf'), content_blob.filepath('pdf')
assert_equal (converted_storage_directory + '/' + content_blob.uuid + '.txt'), content_blob.filepath('txt')
end
test 'file_exists?' do
# specify uuid here to avoid repeating uuid of other content_blob when running the whole test file
content_blob = Factory(:content_blob, uuid: '1111')
assert content_blob.file_exists?
content_blob = Factory(:content_blob, uuid: '2222', data: nil)
assert !content_blob.file_exists?
end
test 'human content type' do
content_blob = Factory(:docx_content_blob)
assert_equal 'Word document', content_blob.human_content_type
content_blob = Factory(:content_blob, content_type: 'application/msexcel')
assert_equal 'Spreadsheet', content_blob.human_content_type
content_blob = Factory.create(:pdf_content_blob, content_type: 'application/pdf')
assert_equal 'PDF document', content_blob.human_content_type
content_blob = Factory(:content_blob, content_type: 'text/html')
assert_equal 'HTML document', content_blob.human_content_type
content_blob = Factory(:content_blob, content_type: 'application/x-download')
assert_equal 'Unknown file type', content_blob.human_content_type
content_blob = Factory(:content_blob, content_type: '')
assert_equal 'Unknown file type', content_blob.human_content_type
content_blob = Factory(:content_blob)
assert_equal 'Unknown file type', content_blob.human_content_type
content_blob = Factory(:tiff_content_blob)
assert_equal 'TIFF image', content_blob.human_content_type
end
test 'mimemagic updates content type on creation if binary' do
tmp_blob = Factory(:pdf_content_blob) # to get the filepath
content_blob = ContentBlob.create data: File.new(tmp_blob.filepath, 'rb').read, original_filename: 'blob', content_type: 'application/octet-stream'
assert_equal 'application/pdf', content_blob.content_type
assert content_blob.is_pdf?
end
test 'is_binary?' do
content_blob = Factory(:pdf_content_blob)
refute content_blob.is_binary?
content_blob = Factory(:binary_content_blob)
assert content_blob.is_binary?
end
test 'covert_office should doc to pdf and then docslit convert pdf to txt' do
check_for_soffice
content_blob = Factory(:doc_content_blob, uuid: 'doc_1')
assert File.exist? content_blob.filepath
pdf_path = content_blob.filepath('pdf')
FileUtils.rm pdf_path if File.exist? pdf_path
assert !File.exist?(pdf_path)
content_blob.convert_to_pdf
assert File.exist?(pdf_path), 'pdf was not created during conversion'
content_blob.extract_text_from_pdf
assert File.exist? content_blob.filepath('txt')
content = File.open(content_blob.filepath('txt'), 'rb').read
assert content.include?('This is a ms word doc format')
end
test 'convert_office should convert docx to pdf and then docsplit convert pdf to txt' do
check_for_soffice
content_blob = Factory(:docx_content_blob, uuid: 'docx_1')
assert File.exist? content_blob.filepath
FileUtils.rm content_blob.filepath('pdf') if File.exist? content_blob.filepath('pdf')
assert !File.exist?(content_blob.filepath('pdf'))
content_blob.convert_to_pdf
assert File.exist?(content_blob.filepath('pdf')), 'pdf was not created during conversion'
content_blob.extract_text_from_pdf
assert File.exist? content_blob.filepath('txt')
content = File.open(content_blob.filepath('txt'), 'rb').read
assert content.include?('This is a ms word docx format')
end
test 'convert_office should convert odt to pdf and then docsplit converts pdf to txt' do
check_for_soffice
content_blob = Factory(:odt_content_blob, uuid: 'odt_1')
assert File.exist? content_blob.filepath
FileUtils.rm content_blob.filepath('pdf') if File.exist? content_blob.filepath('pdf')
assert !File.exist?(content_blob.filepath('pdf'))
content_blob.convert_to_pdf
assert File.exist?(content_blob.filepath('pdf')), 'pdf was not created during conversion'
content_blob.extract_text_from_pdf
assert File.exist? content_blob.filepath('txt')
content = File.open(content_blob.filepath('txt'), 'rb').read
assert content.include?('This is an open office word odt format')
end
test 'convert_office should convert ppt to pdf and then docsplit converts pdf to txt' do
check_for_soffice
content_blob = Factory(:ppt_content_blob, uuid: 'ppt_1')
assert File.exist? content_blob.filepath
FileUtils.rm content_blob.filepath('pdf') if File.exist? content_blob.filepath('pdf')
assert !File.exist?(content_blob.filepath('pdf'))
content_blob.convert_to_pdf
assert File.exist?(content_blob.filepath('pdf')), 'pdf was not created during conversion'
content_blob.extract_text_from_pdf
assert File.exist? content_blob.filepath('txt')
content = File.open(content_blob.filepath('txt'), 'rb').read
assert content.include?('This is a ms power point ppt format')
end
test 'convert_office should convert pptx to pdf and then docsplit converts pdf to txt' do
check_for_soffice
content_blob = Factory(:pptx_content_blob, uuid: 'pptx_1')
assert File.exist? content_blob.filepath
FileUtils.rm content_blob.filepath('pdf') if File.exist? content_blob.filepath('pdf')
assert !File.exist?(content_blob.filepath('pdf'))
content_blob.convert_to_pdf
assert File.exist?(content_blob.filepath('pdf')), 'pdf was not created during conversion'
content_blob.extract_text_from_pdf
assert File.exist? content_blob.filepath('txt')
content = File.open(content_blob.filepath('txt'), 'rb').read
assert content.include?('This is a ms power point pptx format')
end
test 'convert_office should convert odp to pdf and then docsplit converts pdf to txt' do
check_for_soffice
content_blob = Factory(:odp_content_blob, uuid: 'odp_1')
assert File.exist? content_blob.filepath
FileUtils.rm content_blob.filepath('pdf') if File.exist? content_blob.filepath('pdf')
assert !File.exist?(content_blob.filepath('pdf'))
content_blob.convert_to_pdf
assert File.exist?(content_blob.filepath('pdf')), 'pdf was not created during conversion'
content_blob.extract_text_from_pdf
assert File.exist? content_blob.filepath('txt')
content = File.open(content_blob.filepath('txt'), 'rb').read
assert content.include?('This is an open office power point odp format')
end
test 'convert_office should convert rtf to pdf and then docsplit converts pdf to txt' do
check_for_soffice
content_blob = Factory(:rtf_content_blob, uuid: 'rtf_1')
assert File.exist? content_blob.filepath
FileUtils.rm content_blob.filepath('pdf') if File.exist? content_blob.filepath('pdf')
assert !File.exist?(content_blob.filepath('pdf'))
content_blob.convert_to_pdf
assert File.exist?(content_blob.filepath('pdf')), 'pdf was not created during conversion'
content_blob.extract_text_from_pdf
assert File.exist? content_blob.filepath('txt')
content = File.open(content_blob.filepath('txt'), 'rb').read
assert content.mb_chars.normalize.include?('This is a rtf format')
end
test 'convert_office should convert txt to pdf' do
check_for_soffice
content_blob = Factory(:txt_content_blob, uuid: 'txt_1')
assert File.exist? content_blob.filepath
FileUtils.rm content_blob.filepath('pdf') if File.exist? content_blob.filepath('pdf')
assert !File.exist?(content_blob.filepath('pdf'))
content_blob.convert_to_pdf
assert File.exist?(content_blob.filepath('pdf')), 'pdf was not created during conversion'
end
test 'is_content_viewable?' do
viewable_formats = %w(application/pdf)
viewable_formats << 'application/msword'
viewable_formats << 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
viewable_formats << 'application/vnd.ms-powerpoint'
viewable_formats << 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
viewable_formats << 'application/vnd.oasis.opendocument.text'
viewable_formats << 'application/vnd.oasis.opendocument.presentation'
viewable_formats << 'application/rtf'
viewable_formats.each do |viewable_format|
cb_with_content_viewable_format = Factory(:content_blob, content_type: viewable_format, asset: Factory(:sop), data: File.new("#{Rails.root}/test/fixtures/files/a_pdf_file.pdf", 'rb').read)
User.with_current_user cb_with_content_viewable_format.asset.contributor do
assert cb_with_content_viewable_format.is_viewable_format?
assert cb_with_content_viewable_format.is_content_viewable?
end
end
cb_with_no_viewable_format = Factory(:content_blob, content_type: 'application/excel', asset: Factory(:sop), data: File.new("#{Rails.root}/test/fixtures/files/spreadsheet.xls", 'rb').read)
User.with_current_user cb_with_no_viewable_format.asset.contributor do
assert !cb_with_no_viewable_format.is_viewable_format?
assert !cb_with_no_viewable_format.is_content_viewable?
end
end
test 'content needing conversion should not be viewable when pdf_conversion is disabled' do
with_config_value :pdf_conversion_enabled, false do
viewable_formats = %w(application/msword)
viewable_formats << 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
viewable_formats << 'application/vnd.ms-powerpoint'
viewable_formats << 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
viewable_formats << 'application/vnd.oasis.opendocument.text'
viewable_formats << 'application/vnd.oasis.opendocument.presentation'
viewable_formats.each do |viewable_format|
cb_with_content_viewable_format = Factory(:content_blob, content_type: viewable_format, asset: Factory(:sop), data: File.new("#{Rails.root}/test/fixtures/files/a_pdf_file.pdf", 'rb').read)
User.with_current_user cb_with_content_viewable_format.asset.contributor do
assert !cb_with_content_viewable_format.is_content_viewable?
end
end
end
end
test 'content not needing conversion should be viewable when pdf_conversion is disabled' do
pdf_content_blob = Factory(:content_blob, content_type: 'application/pdf', asset: Factory(:sop), data: File.new("#{Rails.root}/test/fixtures/files/a_pdf_file.pdf", 'rb').read)
with_config_value :pdf_conversion_enabled, false do
viewable_formats = %w(text/plain text/csv text/tsv)
viewable_formats.each do |viewable_format|
cb_with_content_viewable_format = Factory(:content_blob, content_type: viewable_format, asset: Factory(:sop), data: File.new("#{Rails.root}/test/fixtures/files/a_pdf_file.pdf", 'rb').read)
User.with_current_user cb_with_content_viewable_format.asset.contributor do
assert cb_with_content_viewable_format.is_content_viewable?
end
end
User.with_current_user pdf_content_blob.asset.contributor do
assert pdf_content_blob.is_content_viewable?
end
end
end
test 'filter_text_content' do
check_for_soffice
ms_word_sop_cb = Factory(:doc_content_blob)
content = "test \n content \f only"
filtered_content = ms_word_sop_cb.send(:filter_text_content, content)
assert !filtered_content.include?('\n')
assert !filtered_content.include?('\f')
end
test 'pdf_contents_for_search for a doc file' do
check_for_soffice
ms_word_sop_content_blob = Factory(:doc_content_blob)
assert ms_word_sop_content_blob.is_pdf_convertable?
content = ms_word_sop_content_blob.pdf_contents_for_search
assert_equal ['This is a ms word doc format'], content
end
test 'pdf_contents_for_search for a pdf file' do
check_for_soffice
pdf_content_blob = Factory(:pdf_content_blob)
content = pdf_content_blob.pdf_contents_for_search
assert_equal ['This is a pdf format'], content
end
test 'calculates file size' do
blob = Factory(:pdf_content_blob)
assert_equal 8827, blob.file_size
end
test 'updates file size' do
blob = Factory(:pdf_content_blob)
blob.data = '123456'
blob.save
assert_equal 6, blob.file_size
end
test 'calculates file size for remote content' do
stub_request(:head, 'http://www.abc.com').to_return(headers: { content_length: 500, content_type: 'text/plain' }, status: 200)
blob = Factory(:url_content_blob)
assert_equal 500, blob.file_size
end
test 'can retrieve remote content' do
stub_request(:head, 'http://www.abc.com').to_return(
headers: { content_length: nil, content_type: 'text/plain' }, status: 200)
stub_request(:get, 'http://www.abc.com').to_return(body: 'abcdefghij' * 500,
headers: { content_type: 'text/plain' }, status: 200)
blob = Factory(:url_content_blob)
assert !blob.file_exists?
assert_equal nil, blob.file_size
blob.retrieve
assert blob.file_exists?
assert_equal 5000, blob.file_size
end
test "won't retrieve remote content over hard limit" do
# Web server lies about content length:
stub_request(:head, 'http://www.abc.com').to_return(
headers: { content_length: 500, content_type: 'text/plain' }, status: 200)
# Size is actually 6kb:
stub_request(:get, 'http://www.abc.com').to_return(body: 'abcdefghij' * 600,
headers: { content_type: 'text/plain' }, status: 200)
blob = Factory(:url_content_blob)
assert !blob.file_exists?
assert_equal 500, blob.file_size
assert_raise Seek::DownloadHandling::SizeLimitExceededException do
blob.retrieve
end
assert !blob.file_exists?
end
test "won't endlessly follow redirects when downloading remote content" do
stub_request(:head, 'http://www.abc.com').to_return(
headers: { content_length: 500, content_type: 'text/plain' }, status: 200)
# Infinitely redirects
stub_request(:get, 'http://www.abc.com').to_return(headers: { location: 'http://www.abc.com' }, status: 302)
blob = Factory(:url_content_blob)
assert !blob.file_exists?
assert_equal 500, blob.file_size
assert_raise Seek::DownloadHandling::RedirectLimitExceededException do
blob.retrieve
end
assert !blob.file_exists?
end
test 'raises exception on bad response code when downloading remote content' do
stub_request(:head, 'http://www.abc.com').to_return(
headers: { content_length: 500, content_type: 'text/plain' }, status: 200)
stub_request(:get, 'http://www.abc.com').to_return(status: 404)
blob = Factory(:url_content_blob)
assert !blob.file_exists?
assert_equal 500, blob.file_size
assert_raise Seek::DownloadHandling::BadResponseCodeException do
blob.retrieve
end
assert !blob.file_exists?
end
test 'handles relative redirects when downloading remote content' do
stub_request(:head, 'http://www.abc.com').to_return(headers: { location: '/xyz' }, status: 302)
stub_request(:get, 'http://www.abc.com').to_return(headers: { location: '/xyz' }, status: 302)
stub_request(:head, 'http://www.abc.com/xyz').to_return(
headers: { content_length: nil, content_type: 'text/plain' }, status: 200)
stub_request(:get, 'http://www.abc.com/xyz').to_return(body: 'abcdefghij' * 500,
headers: { content_type: 'text/plain' }, status: 200)
blob = Factory(:url_content_blob)
assert !blob.file_exists?
assert_equal nil, blob.file_size
blob.retrieve
assert blob.file_exists?
assert_equal 5000, blob.file_size
end
test 'handles absolute redirects when downloading remote content' do
stub_request(:head, 'http://www.abc.com').to_return(headers: { location: 'http://www.abc.com/xyz' }, status: 302)
stub_request(:get, 'http://www.abc.com').to_return(headers: { location: 'http://www.abc.com/xyz' }, status: 302)
stub_request(:head, 'http://www.abc.com/xyz').to_return(
headers: { content_length: nil, content_type: 'text/plain' }, status: 200)
stub_request(:get, 'http://www.abc.com/xyz').to_return(body: 'abcdefghij' * 500,
headers: { content_type: 'text/plain' }, status: 200)
blob = Factory(:url_content_blob)
assert !blob.file_exists?
assert_equal nil, blob.file_size
blob.retrieve
assert blob.file_exists?
assert_equal 5000, blob.file_size
end
test 'handles mixed redirects when downloading remote content' do
stub_request(:head, 'http://www.abc.com').to_return(headers: { location: 'http://www.xyz.com' }, status: 302)
stub_request(:get, 'http://www.abc.com').to_return(headers: { location: 'http://www.xyz.com' }, status: 302)
stub_request(:head, 'http://www.xyz.com').to_return(headers: { location: '/xyz' }, status: 302)
stub_request(:get, 'http://www.xyz.com').to_return(headers: { location: '/xyz' }, status: 302)
stub_request(:head, 'http://www.xyz.com/xyz').to_return(
headers: { content_length: nil, content_type: 'text/plain' }, status: 200)
stub_request(:get, 'http://www.xyz.com/xyz').to_return(body: 'abcdefghij' * 500,
headers: { content_type: 'text/plain' }, status: 200)
blob = Factory(:url_content_blob)
assert !blob.file_exists?
assert_equal nil, blob.file_size
blob.retrieve
assert blob.file_exists?
assert_equal 5000, blob.file_size
end
test 'is_text?' do
assert Factory(:txt_content_blob).is_text?
assert Factory(:csv_content_blob).is_text?
assert Factory(:tsv_content_blob).is_text?
assert Factory(:teusink_model_content_blob).is_text?
assert Factory(:json_content_blob).is_text?
refute Factory(:ppt_content_blob).is_text?
refute Factory(:binary_content_blob).is_text?
end
end
Another test change
require 'test_helper'
require 'docsplit'
require 'seek/download_handling/http_streamer' # Needed to load exceptions that are tested later
class ContentBlobTest < ActiveSupport::TestCase
fixtures :content_blobs
test 'search terms' do
blob = ContentBlob.new
blob.url = 'http://fish.com'
assert_includes blob.search_terms, 'fish'
assert_includes blob.search_terms, 'http://fish.com'
refute_includes blob.search_terms, 'http'
refute_includes blob.search_terms, 'com'
blob = Factory(:txt_content_blob)
assert_includes blob.search_terms, 'txt_test.txt'
assert_includes blob.search_terms, 'txt'
end
test 'max indexable text size' do
blob = Factory :large_txt_content_blob
size = blob.file_size
assert size > 1.megabyte
assert size < 2.megabyte
assert blob.is_text?
with_config_value :max_indexable_text_size, 1 do
refute blob.is_indexable_text?
end
with_config_value :max_indexable_text_size, 2 do
assert blob.is_indexable_text?
end
with_config_value :max_indexable_text_size, '2' do
assert blob.is_indexable_text?
end
end
test 'md5sum_on_demand' do
blob = Factory :rightfield_content_blob
assert_not_nil blob.md5sum
assert_equal '01788bca93265d80e8127ca0039bb69b', blob.md5sum
end
test 'sha1 sum on demand' do
blob = Factory :rightfield_content_blob
assert_not_nil blob.sha1sum
assert_equal 'ffd634ac7564083ab7b66bc3eb2053cbc3d608f5', blob.sha1sum
end
test 'detects it is a webpage' do
as_not_virtualliver do
mock_remote_file "#{Rails.root}/test/fixtures/files/html_file.html", 'http://webpage.com', 'Content-Type' => 'text/html'
blob = ContentBlob.create url: 'http://webpage.com', original_filename: nil, content_type: nil, external_link: true
assert blob.is_webpage?
assert_equal 'text/html', blob.content_type
end
end
test 'detectes webpage if content-type includes charset info' do
as_not_virtualliver do
mock_remote_file "#{Rails.root}/test/fixtures/files/html_file.html", 'http://webpage.com', 'Content-Type' => 'text/html; charset=ascii'
blob = ContentBlob.create url: 'http://webpage.com', original_filename: nil, content_type: nil, external_link: true
assert blob.is_webpage?
assert_equal 'text/html', blob.content_type
end
end
test 'only overrides url content-type if not already known' do
as_not_virtualliver do
mock_remote_file "#{Rails.root}/test/fixtures/files/html_file.html", 'http://webpage.com', 'Content-Type' => 'text/html'
mock_remote_file "#{Rails.root}/test/fixtures/files/file_picture.png", 'http://webpage.com/piccy.png', 'Content-Type' => 'image/png'
blob = ContentBlob.create url: 'http://webpage.com', original_filename: nil, content_type: nil, external_link: true
assert_equal 'text/html', blob.content_type
blob = ContentBlob.create url: 'http://webpage.com/piccy.png', original_filename: nil, content_type: nil
assert_equal 'image/png', blob.content_type
blob = ContentBlob.create url: 'http://webpage.com/piccy.png', original_filename: nil, content_type: 'application/pdf'
assert_equal 'application/pdf', blob.content_type
end
end
test "detects it isn't a webpage" do
as_not_virtualliver do
mock_remote_file "#{Rails.root}/test/fixtures/files/file_picture.png", 'http://webpage.com/piccy.png', 'Content-Type' => 'image/png'
blob = ContentBlob.create url: 'http://webpage.com/piccy.png', original_filename: nil, content_type: nil
assert !blob.is_webpage?
assert_equal 'image/png', blob.content_type
end
end
test 'handles an unavailable url when checking for a webpage' do
mock_remote_file "#{Rails.root}/test/fixtures/files/file_picture.png", 'http://webpage.com/piccy.png', { 'Content-Type' => 'image/png' }, 500
blob = ContentBlob.create url: 'http://webpage.com/piccy.png', original_filename: nil, content_type: nil
assert !blob.is_webpage?
end
test "content type for url type with binary doesn't try read file" do
mock_remote_file "#{Rails.root}/test/fixtures/files/file_picture.png", 'http://webpage.com/binary-file', { 'Content-Type' => 'application/octet-stream' }, 500
blob = ContentBlob.create url: 'http://webpage.com/binary-file', original_filename: nil, content_type: 'application/octet-stream'
assert_equal 'application/octet-stream', blob.content_type
end
def test_cache_key
blob = Factory :rightfield_content_blob
assert_equal "content_blobs/#{blob.id}-ffd634ac7564083ab7b66bc3eb2053cbc3d608f5", blob.cache_key
end
def test_uuid_doesnt_change
blob = content_blobs(:picture_blob)
blob.uuid = 'zzz'
assert_equal 'zzz', blob.uuid
blob.save!
assert_equal 'zzz', blob.uuid
end
def test_uuid_doesnt_change2
blob = content_blobs(:picture_blob)
blob.uuid = 'zzz'
blob.save!
blob = ContentBlob.find(blob.id)
assert_equal 'zzz', blob.uuid
blob.save!
blob = ContentBlob.find(blob.id)
assert_equal 'zzz', blob.uuid
end
def test_regenerate_uuid
pic = content_blobs(:picture_blob)
uuid = pic.uuid
pic.regenerate_uuid
assert_not_equal uuid, pic.uuid
end
def test_file_dump
pic = content_blobs(:picture_blob)
blob = ContentBlob.new(data: pic.data_io_object.read, original_filename: 'piccy.jpg')
blob.save!
assert_not_nil blob.filepath
data = nil
File.open(blob.filepath, 'rb') do |f|
data = f.read
end
assert_not_nil data
assert_equal data_for_test('file_picture.png'), data
end
# checks that the data is assigned through the new method, stored to a file, and not written to the old data_old field
def test_data_assignment
pic = content_blobs(:picture_blob)
pic.save! # to trigger callback to save to file
blob = ContentBlob.new(data: pic.data_io_object.read, original_filename: 'piccy.jpg')
blob.save!
blob = ContentBlob.find(blob.id)
assert_equal data_for_test('file_picture.png'), blob.data_io_object.read
assert_not_nil blob.filepath
data = nil
File.open(blob.filepath, 'rb') do |f|
data = f.read
end
assert_not_nil data
assert_equal data_for_test('file_picture.png'), data
end
# simply checks that get and set data returns the same thing
def test_data_assignment2
pic = content_blobs(:picture_blob)
pic.data = data_for_test('little_file.txt')
pic.save!
assert_equal data_for_test('little_file.txt'), pic.data_io_object.read
# put it back, otherwise other tests fail
pic.data = data_for_test('file_picture.png')
pic.save!
end
#
def test_will_overwrite_if_data_changes
pic = content_blobs(:picture_blob)
pic.save!
assert_equal data_for_test('file_picture.png'), File.open(pic.filepath, 'rb').read
pic.data = data_for_test('little_file.txt')
pic.save!
assert_equal data_for_test('little_file.txt'), File.open(pic.filepath, 'rb').read
end
def test_uuid
pic = content_blobs(:picture_blob)
blob = ContentBlob.new(data: pic.data_io_object.read, original_filename: 'piccy.jpg')
blob.save!
assert_not_nil blob.uuid
assert_not_nil ContentBlob.find(blob.id).uuid
end
def data_for_test(filename)
file = "#{Rails.root}/test/fixtures/files/#{filename}"
File.open(file, 'rb').read
end
def test_tmp_io_object
io_object = Tempfile.new('tmp_io_object_test')
io_object.write("blah blah\nmonkey_business")
blob = ContentBlob.new(tmp_io_object: io_object, original_filename: 'monkey.txt')
assert_difference('ContentBlob.count') do
blob.save!
end
blob.reload
assert_not_nil blob.filepath
assert File.exist?(blob.filepath)
data = nil
File.open(blob.filepath, 'rb') do |f|
data = f.read
end
assert_not_nil data
assert_equal "blah blah\nmonkey_business", data.to_s
end
def test_string_io_object
io_object = StringIO.new('frog')
blob = ContentBlob.new(tmp_io_object: io_object, original_filename: 'frog.txt')
assert_difference('ContentBlob.count') do
blob.save!
end
blob.reload
assert_not_nil blob.filepath
assert File.exist?(blob.filepath)
data = nil
File.open(blob.filepath, 'rb') do |f|
data = f.read
end
assert_not_nil data
assert_equal 'frog', data.to_s
end
test 'validates by content blob or url' do
blob = ContentBlob.new
refute blob.valid?
blob.original_filename = 'fish'
assert blob.valid?
blob.original_filename = nil
blob.url = 'http://google.com'
assert blob.valid?
end
def test_data_io
io_object = StringIO.new('frog')
blob = ContentBlob.new(tmp_io_object: io_object, original_filename: 'frog.txt')
blob.save!
blob.reload
assert_equal 'frog', blob.data_io_object.read
f = Tempfile.new('seek-data-io-test')
f << 'fish'
f.close
io_object = File.new(f.path, 'r')
blob = ContentBlob.new(tmp_io_object: io_object, original_filename: 'seek-data-io-test')
blob.save!
blob.reload
io_object.rewind
assert_equal io_object.read, blob.data_io_object.read
mock_remote_file "#{Rails.root}/test/fixtures/files/file_picture.png", 'http://www.webpage.com/image.png'
blob = ContentBlob.new(url: 'http://www.webpage.com/image.png')
blob.save!
blob.reload
assert_nil blob.data_io_object
blob = ContentBlob.new original_filename: 'nil'
assert_nil blob.data_io_object
blob.save!
assert_nil blob.data_io_object
end
def test_filesize
cb = Factory :content_blob, data: 'z'
assert_equal 1, cb.file_size
File.delete(cb.filepath)
assert_equal 1, cb.file_size
cb = Factory :rightfield_content_blob
assert_not_nil cb.file_size
assert_equal 9216, cb.file_size
end
def test_exception_when_both_data_and_io_object
io_object = StringIO.new('frog')
blob = ContentBlob.new(tmp_io_object: io_object, data: 'snake', original_filename: 'snake.txt')
assert_raise Exception do
blob.save
end
end
test 'storage_directory and filepath' do
content_blob = Factory(:content_blob)
storage_directory = content_blob.data_storage_directory
converted_storage_directory = content_blob.converted_storage_directory
assert_equal "#{Rails.root}/tmp/testing-filestore/assets", storage_directory
assert_equal "#{Rails.root}/tmp/testing-filestore/converted-assets", converted_storage_directory
assert_equal (storage_directory + '/' + content_blob.uuid + '.dat'), content_blob.filepath
assert_equal (converted_storage_directory + '/' + content_blob.uuid + '.pdf'), content_blob.filepath('pdf')
assert_equal (converted_storage_directory + '/' + content_blob.uuid + '.txt'), content_blob.filepath('txt')
end
test 'file_exists?' do
# specify uuid here to avoid repeating uuid of other content_blob when running the whole test file
content_blob = Factory(:content_blob, uuid: '1111')
assert content_blob.file_exists?
content_blob = Factory(:content_blob, uuid: '2222', data: nil)
assert !content_blob.file_exists?
end
test 'human content type' do
content_blob = Factory(:docx_content_blob)
assert_equal 'Word document', content_blob.human_content_type
content_blob = Factory(:content_blob, content_type: 'application/msexcel')
assert_equal 'Spreadsheet', content_blob.human_content_type
content_blob = Factory.create(:pdf_content_blob, content_type: 'application/pdf')
assert_equal 'PDF document', content_blob.human_content_type
content_blob = Factory(:content_blob, content_type: 'text/html')
assert_equal 'HTML document', content_blob.human_content_type
content_blob = Factory(:content_blob, content_type: 'application/x-download')
assert_equal 'Unknown file type', content_blob.human_content_type
content_blob = Factory(:content_blob, content_type: '')
assert_equal 'Unknown file type', content_blob.human_content_type
content_blob = Factory(:content_blob)
assert_equal 'Unknown file type', content_blob.human_content_type
content_blob = Factory(:tiff_content_blob)
assert_equal 'TIFF image', content_blob.human_content_type
end
test 'mimemagic updates content type on creation if binary' do
tmp_blob = Factory(:pdf_content_blob) # to get the filepath
content_blob = ContentBlob.create data: File.new(tmp_blob.filepath, 'rb').read, original_filename: 'blob', content_type: 'application/octet-stream'
assert_equal 'application/pdf', content_blob.content_type
assert content_blob.is_pdf?
end
test 'is_binary?' do
content_blob = Factory(:pdf_content_blob)
refute content_blob.is_binary?
content_blob = Factory(:binary_content_blob)
assert content_blob.is_binary?
end
test 'covert_office should doc to pdf and then docslit convert pdf to txt' do
check_for_soffice
content_blob = Factory(:doc_content_blob, uuid: 'doc_1')
assert File.exist? content_blob.filepath
pdf_path = content_blob.filepath('pdf')
FileUtils.rm pdf_path if File.exist? pdf_path
assert !File.exist?(pdf_path)
content_blob.convert_to_pdf
assert File.exist?(pdf_path), 'pdf was not created during conversion'
content_blob.extract_text_from_pdf
assert File.exist? content_blob.filepath('txt')
content = File.open(content_blob.filepath('txt'), 'rb').read
assert content.include?('This is a ms word doc format')
end
test 'convert_office should convert docx to pdf and then docsplit convert pdf to txt' do
check_for_soffice
content_blob = Factory(:docx_content_blob, uuid: 'docx_1')
assert File.exist? content_blob.filepath
FileUtils.rm content_blob.filepath('pdf') if File.exist? content_blob.filepath('pdf')
assert !File.exist?(content_blob.filepath('pdf'))
content_blob.convert_to_pdf
assert File.exist?(content_blob.filepath('pdf')), 'pdf was not created during conversion'
content_blob.extract_text_from_pdf
assert File.exist? content_blob.filepath('txt')
content = File.open(content_blob.filepath('txt'), 'rb').read
assert content.include?('This is a ms word docx format')
end
test 'convert_office should convert odt to pdf and then docsplit converts pdf to txt' do
check_for_soffice
content_blob = Factory(:odt_content_blob, uuid: 'odt_1')
assert File.exist? content_blob.filepath
FileUtils.rm content_blob.filepath('pdf') if File.exist? content_blob.filepath('pdf')
assert !File.exist?(content_blob.filepath('pdf'))
content_blob.convert_to_pdf
assert File.exist?(content_blob.filepath('pdf')), 'pdf was not created during conversion'
content_blob.extract_text_from_pdf
assert File.exist? content_blob.filepath('txt')
content = File.open(content_blob.filepath('txt'), 'rb').read
assert content.include?('This is an open office word odt format')
end
test 'convert_office should convert ppt to pdf and then docsplit converts pdf to txt' do
check_for_soffice
content_blob = Factory(:ppt_content_blob, uuid: 'ppt_1')
assert File.exist? content_blob.filepath
FileUtils.rm content_blob.filepath('pdf') if File.exist? content_blob.filepath('pdf')
assert !File.exist?(content_blob.filepath('pdf'))
content_blob.convert_to_pdf
assert File.exist?(content_blob.filepath('pdf')), 'pdf was not created during conversion'
content_blob.extract_text_from_pdf
assert File.exist? content_blob.filepath('txt')
content = File.open(content_blob.filepath('txt'), 'rb').read
assert content.include?('This is a ms power point ppt format')
end
test 'convert_office should convert pptx to pdf and then docsplit converts pdf to txt' do
check_for_soffice
content_blob = Factory(:pptx_content_blob, uuid: 'pptx_1')
assert File.exist? content_blob.filepath
FileUtils.rm content_blob.filepath('pdf') if File.exist? content_blob.filepath('pdf')
assert !File.exist?(content_blob.filepath('pdf'))
content_blob.convert_to_pdf
assert File.exist?(content_blob.filepath('pdf')), 'pdf was not created during conversion'
content_blob.extract_text_from_pdf
assert File.exist? content_blob.filepath('txt')
content = File.open(content_blob.filepath('txt'), 'rb').read
assert content.include?('This is a ms power point pptx format')
end
test 'convert_office should convert odp to pdf and then docsplit converts pdf to txt' do
check_for_soffice
content_blob = Factory(:odp_content_blob, uuid: 'odp_1')
assert File.exist? content_blob.filepath
FileUtils.rm content_blob.filepath('pdf') if File.exist? content_blob.filepath('pdf')
assert !File.exist?(content_blob.filepath('pdf'))
content_blob.convert_to_pdf
assert File.exist?(content_blob.filepath('pdf')), 'pdf was not created during conversion'
content_blob.extract_text_from_pdf
assert File.exist? content_blob.filepath('txt')
content = File.open(content_blob.filepath('txt'), 'rb').read
assert content.include?('This is an open office power point odp format')
end
test 'convert_office should convert rtf to pdf and then docsplit converts pdf to txt' do
check_for_soffice
content_blob = Factory(:rtf_content_blob, uuid: 'rtf_1')
assert File.exist? content_blob.filepath
FileUtils.rm content_blob.filepath('pdf') if File.exist? content_blob.filepath('pdf')
assert !File.exist?(content_blob.filepath('pdf'))
content_blob.convert_to_pdf
assert File.exist?(content_blob.filepath('pdf')), 'pdf was not created during conversion'
content_blob.extract_text_from_pdf
assert File.exist? content_blob.filepath('txt')
content = File.open(content_blob.filepath('txt'), 'rb').read
assert content.mb_chars.normalize.include?('This is a rtf format')
end
test 'convert_office should convert txt to pdf' do
check_for_soffice
content_blob = Factory(:txt_content_blob, uuid: 'txt_1')
assert File.exist? content_blob.filepath
FileUtils.rm content_blob.filepath('pdf') if File.exist? content_blob.filepath('pdf')
assert !File.exist?(content_blob.filepath('pdf'))
content_blob.convert_to_pdf
assert File.exist?(content_blob.filepath('pdf')), 'pdf was not created during conversion'
end
test 'is_content_viewable?' do
viewable_formats = %w(application/pdf)
viewable_formats << 'application/msword'
viewable_formats << 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
viewable_formats << 'application/vnd.ms-powerpoint'
viewable_formats << 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
viewable_formats << 'application/vnd.oasis.opendocument.text'
viewable_formats << 'application/vnd.oasis.opendocument.presentation'
viewable_formats << 'application/rtf'
viewable_formats.each do |viewable_format|
cb_with_content_viewable_format = Factory(:content_blob, content_type: viewable_format, asset: Factory(:sop), data: File.new("#{Rails.root}/test/fixtures/files/a_pdf_file.pdf", 'rb').read)
User.with_current_user cb_with_content_viewable_format.asset.contributor do
assert cb_with_content_viewable_format.is_viewable_format?
assert cb_with_content_viewable_format.is_content_viewable?
end
end
cb_with_no_viewable_format = Factory(:content_blob, content_type: 'application/excel', asset: Factory(:sop), data: File.new("#{Rails.root}/test/fixtures/files/spreadsheet.xls", 'rb').read)
User.with_current_user cb_with_no_viewable_format.asset.contributor do
assert !cb_with_no_viewable_format.is_viewable_format?
assert !cb_with_no_viewable_format.is_content_viewable?
end
end
test 'content needing conversion should not be viewable when pdf_conversion is disabled' do
with_config_value :pdf_conversion_enabled, false do
viewable_formats = %w(application/msword)
viewable_formats << 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
viewable_formats << 'application/vnd.ms-powerpoint'
viewable_formats << 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
viewable_formats << 'application/vnd.oasis.opendocument.text'
viewable_formats << 'application/vnd.oasis.opendocument.presentation'
viewable_formats.each do |viewable_format|
cb_with_content_viewable_format = Factory(:content_blob, content_type: viewable_format, asset: Factory(:sop), data: File.new("#{Rails.root}/test/fixtures/files/a_pdf_file.pdf", 'rb').read)
User.with_current_user cb_with_content_viewable_format.asset.contributor do
assert !cb_with_content_viewable_format.is_content_viewable?
end
end
end
end
test 'content not needing conversion should be viewable when pdf_conversion is disabled' do
pdf_content_blob = Factory(:content_blob, content_type: 'application/pdf', asset: Factory(:sop), data: File.new("#{Rails.root}/test/fixtures/files/a_pdf_file.pdf", 'rb').read)
with_config_value :pdf_conversion_enabled, false do
viewable_formats = %w(text/plain text/csv text/tsv)
viewable_formats.each do |viewable_format|
cb_with_content_viewable_format = Factory(:content_blob, content_type: viewable_format, asset: Factory(:sop), data: File.new("#{Rails.root}/test/fixtures/files/a_pdf_file.pdf", 'rb').read)
User.with_current_user cb_with_content_viewable_format.asset.contributor do
assert cb_with_content_viewable_format.is_content_viewable?
end
end
User.with_current_user pdf_content_blob.asset.contributor do
assert pdf_content_blob.is_content_viewable?
end
end
end
test 'filter_text_content' do
check_for_soffice
ms_word_sop_cb = Factory(:doc_content_blob)
content = "test \n content \f only"
filtered_content = ms_word_sop_cb.send(:filter_text_content, content)
assert !filtered_content.include?('\n')
assert !filtered_content.include?('\f')
end
test 'pdf_contents_for_search for a doc file' do
check_for_soffice
ms_word_sop_content_blob = Factory(:doc_content_blob)
assert ms_word_sop_content_blob.is_pdf_convertable?
content = ms_word_sop_content_blob.pdf_contents_for_search
assert_equal ['This is a ms word doc format'], content
end
test 'pdf_contents_for_search for a pdf file' do
check_for_soffice
pdf_content_blob = Factory(:pdf_content_blob)
content = pdf_content_blob.pdf_contents_for_search
assert_equal ['This is a pdf format'], content
end
test 'calculates file size' do
blob = Factory(:pdf_content_blob)
assert_equal 8827, blob.file_size
end
test 'updates file size' do
blob = Factory(:pdf_content_blob)
blob.data = '123456'
blob.save
assert_equal 6, blob.file_size
end
test 'calculates file size for remote content' do
stub_request(:head, 'http://www.abc.com').to_return(headers: { content_length: 500, content_type: 'text/plain' }, status: 200)
blob = Factory(:url_content_blob)
assert_equal 500, blob.file_size
end
test 'can retrieve remote content' do
stub_request(:head, 'http://www.abc.com').to_return(
headers: { content_length: nil, content_type: 'text/plain' }, status: 200)
stub_request(:get, 'http://www.abc.com').to_return(body: 'abcdefghij' * 500,
headers: { content_type: 'text/plain' }, status: 200)
blob = Factory(:url_content_blob)
assert !blob.file_exists?
assert_equal nil, blob.file_size
blob.retrieve
assert blob.file_exists?
assert_equal 5000, blob.file_size
end
test "won't retrieve remote content over hard limit" do
# Web server lies about content length:
stub_request(:head, 'http://www.abc.com').to_return(
headers: { content_length: 500, content_type: 'text/plain' }, status: 200)
# Size is actually 6kb:
stub_request(:get, 'http://www.abc.com').to_return(body: 'abcdefghij' * 600,
headers: { content_type: 'text/plain' }, status: 200)
blob = Factory(:url_content_blob)
assert !blob.file_exists?
assert_equal 500, blob.file_size
assert_raise Seek::DownloadHandling::SizeLimitExceededException do
blob.retrieve
end
assert !blob.file_exists?
end
test "won't endlessly follow redirects when downloading remote content" do
stub_request(:head, 'http://www.abc.com').to_return(
headers: { content_length: 500, content_type: 'text/plain' }, status: 200)
# Infinitely redirects
stub_request(:get, 'http://www.abc.com').to_return(headers: { location: 'http://www.abc.com' }, status: 302)
blob = Factory(:url_content_blob)
assert !blob.file_exists?
assert_equal 500, blob.file_size
assert_raise Seek::DownloadHandling::RedirectLimitExceededException do
blob.retrieve
end
assert !blob.file_exists?
end
test 'raises exception on bad response code when downloading remote content' do
stub_request(:head, 'http://www.abc.com').to_return(
headers: { content_length: 500, content_type: 'text/plain' }, status: 200)
stub_request(:get, 'http://www.abc.com').to_return(status: 404)
blob = Factory(:url_content_blob)
assert !blob.file_exists?
assert_equal 500, blob.file_size
assert_raise Seek::DownloadHandling::BadResponseCodeException do
blob.retrieve
end
assert !blob.file_exists?
end
test 'handles relative redirects when downloading remote content' do
stub_request(:head, 'http://www.abc.com').to_return(headers: { location: '/xyz' }, status: 302)
stub_request(:get, 'http://www.abc.com').to_return(headers: { location: '/xyz' }, status: 302)
stub_request(:head, 'http://www.abc.com/xyz').to_return(
headers: { content_length: nil, content_type: 'text/plain' }, status: 200)
stub_request(:get, 'http://www.abc.com/xyz').to_return(body: 'abcdefghij' * 500,
headers: { content_type: 'text/plain' }, status: 200)
blob = Factory(:url_content_blob)
assert !blob.file_exists?
assert_equal nil, blob.file_size
blob.retrieve
assert blob.file_exists?
assert_equal 5000, blob.file_size
end
test 'handles absolute redirects when downloading remote content' do
stub_request(:head, 'http://www.abc.com').to_return(headers: { location: 'http://www.abc.com/xyz' }, status: 302)
stub_request(:get, 'http://www.abc.com').to_return(headers: { location: 'http://www.abc.com/xyz' }, status: 302)
stub_request(:head, 'http://www.abc.com/xyz').to_return(
headers: { content_length: nil, content_type: 'text/plain' }, status: 200)
stub_request(:get, 'http://www.abc.com/xyz').to_return(body: 'abcdefghij' * 500,
headers: { content_type: 'text/plain' }, status: 200)
blob = Factory(:url_content_blob)
assert !blob.file_exists?
assert_equal nil, blob.file_size
blob.retrieve
assert blob.file_exists?
assert_equal 5000, blob.file_size
end
test 'handles mixed redirects when downloading remote content' do
stub_request(:head, 'http://www.abc.com').to_return(headers: { location: 'http://www.xyz.com' }, status: 302)
stub_request(:get, 'http://www.abc.com').to_return(headers: { location: 'http://www.xyz.com' }, status: 302)
stub_request(:head, 'http://www.xyz.com').to_return(headers: { location: '/xyz' }, status: 302)
stub_request(:get, 'http://www.xyz.com').to_return(headers: { location: '/xyz' }, status: 302)
stub_request(:head, 'http://www.xyz.com/xyz').to_return(
headers: { content_length: nil, content_type: 'text/plain' }, status: 200)
stub_request(:get, 'http://www.xyz.com/xyz').to_return(body: 'abcdefghij' * 500,
headers: { content_type: 'text/plain' }, status: 200)
blob = Factory(:url_content_blob)
assert !blob.file_exists?
assert_equal nil, blob.file_size
blob.retrieve
assert blob.file_exists?
assert_equal 5000, blob.file_size
end
test 'is_text?' do
assert Factory(:txt_content_blob).is_text?
assert Factory(:csv_content_blob).is_text?
assert Factory(:tsv_content_blob).is_text?
assert Factory(:teusink_model_content_blob).is_text?
assert Factory(:json_content_blob).is_text?
refute Factory(:ppt_content_blob).is_text?
refute Factory(:binary_content_blob).is_text?
end
end
|
require 'test_helper'
class RecordsControllerTest < ActionController::TestCase
setup do
@record = records(:one)
# add pseudo authentication so the tests don't break
CASClient::Frameworks::Rails::Filter.fake("homer")
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:records)
end
test "should get new" do
get :new
assert_response :success
end
test "should create record" do
assert_difference('Record.count') do
post :create, record: { cas_user_name: @record.cas_user_name, metadata: @record.metadata, title: @record.title }
end
assert_redirected_to record_path(assigns(:record))
end
test "should show record" do
get :show, id: @record
if record_exists(@record.id)
# we only allow individuals to access records
# if they created those records,
# and if the requested record exists
# otherwise we redirect them to the home page,
# so verify the user created this record
if @record.cas_user_name == session[:cas_username]
assert_response :success
else
assert_redirected_to root_path
end
else
assert_redirected_to root_path
end
end
test "should get edit" do
get :edit, id: @record
if record_exists(@record.id)
# we only allow individuals to access records
# if they created those records,
# and if the requested record exists
# otherwise we redirect them to the home page,
# so verify the user created this record
if @record.cas_user_name == session[:cas_username]
assert_response :success
else
assert_redirected_to root_path
end
else
assert_redirected_to root_path
end
end
test "should update record" do
if record_exists(@record.id)
patch :update, id: @record, record: { cas_user_name: @record.cas_user_name, metadata: @record.metadata, title: @record.title }
# we only allow individuals to access records
# if they created those records,
# and if the requested record exists
# otherwise we redirect them to the home page,
# so verify the user created this record
if @record.cas_user_name == session[:cas_username]
assert_redirected_to record_path(assigns(:record))
else
assert_redirected_to root_path
end
end
end
test "should destroy record" do
if @record.cas_user_name == session[:cas_username]
assert_difference('Record.count', -1) do
delete :destroy, id: @record
end
end
end
end
update records controller test to check for redirects to appropriate places
require 'test_helper'
class RecordsControllerTest < ActionController::TestCase
setup do
@record = records(:one)
# add pseudo authentication so the tests don't break
CASClient::Frameworks::Rails::Filter.fake("homer")
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:records)
end
test "should get new" do
get :new
assert_response :success
end
test "should create record" do
assert_difference('Record.count') do
post :create, record: { cas_user_name: @record.cas_user_name, metadata: @record.metadata, title: @record.title }
end
assert_redirected_to record_path(assigns(:record))
end
test "should show record" do
get :show, id: @record
if record_exists(@record.id)
# we only allow individuals to access records
# if they created those records,
# and if the requested record exists
# otherwise we redirect them to the home page,
# so verify the user created this record
if @record.cas_user_name == session[:cas_username]
assert_response :success
else
assert_redirected_to user_show_path
end
else
assert_redirected_to user_show_path
end
end
test "should get edit" do
get :edit, id: @record
if record_exists(@record.id)
# we only allow individuals to access records
# if they created those records,
# and if the requested record exists
# otherwise we redirect them to the home page,
# so verify the user created this record
if @record.cas_user_name == session[:cas_username]
assert_response :success
else
assert_redirected_to user_show_path
end
else
assert_redirected_to user_show_path
end
end
test "should update record" do
if record_exists(@record.id)
patch :update, id: @record, record: { cas_user_name: @record.cas_user_name, metadata: @record.metadata, title: @record.title }
# we only allow individuals to access records
# if they created those records,
# and if the requested record exists
# otherwise we redirect them to the home page,
# so verify the user created this record
if @record.cas_user_name == session[:cas_username]
assert_redirected_to record_path(assigns(:record))
else
assert_redirected_to user_show_path
end
end
end
test "should destroy record" do
if @record.cas_user_name == session[:cas_username]
assert_difference('Record.count', -1) do
delete :destroy, id: @record
end
end
end
end
|
require 'test_helper'
class WelcomeControllerTest < ActionController::TestCase
def add_item(shop,category,item,name,price,good,bad)
item = Item.new
item.shop=shop
item.category=category
item.name=name
item.price=price
item.good=good
item.bad=bad
item.save
end
def setup
items = Item.all
items.each {|item|
item.destroy
}
end
test "Indexの表示" do
# 惣菜のみが表示される
self.add_item('ファミマ','惣菜','惣菜','国産鶏のサラダチキン',239,0,0)
self.add_item('セブン','惣菜','惣菜','サラダチキン',198,0,0)
self.add_item('ローソン','おにぎり','おにぎり','シーチキンマヨネーズ',110,0,0)
get :index
assert_response :success
assert_select "a.p_name",2
end
test "惣菜の表示" do
# 惣菜のみが表示される
add_item('ファミマ','惣菜','惣菜','国産鶏のサラダチキン',239,0,0)
add_item('セブン','惣菜','惣菜','サラダチキン',198,0,0)
add_item('ローソン','おにぎり','おにぎり','シーチキンマヨネーズ',110,0,0)
get :index,{"item"=>"惣菜"}
assert_response :success
assert_select "a.p_name",2
end
test "おにぎりの表示" do
# おにぎりのみが表示される
add_item('ファミマ','惣菜','惣菜','国産鶏のサラダチキン',239,0,0)
add_item('セブン','おにぎり','おにぎり','紀州南高梅',198,0,0)
add_item('ローソン','おにぎり','おにぎり','シーチキンマヨネーズ',110,0,0)
get :index,{"item"=>"おにぎり"}
assert_response :success
assert_select "a.p_name",2
end
test "スイーツの表示" do
#スイーツのみ表示される
add_item('ファミマ','スイーツ','スイーツ','プリン',239,0,0)
add_item('セブン','ドリンク','ドリンク','ドリンク2',198,0,0)
add_item('ローソン','スイーツ','スイーツ','チョコチップスナック',110,0,0)
get :index,{"item"=>"スイーツ"}
assert_response :success
assert_select "a.p_name",2
end
test "飲むヨーグルト(プレーン)の表示" do
#ドリンクのみ表示される
add_item('ファミマ','ドリンク','ドリンク','ドリンク1',239,0,0)
add_item('セブン','ドリンク','ドリンク','ドリンク2',198,0,0)
add_item('ローソン','おにぎり','おにぎり','シーチキンマヨネーズ',110,0,0)
get :index,{"item"=>"ドリンク"}
assert_response :success
assert_select "a.p_name",2
end
test "NotFoundの表示" do
#なにも表示されない
add_item('ファミマ','惣菜','惣菜','国産鶏のサラダチキン',239,0,0)
add_item('セブン','惣菜','惣菜','サラダチキン',198,0,0)
add_item('ローソン','おにぎり','おにぎり','シーチキンマヨネーズ',110,0,0)
get :index,{"item"=>"適当な商品"}
assert_response :success
assert_select ".not_found",1
end
test "商品表示順の確認" do
#惣菜のみが表示される
#惣菜2、惣菜3、惣菜1の順に表示される
item1 = add_item('ファミマ','惣菜','惣菜','惣菜1',239,5,4)
item2 = add_item('セブン','惣菜','惣菜','惣菜2',198,0,20)
item3 = add_item('ローソン','惣菜','惣菜','惣菜3',110,10,0)
get :index,{"item"=>"惣菜"}
assert_response :success
assert_select ".rank1 .p_name","惣菜2"
assert_select ".rank2 .p_name","惣菜3"
assert_select ".rank3 .p_name","惣菜1"
end
test "商品表示順の確認(同点時)" do
item1 = add_item('ファミマ','惣菜','惣菜','惣菜1',239,5,4)
item2 = add_item('セブン','惣菜','惣菜','惣菜2',198,0,20)
item3 = add_item('ローソン','惣菜','惣菜','惣菜3',110,20,0)
get :index,{"item"=>"惣菜"}
assert_response :success
assert_select ".rank1 .p_name",2
assert_select ".rank2 .p_name",0
assert_select ".rank3 .p_name",1
end
test "商品表示順の確認(全て同点時)" do
item1 = add_item('ファミマ','惣菜','惣菜','惣菜1',239,0,0)
item2 = add_item('セブン','惣菜','惣菜','惣菜2',198,0,0)
item3 = add_item('ローソン','惣菜','惣菜','惣菜3',110,0,0)
get :index,{"item"=>"惣菜"}
assert_response :success
assert_select ".rank1 .p_name",3
assert_select ".rank2 .p_name",0
assert_select ".rank3 .p_name",0
end
end
テストコードに開発中の不要な処理が残っていたので削除
require 'test_helper'
class WelcomeControllerTest < ActionController::TestCase
def add_item(shop,category,name,price,good,bad)
item = Item.new
item.shop=shop
item.category=category
item.item=category
item.name=name
item.price=price
item.good=good
item.bad=bad
item.save
end
def setup
items = Item.all
items.each {|item|
item.destroy
}
end
test "Indexの表示" do
# 惣菜のみが表示される
self.add_item('ファミマ','惣菜','国産鶏のサラダチキン',239,0,0)
self.add_item('セブン','惣菜','サラダチキン',198,0,0)
self.add_item('ローソン','おにぎり','シーチキンマヨネーズ',110,0,0)
get :index
assert_response :success
assert_select "a.p_name",2
end
test "惣菜の表示" do
# 惣菜のみが表示される
add_item('ファミマ','惣菜','国産鶏のサラダチキン',239,0,0)
add_item('セブン','惣菜','サラダチキン',198,0,0)
add_item('ローソン','おにぎり','シーチキンマヨネーズ',110,0,0)
get :index,{"item"=>"惣菜"}
assert_response :success
assert_select "a.p_name",2
end
test "おにぎりの表示" do
# おにぎりのみが表示される
add_item('ファミマ','惣菜','国産鶏のサラダチキン',239,0,0)
add_item('セブン','おにぎり','紀州南高梅',198,0,0)
add_item('ローソン','おにぎり','シーチキンマヨネーズ',110,0,0)
get :index,{"item"=>"おにぎり"}
assert_response :success
assert_select "a.p_name",2
end
test "スイーツの表示" do
#スイーツのみ表示される
add_item('ファミマ','スイーツ','プリン',239,0,0)
add_item('セブン','ドリンク','ドリンク2',198,0,0)
add_item('ローソン','スイーツ','チョコチップスナック',110,0,0)
get :index,{"item"=>"スイーツ"}
assert_response :success
assert_select "a.p_name",2
end
test "飲むヨーグルト(プレーン)の表示" do
#ドリンクのみ表示される
add_item('ファミマ','ドリンク','ドリンク1',239,0,0)
add_item('セブン','ドリンク','ドリンク2',198,0,0)
add_item('ローソン','おにぎり','シーチキンマヨネーズ',110,0,0)
get :index,{"item"=>"ドリンク"}
assert_response :success
assert_select "a.p_name",2
end
test "NotFoundの表示" do
#なにも表示されない
add_item('ファミマ','惣菜','国産鶏のサラダチキン',239,0,0)
add_item('セブン','惣菜','サラダチキン',198,0,0)
add_item('ローソン','おにぎり','シーチキンマヨネーズ',110,0,0)
get :index,{"item"=>"適当な商品"}
assert_response :success
assert_select ".not_found",1
end
test "商品表示順の確認" do
#惣菜のみが表示される
#惣菜2、惣菜3、惣菜1の順に表示される
add_item('ファミマ','惣菜','惣菜1',239,5,4)
add_item('セブン','惣菜','惣菜2',198,0,20)
add_item('ローソン','惣菜','惣菜3',110,10,0)
get :index,{"item"=>"惣菜"}
assert_response :success
assert_select ".rank1 .p_name","惣菜2"
assert_select ".rank2 .p_name","惣菜3"
assert_select ".rank3 .p_name","惣菜1"
end
test "商品表示順の確認(同点時)" do
add_item('ファミマ','惣菜','惣菜1',239,5,4)
add_item('セブン','惣菜','惣菜2',198,0,20)
add_item('ローソン','惣菜','惣菜3',110,20,0)
get :index,{"item"=>"惣菜"}
assert_response :success
assert_select ".rank1 .p_name",2
assert_select ".rank2 .p_name",0
assert_select ".rank3 .p_name",1
end
test "商品表示順の確認(全て同点時)" do
add_item('ファミマ','惣菜','惣菜1',239,0,0)
add_item('セブン','惣菜','惣菜2',198,0,0)
add_item('ローソン','惣菜','惣菜3',110,0,0)
get :index,{"item"=>"惣菜"}
assert_response :success
assert_select ".rank1 .p_name",3
assert_select ".rank2 .p_name",0
assert_select ".rank3 .p_name",0
end
end
|
Pod::Spec.new do |s|
s.name = 'ClassMapper'
s.version = '0.0.1'
s.license = 'BSD'
s.summary = 'Simple and extensible mapping between your classes and NSDictionary'
s.author = { 'Pat Shields' => 'yeoldefortran@gmail.com' }
s.homepage = 'https://github.com/pashields/ClassMapper'
s.source = { :git => 'git://github.com/pashields/ClassMapper.git' }
s.platform = :ios
s.source_files = ['ClassMapper/*.{h,m}', 'ClassMapper/Categories/*.{h,m}']
s.requires_arc = true
end
Update podspec for release.
Pod::Spec.new do |s|
s.name = 'ClassMapper'
s.version = '0.0.1'
s.license = 'BSD'
s.summary = 'A simple obj-c library for converting classes which follow Key-Value Coding (KVC) conventions to other objects.'
s.author = { 'Pat Shields' => 'yeoldefortran@gmail.com' }
s.homepage = 'https://github.com/pashields/ClassMapper'
s.source = { :git => 'git://github.com/pashields/ClassMapper.git', :tag => 'v0.0.1' }
s.platform = :ios
s.source_files = ['ClassMapper/*.{h,m}', 'ClassMapper/Categories/*.{h,m}']
s.requires_arc = true
end
|
fix bugs with stric mode
RE_PARTIAL = /.*\.(coffee|js)$/
targets = Dir.glob("(app|test)/**/*")
targets.each do |file|
if file=~RE_PARTIAL
p file
rd = IO.read file
IO.write file, "'use strict'\n" + rd
end
end |
Add is_done flag to trade_annual_report_uploads. Default is false, should be set to true when related shipments are moved to shipments table
class AddIsDoneToTradeAnnualReportUploads < ActiveRecord::Migration
def change
add_column :trade_annual_report_uploads, :is_done, :boolean, :default => false
end
end
|
#
# Be sure to run `pod lib lint PooTools.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'PooTools'
s.version = '1.3.0'
s.author = { 'crazypoo' => '273277355@qq.com' }
s.homepage = 'https://github.com/crazypoo/PTools'
s.summary = 'hahahahahahahahha.'
s.source = { :git => 'https://github.com/crazypoo/PTools.git', :tag => s.version.to_s }
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.platform = :ios, '8.0'
s.requires_arc = true
s.source_files = 'PooTools','PooTools/**/*.{h,m}'
#,'PooTools/**/*.h'
#,'PooTools/*',
#'PooTools/*.{h,m}'
s.ios.deployment_target = '8.0'
s.frameworks = 'UIKit', 'AudioToolbox','ExternalAccessory','CoreText','SystemConfiguration','WebKit','QuartzCore','CoreTelephony','Security','Foundation','AVFoundation','Speech','LocalAuthentication','HealthKit','CoreMotion'
s.dependencies = ['SDWebImage'] ,['CYLTabBarController']
#,'Mantle','TOWebViewController','DZNEmptyDataSet','IQKeyboardManager','UITableView+FDTemplateLayoutCell','FDFullscreenPopGesture','LTNavigationBar','HTAutocompleteTextField','UIViewController+Swizzled','AFNetworking','FMDB','FLEX','JPFPSStatus','DHSmartScreenshot','YCXMenu'
end
#Pod::Spec.new do |s|
#s.name = 'PTools'
#s.version = '1.1.7'
#s.summary = 'A short description of PooTools.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
#s.description = '6666666666666'
#s.homepage = 'https://github.com/crazypoo/PTools'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
#s.license = { :type => 'MIT', :file => 'LICENSE' }
#s.author = { 'crazypoo' => '273277355@qq.com' }
#s.source = { :git => 'https://github.com/crazypoo/PTools.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
#s.ios.deployment_target = '8.0'
#s.source_files = 'PooTools/Classes/**/*'
# s.resource_bundles = {
# 'PooTools' => ['PooTools/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'AudioToolbox','ExternalAccessory','CoreText','SystemConfiguration','WebKit','QuartzCore','CoreTelephony','Security','Foundation','AVFoundation','Speech','LocalAuthentication','HealthKit','CoreMotion'
# s.dependency 'AFNetworking', '~> 2.3'
#end
no message
#
# Be sure to run `pod lib lint PooTools.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'PooTools'
s.version = '1.3.1'
s.author = { 'crazypoo' => '273277355@qq.com' }
s.homepage = 'https://github.com/crazypoo/PTools'
s.summary = 'hahahahahahahahha.'
s.source = { :git => 'https://github.com/crazypoo/PTools.git', :tag => s.version.to_s }
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.platform = :ios, '8.0'
s.requires_arc = true
s.source_files = 'PooTools','PooTools/**/*.{h,m}'
#,'PooTools/**/*.h'
#,'PooTools/*',
#'PooTools/*.{h,m}'
s.ios.deployment_target = '8.0'
s.frameworks = 'UIKit', 'AudioToolbox','ExternalAccessory','CoreText','SystemConfiguration','WebKit','QuartzCore','CoreTelephony','Security','Foundation','AVFoundation','Speech','LocalAuthentication','HealthKit','CoreMotion'
s.dependencies = ['SDWebImage','CYLTabBarController']
#,'Mantle','TOWebViewController','DZNEmptyDataSet','IQKeyboardManager','UITableView+FDTemplateLayoutCell','FDFullscreenPopGesture','LTNavigationBar','HTAutocompleteTextField','UIViewController+Swizzled','AFNetworking','FMDB','FLEX','JPFPSStatus','DHSmartScreenshot','YCXMenu'
end
#Pod::Spec.new do |s|
#s.name = 'PTools'
#s.version = '1.1.7'
#s.summary = 'A short description of PooTools.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
#s.description = '6666666666666'
#s.homepage = 'https://github.com/crazypoo/PTools'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
#s.license = { :type => 'MIT', :file => 'LICENSE' }
#s.author = { 'crazypoo' => '273277355@qq.com' }
#s.source = { :git => 'https://github.com/crazypoo/PTools.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
#s.ios.deployment_target = '8.0'
#s.source_files = 'PooTools/Classes/**/*'
# s.resource_bundles = {
# 'PooTools' => ['PooTools/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'AudioToolbox','ExternalAccessory','CoreText','SystemConfiguration','WebKit','QuartzCore','CoreTelephony','Security','Foundation','AVFoundation','Speech','LocalAuthentication','HealthKit','CoreMotion'
# s.dependency 'AFNetworking', '~> 2.3'
#end
|
Pod::Spec.new do |s|
s.name = 'Position'
s.version = '0.6.0'
s.license = 'MIT'
s.summary = 'location positioning and tracking for iOS in Swift'
s.homepage = 'https://github.com/piemonte/Position'
s.social_media_url = 'http://twitter.com/piemonte'
s.authors = { 'patrick piemonte' => "patrick.piemonte@gmail.com" }
s.source = { :git => 'https://github.com/piemonte/Position.git', :tag => s.version }
s.ios.deployment_target = '10.0'
s.source_files = 'Sources/*.swift'
s.requires_arc = true
s.swift_version = '4.2'
end
update podspec
Pod::Spec.new do |s|
s.name = 'Position'
s.version = '0.6.0'
s.license = 'MIT'
s.summary = 'location positioning and tracking for iOS in Swift'
s.homepage = 'https://github.com/piemonte/Position'
s.social_media_url = 'http://twitter.com/piemonte'
s.authors = { 'patrick piemonte' => "patrick.piemonte@gmail.com" }
s.source = { :git => 'https://github.com/piemonte/Position.git', :tag => s.version }
s.ios.deployment_target = '10.0'
s.source_files = 'Sources/*.swift'
s.requires_arc = true
s.swift_version = '5.0'
end
|
require pegasus_dir 'forms/volunteer_engineer_submission'
class VolunteerEngineerSubmission2015 < VolunteerEngineerSubmission
def self.normalize(data)
result = {}
result[:name_s] = required stripped data[:name_s]
result[:company_s] = nil_if_empty stripped data[:company_s]
result[:experience_s] = required data[:experience_s]
result[:location_s] = required stripped data[:location_s]
result[:location_flexibility_ss] = required data[:location_flexibility_ss]
result[:volunteer_after_hoc_b] = nil_if_empty data[:volunteer_after_hoc_b]
result[:time_commitment_s] = nil_if_empty data[:time_commitment_s]
result[:linkedin_s] = nil_if_empty stripped data[:linkedin_s]
result[:facebook_s] = nil_if_empty stripped data[:facebook_s]
result[:description_s] = required data[:description_s]
result[:email_s] = required email_address data[:email_s]
result[:allow_contact_b] = required data[:allow_contact_b]
result
end
def self.commitments()
@commitments ||= commitments_with_i18n_labels(
'annually',
'monthly',
'weekly',
'more',
)
end
def self.locations()
@locations ||= locations_with_i18n_labels(
'onsite',
'remote',
)
end
def self.locations_with_i18n_labels(*locations)
results = {}
locations.each do |location|
results[location] = I18n.t("volunteer_engineer_submission_location_flexibility_#{location}")
end
results
end
end
add Non-engineer at a tech company to volunteer engineer signup form
require pegasus_dir 'forms/volunteer_engineer_submission'
class VolunteerEngineerSubmission2015 < VolunteerEngineerSubmission
def self.normalize(data)
result = {}
result[:name_s] = required stripped data[:name_s]
result[:company_s] = nil_if_empty stripped data[:company_s]
result[:experience_s] = required data[:experience_s]
result[:location_s] = required stripped data[:location_s]
result[:location_flexibility_ss] = required data[:location_flexibility_ss]
result[:volunteer_after_hoc_b] = nil_if_empty data[:volunteer_after_hoc_b]
result[:time_commitment_s] = nil_if_empty data[:time_commitment_s]
result[:linkedin_s] = nil_if_empty stripped data[:linkedin_s]
result[:facebook_s] = nil_if_empty stripped data[:facebook_s]
result[:description_s] = required data[:description_s]
result[:email_s] = required email_address data[:email_s]
result[:allow_contact_b] = required data[:allow_contact_b]
result
end
def self.commitments()
@commitments ||= commitments_with_i18n_labels(
'annually',
'monthly',
'weekly',
'more',
)
end
def self.locations()
@locations ||= locations_with_i18n_labels(
'onsite',
'remote',
)
end
def self.experiences()
@experiences ||= experiences_with_i18n_labels(
'unspecified',
'tech_company',
'university_student_or_researcher',
'software_professional',
)
end
def self.locations_with_i18n_labels(*locations)
results = {}
locations.each do |location|
results[location] = I18n.t("volunteer_engineer_submission_location_flexibility_#{location}")
end
results
end
end
|
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'fruit_to_lime'
s.version = '2.1.0'
s.platform = Gem::Platform::RUBY
s.authors = ['Oskar Gewalli', 'Peter Wilhelmsson', 'Anders Pålsson']
s.email = 'support@lundalogik.se'
s.summary = 'Library to generate Lime Go xml import format'
s.description = <<-EOF
With this small library it should be much easier to generate import file to Lime Go.
EOF
s.add_dependency 'iso_country_codes'
s.add_dependency 'bundler'
s.add_dependency 'thor'
s.add_development_dependency 'rspec', '>= 2.14'
s.add_development_dependency 'rake'
s.files = Dir.glob('lib/**/*.rb') + Dir.glob('bin/**/*') + Dir.glob('templates/**/*')
s.test_files = Dir.glob('spec/**/*.rb')
s.executables = ['fruit_to_lime']
s.require_paths = ['lib']
end
Actually needed roo because of helper
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'fruit_to_lime'
s.version = '2.1.0'
s.platform = Gem::Platform::RUBY
s.authors = ['Oskar Gewalli', 'Peter Wilhelmsson', 'Anders Pålsson']
s.email = 'support@lundalogik.se'
s.summary = 'Library to generate Lime Go xml import format'
s.description = <<-EOF
With this small library it should be much easier to generate import file to Lime Go.
EOF
s.add_dependency 'iso_country_codes'
s.add_dependency 'bundler'
s.add_dependency 'thor'
s.add_dependency 'roo'
s.add_development_dependency 'rspec', '>= 2.14'
s.add_development_dependency 'rake'
s.files = Dir.glob('lib/**/*.rb') + Dir.glob('bin/**/*') + Dir.glob('templates/**/*')
s.test_files = Dir.glob('spec/**/*.rb')
s.executables = ['fruit_to_lime']
s.require_paths = ['lib']
end
|
Pod::Spec.new do |s|
s.name = 'Colorblinds'
s.version = '1.0.11'
s.summary = 'Colorblinds is an easy to use library to simulate color blindness in your app.'
s.description = <<-DESC
Colorblinds is a easy to use library to simulate color blindness within your app. The feature can be easily activated with a 3-tap gesture.
DESC
s.homepage = 'https://github.com/jordidekock/Colorblinds'
s.screenshots = ['https://raw.githubusercontent.com/jordidekock/Colorblinds/master/screen1.PNG', 'https://raw.githubusercontent.com/jordidekock/Colorblinds/master/screen2.PNG']
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Jordi de Kock' => 'jordidekock@gmail.com' }
s.source = { :git => 'https://github.com/jordidekock/Colorblinds.git', :tag => 'v1.0.11' }
s.ios.deployment_target = '8.0'
s.source_files = 'Source/*'
end
Updated podspec
Pod::Spec.new do |s|
s.name = 'Colorblinds'
s.version = '1.1'
s.summary = 'Colorblinds is an easy to use library to simulate color blindness in your app.'
s.description = <<-DESC
Colorblinds is a easy to use library to simulate color blindness within your app. The feature can be easily activated with a 3-tap gesture.
DESC
s.homepage = 'https://github.com/jordidekock/Colorblinds'
s.screenshots = ['https://raw.githubusercontent.com/jordidekock/Colorblinds/master/screen1.PNG', 'https://raw.githubusercontent.com/jordidekock/Colorblinds/master/screen2.PNG']
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Jordi de Kock' => 'jordidekock@gmail.com' }
s.source = { :git => 'https://github.com/jordidekock/Colorblinds.git', :tag => 'v1.0.11' }
s.ios.deployment_target = '8.0'
s.source_files = 'Source/*'
end
|
require 'test_helper'
require 'tmpdir'
class ExtractTextTest < Test::Unit::TestCase
def test_paged_extraction
Docsplit.extract_text('test/fixtures/obama_arts.pdf', :pages => 'all', :output => OUTPUT)
assert Dir["#{OUTPUT}/*.txt"].length == 2
assert File.read("#{OUTPUT}/obama_arts_1.txt").match("Paid for by Obama for America")
end
def test_page_only_extraction
Docsplit.extract_text('test/fixtures/obama_arts.pdf', :pages => 2..2, :output => OUTPUT)
assert Dir["#{OUTPUT}/*.txt"] == ["#{OUTPUT}/obama_arts_2.txt"]
end
def test_capitalized_pdf_extraction
Dir["#{OUTPUT}/*.txt"].each {|previous| FileUtils.rm(previous) }
Dir.mktmpdir do |dir|
FileUtils.cp('test/fixtures/obama_arts.pdf', "#{dir}/OBAMA_ARTS.PDF")
Docsplit.extract_text("#{dir}/OBAMA_ARTS.PDF", :pages => 2..2, :output => OUTPUT)
end
assert Dir["#{OUTPUT}/*.txt"] == ["#{OUTPUT}/OBAMA_ARTS_2.txt"]
end
def test_unicode_extraction
Docsplit.extract_text('test/fixtures/unicode.pdf', :pages => 'all', :output => OUTPUT)
assert Dir["#{OUTPUT}/*.txt"].length == 3
end
def test_ocr_extraction
Docsplit.extract_text('test/fixtures/corrosion.pdf', :pages => 'all', :output => OUTPUT)
assert Dir["#{OUTPUT}/*.txt"].length == 4
4.times do |i|
file = "corrosion_#{i + 1}.txt"
# File.open("test/fixtures/corrosion/#{file}", "w+") {|f| f.write(File.read("#{OUTPUT}/#{file}")) }
assert File.read("#{OUTPUT}/#{file}") == File.read("test/fixtures/corrosion/#{file}")
end
end
def test_ocr_extraction_in_mock_language
exception = assert_raise(Docsplit::ExtractionFailed) {Docsplit.extract_text('test/fixtures/corrosion.pdf', :pages => 'all', :output => OUTPUT, :language => "mock")}
assert(exception.message.match("mock.traineddata"))
end
def test_password_protected
assert_raises(ExtractionFailed) do
Docsplit.extract_text('test/fixtures/completely_encrypted.pdf')
end
end
def test_name_escaping_while_extracting_text
Docsplit.extract_text('test/fixtures/PDF file with spaces \'single\' and "double quotes".pdf', :pages => 'all', :output => OUTPUT)
assert Dir["#{OUTPUT}/*.txt"].length == 2
end
end
Add test for multiple language support
This test does not require any additional tesseract language backends to be
installed, but might fail if tesseract changes its error messages in the
future.
require 'test_helper'
require 'tmpdir'
class ExtractTextTest < Test::Unit::TestCase
def test_paged_extraction
Docsplit.extract_text('test/fixtures/obama_arts.pdf', :pages => 'all', :output => OUTPUT)
assert Dir["#{OUTPUT}/*.txt"].length == 2
assert File.read("#{OUTPUT}/obama_arts_1.txt").match("Paid for by Obama for America")
end
def test_page_only_extraction
Docsplit.extract_text('test/fixtures/obama_arts.pdf', :pages => 2..2, :output => OUTPUT)
assert Dir["#{OUTPUT}/*.txt"] == ["#{OUTPUT}/obama_arts_2.txt"]
end
def test_capitalized_pdf_extraction
Dir["#{OUTPUT}/*.txt"].each {|previous| FileUtils.rm(previous) }
Dir.mktmpdir do |dir|
FileUtils.cp('test/fixtures/obama_arts.pdf', "#{dir}/OBAMA_ARTS.PDF")
Docsplit.extract_text("#{dir}/OBAMA_ARTS.PDF", :pages => 2..2, :output => OUTPUT)
end
assert Dir["#{OUTPUT}/*.txt"] == ["#{OUTPUT}/OBAMA_ARTS_2.txt"]
end
def test_unicode_extraction
Docsplit.extract_text('test/fixtures/unicode.pdf', :pages => 'all', :output => OUTPUT)
assert Dir["#{OUTPUT}/*.txt"].length == 3
end
def test_ocr_extraction
Docsplit.extract_text('test/fixtures/corrosion.pdf', :pages => 'all', :output => OUTPUT)
assert Dir["#{OUTPUT}/*.txt"].length == 4
4.times do |i|
file = "corrosion_#{i + 1}.txt"
# File.open("test/fixtures/corrosion/#{file}", "w+") {|f| f.write(File.read("#{OUTPUT}/#{file}")) }
assert File.read("#{OUTPUT}/#{file}") == File.read("test/fixtures/corrosion/#{file}")
end
end
def test_ocr_extraction_in_mock_language
exception = assert_raise(Docsplit::ExtractionFailed) {Docsplit.extract_text('test/fixtures/corrosion.pdf', :pages => 'all', :output => OUTPUT, :language => "mock")}
assert exception.message.match("tessdata/mock"), "Expected problem with loading data for language 'mock'"
end
def test_password_protected
assert_raises(ExtractionFailed) do
Docsplit.extract_text('test/fixtures/completely_encrypted.pdf')
end
end
def test_name_escaping_while_extracting_text
Docsplit.extract_text('test/fixtures/PDF file with spaces \'single\' and "double quotes".pdf', :pages => 'all', :output => OUTPUT)
assert Dir["#{OUTPUT}/*.txt"].length == 2
end
end
|
Pod::Spec.new do |s|
s.name = 'PrediKit'
s.version = '2.0'
s.license = 'MIT'
s.summary = 'A Swift NSPredicate DSL for iOS & OS X inspired by SnapKit, lovingly written in Swift, and created by the awesome peeps at KrakenDev.io!'
s.homepage = 'https://github.com/KrakenDev/PrediKit'
s.authors = { 'Hector Matos' => 'hectormatos2011@gmail.com' }
s.social_media_url = 'http://twitter.com/allonsykraken'
s.source = { :git => 'https://github.com/KrakenDev/PrediKit.git', :tag => s.version }
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.10'
s.tvos.deployment_target = '9.0'
s.source_files = 'Sources/*.swift'
s.requires_arc = true
end
update podspec
Pod::Spec.new do |s|
s.name = 'PrediKit'
s.version = '2.0.1'
s.license = 'MIT'
s.summary = 'A Swift NSPredicate DSL for iOS & OS X inspired by SnapKit, lovingly written in Swift, and created by the awesome peeps at KrakenDev.io!'
s.homepage = 'https://github.com/KrakenDev/PrediKit'
s.authors = { 'Hector Matos' => 'hectormatos2011@gmail.com' }
s.social_media_url = 'http://twitter.com/allonsykraken'
s.source = { :git => 'https://github.com/KrakenDev/PrediKit.git', :tag => s.version }
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.10'
s.tvos.deployment_target = '9.0'
s.source_files = 'Sources/*.swift'
s.requires_arc = true
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'extraction/version'
Gem::Specification.new do |spec|
spec.name = "extraction"
spec.version = Extraction::VERSION
spec.authors = ["Guilherme Zabot"]
spec.email = ["zabot.gui@gmail.com"]
spec.summary = %q{TODO: Write a short summary, because Rubygems requires one.}
spec.description = %q{TODO: Write a longer description or delete this line.}
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against " \
"public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.14"
spec.add_development_dependency "rake", "~> 10.0"
end
gemspec atualizado
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'extraction/version'
Gem::Specification.new do |spec|
spec.name = "extraction"
spec.version = Extraction::VERSION
spec.authors = ["Guilherme Zabot"]
spec.email = ["zabot.gui@gmail.com"]
spec.summary = "Gem used to extract data from files in .txt format"
spec.description = "Gem created for DEV test"
spec.homepage = ""
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against " \
"public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.14"
spec.add_development_dependency "rake", "~> 10.0"
end
|
require 'test_helper'
require 'lotus/model/migrator'
describe 'PostgreSQL Database migrations' do
let(:adapter_prefix) { 'jdbc:' if Lotus::Utils.jruby? }
let(:db_prefix) { name.gsub(/[^\w]/, '_') }
let(:random_token) { SecureRandom.hex(4) }
before do
Lotus::Model.unload!
end
after do
Lotus::Model::Migrator.drop rescue nil
Lotus::Model.unload!
end
describe "PostgreSQL" do
before do
@database = "#{ db_prefix }_#{ random_token }"
@uri = uri = "#{ adapter_prefix }postgresql://127.0.0.1/#{ @database }?user=#{ POSTGRES_USER }"
Lotus::Model.configure do
adapter type: :sql, uri: uri
migrations __dir__ + '/../../fixtures/migrations'
end
end
after do
SQLite3::Database.new(@uri) { |db| db.close } if File.exist?(@database)
end
describe "create" do
before do
Lotus::Model::Migrator.create
end
it "creates the database" do
connection = Sequel.connect(@uri)
connection.tables.must_be :empty?
end
it 'raises error if database is busy' do
Sequel.connect(@uri).tables
exception = -> { Lotus::Model::Migrator.create }.must_raise Lotus::Model::MigrationError
exception.message.must_include 'createdb: database creation failed'
exception.message.must_include 'There is 1 other session using the database'
end
end
describe "drop" do
before do
Lotus::Model::Migrator.create
end
it "drops the database" do
Lotus::Model::Migrator.drop
-> { Sequel.connect(@uri).tables }.must_raise Sequel::DatabaseConnectionError
end
it "raises error if database doesn't exist" do
Lotus::Model::Migrator.drop # remove the first time
exception = -> { Lotus::Model::Migrator.drop }.must_raise Lotus::Model::MigrationError
exception.message.must_equal "Cannot find database: #{ @database }"
end
it 'raises error if database is busy' do
Sequel.connect(@uri).tables
exception = -> { Lotus::Model::Migrator.drop }.must_raise Lotus::Model::MigrationError
exception.message.must_include 'dropdb: database removal failed'
exception.message.must_include 'There is 1 other session using the database'
end
describe "when a command isn't available" do
before do
# We accomplish having a command not be available by setting PATH
# to an empty string, which means *no commands* are available.
@original_path = ENV['PATH']
ENV['PATH'] = ''
end
it "raises MigrationError on create" do
-> { Lotus::Model::Migrator.create }.must_raise Lotus::Model::MigrationError
end
after do
ENV['PATH'] = @original_path
end
end
end
describe "migrate" do
before do
Lotus::Model::Migrator.create
end
describe "when no migrations" do
before do
@migrations_root = migrations_root = Pathname.new(__dir__ + '/../../fixtures/empty_migrations')
Lotus::Model.configure do
migrations migrations_root
end
end
it "it doesn't alter database" do
Lotus::Model::Migrator.migrate
connection = Sequel.connect(@uri)
connection.tables.must_be :empty?
end
end
describe "when migrations are present" do
it "migrates the database" do
Lotus::Model::Migrator.migrate
connection = Sequel.connect(@uri)
connection.tables.wont_be :empty?
table = connection.schema(:books)
name, options = table[0] # id
name.must_equal :id
options.fetch(:allow_null).must_equal false
options.fetch(:default).must_equal "nextval('books_id_seq'::regclass)"
options.fetch(:type).must_equal :integer
options.fetch(:db_type).must_equal "integer"
options.fetch(:primary_key).must_equal true
options.fetch(:auto_increment).must_equal true
name, options = table[1] # title
name.must_equal :title
options.fetch(:allow_null).must_equal false
options.fetch(:default).must_equal nil
options.fetch(:type).must_equal :string
options.fetch(:db_type).must_equal "text"
options.fetch(:primary_key).must_equal false
name, options = table[2] # price (second migration)
name.must_equal :price
options.fetch(:allow_null).must_equal true
options.fetch(:default).must_equal "100"
options.fetch(:type).must_equal :integer
options.fetch(:db_type).must_equal "integer"
options.fetch(:primary_key).must_equal false
end
end
describe "when migrations are ran twice" do
before do
Lotus::Model::Migrator.migrate
end
it "doesn't alter the schema" do
Lotus::Model::Migrator.migrate
connection = Sequel.connect(@uri)
connection.tables.wont_be :empty?
connection.tables.must_equal [:schema_migrations, :books]
end
end
describe "migrate down" do
before do
Lotus::Model::Migrator.migrate
end
it "migrates the database" do
Lotus::Model::Migrator.migrate(version: '20150610133853')
connection = Sequel.connect(@uri)
connection.tables.wont_be :empty?
table = connection.schema(:books)
name, options = table[0] # id
name.must_equal :id
options.fetch(:allow_null).must_equal false
options.fetch(:default).must_equal "nextval('books_id_seq'::regclass)"
options.fetch(:type).must_equal :integer
options.fetch(:db_type).must_equal "integer"
options.fetch(:primary_key).must_equal true
options.fetch(:auto_increment).must_equal true
name, options = table[1] # title
name.must_equal :title
options.fetch(:allow_null).must_equal false
options.fetch(:default).must_equal nil
options.fetch(:type).must_equal :string
options.fetch(:db_type).must_equal "text"
options.fetch(:primary_key).must_equal false
name, options = table[2] # price (rolled back second migration)
name.must_be_nil
options.must_be_nil
end
end
end
describe "apply" do
before do
uri = @uri
@migrations_root = migrations_root = Pathname.new(__dir__ + '/../../../tmp')
@fixtures_root = fixtures_root = Pathname.new(__dir__ + '/../../fixtures/migrations')
migrations_root.mkpath
FileUtils.cp_r(fixtures_root, migrations_root)
Lotus::Model.unload!
Lotus::Model.configure do
adapter type: :sql, uri: uri
migrations migrations_root.join('migrations')
schema migrations_root.join('schema-postgres.sql')
end
Lotus::Model::Migrator.create
Lotus::Model::Migrator.apply
end
it "migrates to latest version" do
connection = Sequel.connect(@uri)
migration = connection[:schema_migrations].to_a[1]
migration.fetch(:filename).must_include("20150610141017")
end
it "dumps database schema.sql" do
schema = @migrations_root.join('schema-postgres.sql').read
schema.must_include <<-SQL
CREATE TABLE books (
id integer NOT NULL,
title text NOT NULL,
price integer DEFAULT 100
);
SQL
schema.must_include <<-SQL
CREATE SEQUENCE books_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
SQL
schema.must_include <<-SQL
ALTER SEQUENCE books_id_seq OWNED BY books.id;
SQL
schema.must_include <<-SQL
ALTER TABLE ONLY books ALTER COLUMN id SET DEFAULT nextval('books_id_seq'::regclass);
SQL
schema.must_include <<-SQL
ALTER TABLE ONLY books
ADD CONSTRAINT books_pkey PRIMARY KEY (id);
SQL
schema.must_include <<-SQL
CREATE TABLE schema_migrations (
filename text NOT NULL
);
SQL
schema.must_include <<-SQL
COPY schema_migrations (filename) FROM stdin;
20150610133853_create_books.rb
20150610141017_add_price_to_books.rb
SQL
schema.must_include <<-SQL
ALTER TABLE ONLY schema_migrations
ADD CONSTRAINT schema_migrations_pkey PRIMARY KEY (filename);
SQL
end
it "deletes all the migrations" do
@migrations_root.join('migrations').children.must_be :empty?
end
end
describe "prepare" do
before do
uri = @uri
@migrations_root = migrations_root = Pathname.new(__dir__ + '/../../../tmp')
@fixtures_root = fixtures_root = Pathname.new(__dir__ + '/../../fixtures/migrations')
migrations_root.mkpath
FileUtils.cp_r(fixtures_root, migrations_root)
Lotus::Model.unload!
Lotus::Model.configure do
adapter type: :sql, uri: uri
migrations migrations_root.join('migrations')
schema migrations_root.join('schema-postgres.sql')
end
end
it "creates database, loads schema and migrate" do
# Simulate already existing schema.sql, without existing database and pending migrations
connection = Sequel.connect(@uri)
FileUtils.cp 'test/fixtures/20150611165922_create_authors.rb',
@migrations_root.join('migrations/20150611165922_create_authors.rb')
Lotus::Model::Migrator.prepare
connection.tables.must_include(:schema_migrations)
connection.tables.must_include(:books)
connection.tables.must_include(:authors)
FileUtils.rm_f @migrations_root.join('migrations/20150611165922_create_authors.rb')
end
it "works even if schema doesn't exist" do
# Simulate no database, no schema and pending migrations
@migrations_root.join('migrations/20150611165922_create_authors.rb').delete rescue nil
@migrations_root.join('schema-postgres.sql').delete rescue nil
Lotus::Model::Migrator.prepare
connection = Sequel.connect(@uri)
connection.tables.must_equal [:schema_migrations, :books]
end
it "drops the database and recreate it" do
Lotus::Model::Migrator.create
Lotus::Model::Migrator.prepare
connection = Sequel.connect(@uri)
connection.tables.must_include(:schema_migrations)
connection.tables.must_include(:books)
end
end
describe "version" do
before do
Lotus::Model::Migrator.create
end
describe "when no migrations were ran" do
it "returns nil" do
version = Lotus::Model::Migrator.version
version.must_be_nil
end
end
describe "with migrations" do
before do
Lotus::Model::Migrator.migrate
end
it "returns current database version" do
version = Lotus::Model::Migrator.version
version.must_equal "20150610141017"
end
end
end
end
end
Cleanup for #265
require 'test_helper'
require 'lotus/model/migrator'
describe 'PostgreSQL Database migrations' do
let(:adapter_prefix) { 'jdbc:' if Lotus::Utils.jruby? }
let(:db_prefix) { name.gsub(/[^\w]/, '_') }
let(:random_token) { SecureRandom.hex(4) }
before do
Lotus::Model.unload!
end
after do
Lotus::Model::Migrator.drop rescue nil
Lotus::Model.unload!
end
describe "PostgreSQL" do
before do
@database = "#{ db_prefix }_#{ random_token }"
@uri = uri = "#{ adapter_prefix }postgresql://127.0.0.1/#{ @database }?user=#{ POSTGRES_USER }"
Lotus::Model.configure do
adapter type: :sql, uri: uri
migrations __dir__ + '/../../fixtures/migrations'
end
end
after do
SQLite3::Database.new(@uri) { |db| db.close } if File.exist?(@database)
end
describe "create" do
before do
Lotus::Model::Migrator.create
end
it "creates the database" do
connection = Sequel.connect(@uri)
connection.tables.must_be :empty?
end
it 'raises error if database is busy' do
Sequel.connect(@uri).tables
exception = -> { Lotus::Model::Migrator.create }.must_raise Lotus::Model::MigrationError
exception.message.must_include 'createdb: database creation failed'
exception.message.must_include 'There is 1 other session using the database'
end
end
describe "drop" do
before do
Lotus::Model::Migrator.create
end
it "drops the database" do
Lotus::Model::Migrator.drop
-> { Sequel.connect(@uri).tables }.must_raise Sequel::DatabaseConnectionError
end
it "raises error if database doesn't exist" do
Lotus::Model::Migrator.drop # remove the first time
exception = -> { Lotus::Model::Migrator.drop }.must_raise Lotus::Model::MigrationError
exception.message.must_equal "Cannot find database: #{ @database }"
end
it 'raises error if database is busy' do
Sequel.connect(@uri).tables
exception = -> { Lotus::Model::Migrator.drop }.must_raise Lotus::Model::MigrationError
exception.message.must_include 'dropdb: database removal failed'
exception.message.must_include 'There is 1 other session using the database'
end
describe "when a command isn't available" do
before do
# We accomplish having a command not be available by setting PATH
# to an empty string, which means *no commands* are available.
@original_path = ENV['PATH']
ENV['PATH'] = ''
end
after do
ENV['PATH'] = @original_path
end
it "raises MigrationError on create" do
exception = -> { Lotus::Model::Migrator.create }.must_raise Lotus::Model::MigrationError
exception.message.must_equal "No such file or directory - createdb"
end
end
end
describe "migrate" do
before do
Lotus::Model::Migrator.create
end
describe "when no migrations" do
before do
@migrations_root = migrations_root = Pathname.new(__dir__ + '/../../fixtures/empty_migrations')
Lotus::Model.configure do
migrations migrations_root
end
end
it "it doesn't alter database" do
Lotus::Model::Migrator.migrate
connection = Sequel.connect(@uri)
connection.tables.must_be :empty?
end
end
describe "when migrations are present" do
it "migrates the database" do
Lotus::Model::Migrator.migrate
connection = Sequel.connect(@uri)
connection.tables.wont_be :empty?
table = connection.schema(:books)
name, options = table[0] # id
name.must_equal :id
options.fetch(:allow_null).must_equal false
options.fetch(:default).must_equal "nextval('books_id_seq'::regclass)"
options.fetch(:type).must_equal :integer
options.fetch(:db_type).must_equal "integer"
options.fetch(:primary_key).must_equal true
options.fetch(:auto_increment).must_equal true
name, options = table[1] # title
name.must_equal :title
options.fetch(:allow_null).must_equal false
options.fetch(:default).must_equal nil
options.fetch(:type).must_equal :string
options.fetch(:db_type).must_equal "text"
options.fetch(:primary_key).must_equal false
name, options = table[2] # price (second migration)
name.must_equal :price
options.fetch(:allow_null).must_equal true
options.fetch(:default).must_equal "100"
options.fetch(:type).must_equal :integer
options.fetch(:db_type).must_equal "integer"
options.fetch(:primary_key).must_equal false
end
end
describe "when migrations are ran twice" do
before do
Lotus::Model::Migrator.migrate
end
it "doesn't alter the schema" do
Lotus::Model::Migrator.migrate
connection = Sequel.connect(@uri)
connection.tables.wont_be :empty?
connection.tables.must_equal [:schema_migrations, :books]
end
end
describe "migrate down" do
before do
Lotus::Model::Migrator.migrate
end
it "migrates the database" do
Lotus::Model::Migrator.migrate(version: '20150610133853')
connection = Sequel.connect(@uri)
connection.tables.wont_be :empty?
table = connection.schema(:books)
name, options = table[0] # id
name.must_equal :id
options.fetch(:allow_null).must_equal false
options.fetch(:default).must_equal "nextval('books_id_seq'::regclass)"
options.fetch(:type).must_equal :integer
options.fetch(:db_type).must_equal "integer"
options.fetch(:primary_key).must_equal true
options.fetch(:auto_increment).must_equal true
name, options = table[1] # title
name.must_equal :title
options.fetch(:allow_null).must_equal false
options.fetch(:default).must_equal nil
options.fetch(:type).must_equal :string
options.fetch(:db_type).must_equal "text"
options.fetch(:primary_key).must_equal false
name, options = table[2] # price (rolled back second migration)
name.must_be_nil
options.must_be_nil
end
end
end
describe "apply" do
before do
uri = @uri
@migrations_root = migrations_root = Pathname.new(__dir__ + '/../../../tmp')
@fixtures_root = fixtures_root = Pathname.new(__dir__ + '/../../fixtures/migrations')
migrations_root.mkpath
FileUtils.cp_r(fixtures_root, migrations_root)
Lotus::Model.unload!
Lotus::Model.configure do
adapter type: :sql, uri: uri
migrations migrations_root.join('migrations')
schema migrations_root.join('schema-postgres.sql')
end
Lotus::Model::Migrator.create
Lotus::Model::Migrator.apply
end
it "migrates to latest version" do
connection = Sequel.connect(@uri)
migration = connection[:schema_migrations].to_a[1]
migration.fetch(:filename).must_include("20150610141017")
end
it "dumps database schema.sql" do
schema = @migrations_root.join('schema-postgres.sql').read
schema.must_include <<-SQL
CREATE TABLE books (
id integer NOT NULL,
title text NOT NULL,
price integer DEFAULT 100
);
SQL
schema.must_include <<-SQL
CREATE SEQUENCE books_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
SQL
schema.must_include <<-SQL
ALTER SEQUENCE books_id_seq OWNED BY books.id;
SQL
schema.must_include <<-SQL
ALTER TABLE ONLY books ALTER COLUMN id SET DEFAULT nextval('books_id_seq'::regclass);
SQL
schema.must_include <<-SQL
ALTER TABLE ONLY books
ADD CONSTRAINT books_pkey PRIMARY KEY (id);
SQL
schema.must_include <<-SQL
CREATE TABLE schema_migrations (
filename text NOT NULL
);
SQL
schema.must_include <<-SQL
COPY schema_migrations (filename) FROM stdin;
20150610133853_create_books.rb
20150610141017_add_price_to_books.rb
SQL
schema.must_include <<-SQL
ALTER TABLE ONLY schema_migrations
ADD CONSTRAINT schema_migrations_pkey PRIMARY KEY (filename);
SQL
end
it "deletes all the migrations" do
@migrations_root.join('migrations').children.must_be :empty?
end
end
describe "prepare" do
before do
uri = @uri
@migrations_root = migrations_root = Pathname.new(__dir__ + '/../../../tmp')
@fixtures_root = fixtures_root = Pathname.new(__dir__ + '/../../fixtures/migrations')
migrations_root.mkpath
FileUtils.cp_r(fixtures_root, migrations_root)
Lotus::Model.unload!
Lotus::Model.configure do
adapter type: :sql, uri: uri
migrations migrations_root.join('migrations')
schema migrations_root.join('schema-postgres.sql')
end
end
it "creates database, loads schema and migrate" do
# Simulate already existing schema.sql, without existing database and pending migrations
connection = Sequel.connect(@uri)
FileUtils.cp 'test/fixtures/20150611165922_create_authors.rb',
@migrations_root.join('migrations/20150611165922_create_authors.rb')
Lotus::Model::Migrator.prepare
connection.tables.must_include(:schema_migrations)
connection.tables.must_include(:books)
connection.tables.must_include(:authors)
FileUtils.rm_f @migrations_root.join('migrations/20150611165922_create_authors.rb')
end
it "works even if schema doesn't exist" do
# Simulate no database, no schema and pending migrations
@migrations_root.join('migrations/20150611165922_create_authors.rb').delete rescue nil
@migrations_root.join('schema-postgres.sql').delete rescue nil
Lotus::Model::Migrator.prepare
connection = Sequel.connect(@uri)
connection.tables.must_equal [:schema_migrations, :books]
end
it "drops the database and recreate it" do
Lotus::Model::Migrator.create
Lotus::Model::Migrator.prepare
connection = Sequel.connect(@uri)
connection.tables.must_include(:schema_migrations)
connection.tables.must_include(:books)
end
end
describe "version" do
before do
Lotus::Model::Migrator.create
end
describe "when no migrations were ran" do
it "returns nil" do
version = Lotus::Model::Migrator.version
version.must_be_nil
end
end
describe "with migrations" do
before do
Lotus::Model::Migrator.migrate
end
it "returns current database version" do
version = Lotus::Model::Migrator.version
version.must_equal "20150610141017"
end
end
end
end
end
|
# frozen_string_literal: true
require_relative "helper"
class TestRemoteServerControlCommands < Minitest::Test
include Helper::Client
def test_info
keys = [
"redis_version",
"uptime_in_seconds",
"uptime_in_days",
"connected_clients",
"used_memory",
"total_connections_received",
"total_commands_processed",
]
info = r.info
keys.each do |k|
msg = "expected #info to include #{k}"
assert info.keys.include?(k), msg
end
end
def test_info_commandstats
target_version "2.5.7" do
r.config(:resetstat)
r.ping
result = r.info(:commandstats)
assert_equal "1", result["ping"]["calls"]
end
end
def test_monitor_redis_lt_2_5_0
return unless version < "2.5.0"
log = []
wire = Wire.new do
Redis.new(OPTIONS).monitor do |line|
log << line
break if log.size == 3
end
end
Wire.pass while log.empty? # Faster than sleep
r.set "foo", "s1"
wire.join
assert log[-1][%q{(db 15) "set" "foo" "s1"}]
end
def test_monitor_redis_gte_2_5_0
return unless version >= "2.5.0"
log = []
wire = Wire.new do
Redis.new(OPTIONS).monitor do |line|
log << line
break if line =~ /set/
end
end
Wire.pass while log.empty? # Faster than sleep
r.set "foo", "s1"
wire.join
assert log[-1] =~ /\b15\b.* "set" "foo" "s1"/
end
def test_monitor_returns_value_for_break
result = r.monitor do |line|
break line
end
assert_equal "OK", result
end
def test_echo
assert_equal "foo bar baz\n", r.echo("foo bar baz\n")
end
def test_debug
r.set "foo", "s1"
assert r.debug(:object, "foo").kind_of?(String)
end
def test_object
r.lpush "list", "value"
assert_equal 1, r.object(:refcount, "list")
encoding = r.object(:encoding, "list")
assert "ziplist" == encoding || "quicklist" == encoding, "Wrong encoding for list"
assert r.object(:idletime, "list").kind_of?(Integer)
end
def test_sync
redis_mock(:sync => lambda { "+OK" }) do |redis|
assert_equal "OK", redis.sync
end
end
def test_slowlog
r.slowlog(:reset)
result = r.slowlog(:len)
assert_equal 0, result
end
def test_client
assert_equal r.instance_variable_get(:@client), r._client
end
def test_client_list
return if version < "2.4.0"
keys = [
"addr",
"fd",
"name",
"age",
"idle",
"flags",
"db",
"sub",
"psub",
"multi",
"qbuf",
"qbuf-free",
"obl",
"oll",
"omem",
"events",
"cmd"
]
clients = r.client(:list)
clients.each do |client|
keys.each do |k|
msg = "expected #client(:list) to include #{k}"
assert client.keys.include?(k), msg
end
end
end
def test_client_kill
return if version < "2.6.9"
r.client(:setname, 'redis-rb')
clients = r.client(:list)
i = clients.index {|client| client['name'] == 'redis-rb'}
assert_equal "OK", r.client(:kill, clients[i]["addr"])
clients = r.client(:list)
i = clients.index {|client| client['name'] == 'redis-rb'}
assert_nil i
end
def test_client_getname_and_setname
return if version < "2.6.9"
assert_nil r.client(:getname)
r.client(:setname, 'redis-rb')
name = r.client(:getname)
assert_equal 'redis-rb', name
end
end
Since Sentinel keeps monitoring by ping, change commandstats key for test.
# frozen_string_literal: true
require_relative "helper"
class TestRemoteServerControlCommands < Minitest::Test
include Helper::Client
def test_info
keys = [
"redis_version",
"uptime_in_seconds",
"uptime_in_days",
"connected_clients",
"used_memory",
"total_connections_received",
"total_commands_processed",
]
info = r.info
keys.each do |k|
msg = "expected #info to include #{k}"
assert info.keys.include?(k), msg
end
end
def test_info_commandstats
target_version "2.5.7" do
r.config(:resetstat)
r.config(:get, :port)
result = r.info(:commandstats)
assert_equal '2', result['config']['calls']
end
end
def test_monitor_redis_lt_2_5_0
return unless version < "2.5.0"
log = []
wire = Wire.new do
Redis.new(OPTIONS).monitor do |line|
log << line
break if log.size == 3
end
end
Wire.pass while log.empty? # Faster than sleep
r.set "foo", "s1"
wire.join
assert log[-1][%q{(db 15) "set" "foo" "s1"}]
end
def test_monitor_redis_gte_2_5_0
return unless version >= "2.5.0"
log = []
wire = Wire.new do
Redis.new(OPTIONS).monitor do |line|
log << line
break if line =~ /set/
end
end
Wire.pass while log.empty? # Faster than sleep
r.set "foo", "s1"
wire.join
assert log[-1] =~ /\b15\b.* "set" "foo" "s1"/
end
def test_monitor_returns_value_for_break
result = r.monitor do |line|
break line
end
assert_equal "OK", result
end
def test_echo
assert_equal "foo bar baz\n", r.echo("foo bar baz\n")
end
def test_debug
r.set "foo", "s1"
assert r.debug(:object, "foo").kind_of?(String)
end
def test_object
r.lpush "list", "value"
assert_equal 1, r.object(:refcount, "list")
encoding = r.object(:encoding, "list")
assert "ziplist" == encoding || "quicklist" == encoding, "Wrong encoding for list"
assert r.object(:idletime, "list").kind_of?(Integer)
end
def test_sync
redis_mock(:sync => lambda { "+OK" }) do |redis|
assert_equal "OK", redis.sync
end
end
def test_slowlog
r.slowlog(:reset)
result = r.slowlog(:len)
assert_equal 0, result
end
def test_client
assert_equal r.instance_variable_get(:@client), r._client
end
def test_client_list
return if version < "2.4.0"
keys = [
"addr",
"fd",
"name",
"age",
"idle",
"flags",
"db",
"sub",
"psub",
"multi",
"qbuf",
"qbuf-free",
"obl",
"oll",
"omem",
"events",
"cmd"
]
clients = r.client(:list)
clients.each do |client|
keys.each do |k|
msg = "expected #client(:list) to include #{k}"
assert client.keys.include?(k), msg
end
end
end
def test_client_kill
return if version < "2.6.9"
r.client(:setname, 'redis-rb')
clients = r.client(:list)
i = clients.index {|client| client['name'] == 'redis-rb'}
assert_equal "OK", r.client(:kill, clients[i]["addr"])
clients = r.client(:list)
i = clients.index {|client| client['name'] == 'redis-rb'}
assert_nil i
end
def test_client_getname_and_setname
return if version < "2.6.9"
assert_nil r.client(:getname)
r.client(:setname, 'redis-rb')
name = r.client(:getname)
assert_equal 'redis-rb', name
end
end
|
require 'test/unit'
require File.dirname(__FILE__) + '/../test_helper'
class RemoteSecurePayTest < Test::Unit::TestCase
include ActiveMerchant::Billing
AMOUNT = 100
def setup
@login = 'LOGIN'
@password = 'PASSWORD'
@gateway = SecurePayGateway.new(
:login => @login,
:password => @password
)
@creditcard = credit_card('4111111111111111',
:month => 7,
:year => 2007
)
@options = { :order_id => generate_order_id,
:description => 'Store purchase',
:billing_address => {
:address1 => '1234 My Street',
:address2 => 'Apartment 204',
:city => 'Beverly Hills',
:state => 'CA',
:country => 'US',
:zip => '90210'
}
}
end
def test_successful_purchase
assert response = @gateway.purchase(AMOUNT, @creditcard, @options)
assert response.success?
assert response.test?
assert_equal 'This transaction has been approved', response.message
assert response.authorization
end
end
remove require of test/unit
git-svn-id: 15afb6ebb5ffcaa0dbaaa80925839866918ea29e@370 6513ea26-6c20-0410-8a68-89cd7235086d
require File.dirname(__FILE__) + '/../test_helper'
class RemoteSecurePayTest < Test::Unit::TestCase
include ActiveMerchant::Billing
AMOUNT = 100
def setup
@login = 'LOGIN'
@password = 'PASSWORD'
@gateway = SecurePayGateway.new(
:login => @login,
:password => @password
)
@creditcard = credit_card('4111111111111111',
:month => 7,
:year => 2007
)
@options = { :order_id => generate_order_id,
:description => 'Store purchase',
:billing_address => {
:address1 => '1234 My Street',
:address2 => 'Apartment 204',
:city => 'Beverly Hills',
:state => 'CA',
:country => 'US',
:zip => '90210'
}
}
end
def test_successful_purchase
assert response = @gateway.purchase(AMOUNT, @creditcard, @options)
assert response.success?
assert response.test?
assert_equal 'This transaction has been approved', response.message
assert response.authorization
end
end
|
encode script
#!/usr/bin/env ruby
class Encode
def initialize()
end
end
musik_dir = "/home/aetu/musik";
encoded_dir = "/home/aetu/musik/encoded";
files = Dir.glob(musik_dir + "/*");
hash = {}
begin
File.open(encoded_dir + "/list") { | fd |
fd.each { |l|
hash[l.strip] = true;
}
}
rescue
end
new_files = [];
files.each { | f |
name = f.scan(/.*\/(.*)/);
name = name[0][0];
if(hash[name] == nil)
hash[name] = true;
new_files.push(f);
end
}
new_files.each { | f |
name = f.scan(/.*\/(.*)/);
name = name[0][0];
val = system("mpg123 --stereo -r 44100 -s \"#{f}\" | lame - \"#{encoded_dir + "/" + name}\" -r" );
puts val.inspect;
}
File.open(encoded_dir + "/list", "w") { | fd |
hash.each { | k, v |
fd.write(k + "\n");
}
}
|
$: << File.join(File.dirname(__FILE__), 'ext')
require 'test/unit'
class MultipleExtensionTest < Test::Unit::TestCase
def test_multiple_extensions_with_inheritance
require 't1/t1'
require 't2/t2'
foo = Foo.new
assert_equal 42, foo.foo
end
end
Changed class name.
$: << File.join(File.dirname(__FILE__), 'ext')
require 'test/unit'
class MultipleExtensionsSameClassTest < Test::Unit::TestCase
def test_multiple_extensions_same_class
require 't1/t1'
require 't2/t2'
foo = Foo.new
assert_equal 42, foo.foo
end
end
|
#
# Be sure to run `pod lib lint TutorialScrollViewController.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "TutorialScrollViewController"
s.version = "0.1.0"
s.summary = "A subclass of UIScrollViewController, which helps set up a working scrolling start-up tutorial view quickly"
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
Whenever we make an app, it is really likely for us to include several tutorial views when app is first launched. Normally, these view are contained in a scrollViewController with paging enable. I believe most of you know how to achieve this from scratch, but it takes time. So this framework is aimed to minimize the work you need to do to set up a sound and working tutorial viewController
DESC
s.homepage = "https://github.com/lichenglu/TutorialScrollViewController"
# s.screenshots = "www.example.com/screenshots_1", "www.example.com/screenshots_2"
s.license = 'MIT'
s.author = { "Chenglu Li" => "kabelee92@gmail.com" }
s.source = { :git => "https://github.com/<GITHUB_USERNAME>/TutorialScrollViewController.git", :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.platform = :ios, '8.0'
s.requires_arc = true
s.source_files = 'Pod/Classes/**/*'
s.resource_bundles = {
'TutorialScrollViewController' => ['Pod/Assets/*.png']
}
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
push pod to cocoa pod
#
# Be sure to run `pod lib lint TutorialScrollViewController.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "TutorialScrollViewController"
s.version = "0.1.0"
s.summary = "A subclass of UIScrollViewController, which helps set up a working scrolling start-up tutorial view quickly"
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
Whenever we make an app, it is really likely for us to include several tutorial views when app is first launched. Normally, these view are contained in a scrollViewController with paging enable. I believe most of you know how to achieve this from scratch, but it takes time. So this framework is aimed to minimize the work you need to do to set up a sound and working tutorial viewController
DESC
s.homepage = "https://github.com/lichenglu/TutorialScrollViewController"
# s.screenshots = "www.example.com/screenshots_1", "www.example.com/screenshots_2"
s.license = 'MIT'
s.author = { "Chenglu Li" => "kabelee92@gmail.com" }
s.source = { :git => "https://github.com/lichenglu/TutorialScrollViewController.git", :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.platform = :ios, '8.0'
s.requires_arc = true
s.source_files = 'Pod/Classes/**/*'
s.resource_bundles = {
'TutorialScrollViewController' => ['Pod/Assets/*.png']
}
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
|
NAME="Node.Net"
require 'raykit'
CLEAN.include('**/obj')
task :default do
PROJECT.info
target='tmp.txt'
CLEAN.exclude(target)
if(PROJECT.last_modified_filename != target)
PROJECT.run(["dotnet build --configuration Release",
"dotnet test #{PROJECT.name}.Test/#{PROJECT.name}.Test.csproj -c Release -v normal",
"dotnet pack #{PROJECT.name}.sln -c Release"])
#package="#{PROJECT.name}/bin/Release/#{PROJECT.name}.#{PROJECT.version}.nupkg"
#puts "publishing" + Rainbow(package).yellow.bright + " to " + Rainbow("nuget.org").yellow.bright
#NUGET_KEY=ENV['NUGET_KEY']
#puts `nuget push #{package} -ApiKey #{NUGET_KEY} -Source https://api.nuget.org/v3/index.json`
PROJECT.commit.tag.push.pull
end
PROJECT.summary
end
task :setup do
Raykit::DotNet::initialize_csharp_lib PROJECT.name
end
'update'
NAME="Node.Net"
require 'raykit'
CLEAN.include('**/obj')
task :default do
PROJECT.info
target='tmp.txt'
CLEAN.exclude(target)
if(PROJECT.last_modified_filename != target)
PROJECT.run(["dotnet build --configuration Release",
"dotnet test #{PROJECT.name}.Test/#{PROJECT.name}.Test.csproj -c Release -v normal",
"dotnet pack #{PROJECT.name}.sln -c Release"])
package="#{PROJECT.name}/bin/Release/#{PROJECT.name}.#{PROJECT.version}.nupkg"
puts "publishing" + Rainbow(package).yellow.bright + " to " + Rainbow("nuget.org").yellow.bright
NUGET_KEY=ENV['NUGET_KEY']
puts `nuget push #{package} -ApiKey #{NUGET_KEY} -Source https://api.nuget.org/v3/index.json`
PROJECT.commit.tag.push.pull
end
PROJECT.summary
end
task :setup do
Raykit::DotNet::initialize_csharp_lib PROJECT.name
end
|
require 'rake/clean'
require 'rspec/core/rake_task'
CLEAN.include 'doc'
CLEAN.include 'coverage'
CLEAN.include '*.gem'
CLEAN.include '.yardoc'
desc 'Run specs.'
task :default => :spec
desc 'Run specs.'
RSpec::Core::RakeTask.new :spec do |t|
t.ruby_opts = ['-w']
end
desc 'Generate SimpleCov spec coverage.'
RSpec::Core::RakeTask.new :coverage do |t|
t.rspec_opts = ['--require simplecov_helper']
end
desc 'Build the gem.'
task :build do
sh "gem build #{name}.gemspec"
end
desc 'Install the gem'
task :install do
sh "gem install ./#{name}-#{version}.gem"
end
desc 'Uninstall the gem'
task :uninstall do
sh "gem uninstall #{name}"
end
begin
gem 'flog'
desc 'Flog the code'
task :flog, [:flags] do |t, args|
flags = args[:flags] ? "-#{args[:flags]}" : ''
files = FileList['lib/**/*.rb'].join(' ')
sh "flog #{flags} #{files}"
end
rescue Gem::LoadError
end
def name
@name ||= Dir['*.gemspec'].first.split('.').first
end
def version
text = File.read("lib/#{name}/version.rb")
text = text[/^\s*VERSION\s*=\s*.*/]
@version ||= text.match(/.*VERSION\s*=\s*['"](.*)['"]/)[1]
end
Keeping Rake task descriptions consistent with punctuation at the end.
require 'rake/clean'
require 'rspec/core/rake_task'
CLEAN.include 'doc'
CLEAN.include 'coverage'
CLEAN.include '*.gem'
CLEAN.include '.yardoc'
desc 'Run specs.'
task :default => :spec
desc 'Run specs.'
RSpec::Core::RakeTask.new :spec do |t|
t.ruby_opts = ['-w']
end
desc 'Generate SimpleCov spec coverage.'
RSpec::Core::RakeTask.new :coverage do |t|
t.rspec_opts = ['--require simplecov_helper']
end
desc 'Build the gem.'
task :build do
sh "gem build #{name}.gemspec"
end
desc 'Install the gem.'
task :install do
sh "gem install ./#{name}-#{version}.gem"
end
desc 'Uninstall the gem.'
task :uninstall do
sh "gem uninstall #{name}"
end
begin
gem 'flog'
desc 'Flog the code.'
task :flog, [:flags] do |t, args|
flags = args[:flags] ? "-#{args[:flags]}" : ''
files = FileList['lib/**/*.rb'].join(' ')
sh "flog #{flags} #{files}"
end
rescue Gem::LoadError
end
def name
@name ||= Dir['*.gemspec'].first.split('.').first
end
def version
text = File.read("lib/#{name}/version.rb")
text = text[/^\s*VERSION\s*=\s*.*/]
@version ||= text.match(/.*VERSION\s*=\s*['"](.*)['"]/)[1]
end
|
require 'rubygems/package_task'
require 'rake/testtask'
require 'rdoc/task'
gemspec = Gem::Specification.new do |s|
s.name = "gem-patch"
s.version = "0.1.3"
s.platform = Gem::Platform::RUBY
s.summary = "RubyGems plugin for patching gems."
s.description = <<-EOF
`gem-patch` is a RubyGems plugin that helps to patch gems without manually opening and rebuilding them.
It opens a given .gem file, extracts it, patches it with system `patch` command,
clones its spec, updates the file list and builds the patched gem.
EOF
s.homepage = "http://github.com/strzibny/gem-patch"
s.licenses = ["MIT"]
s.author = "Josef Stribny"
s.email = "jstribny@redhat.com"
s.required_ruby_version = ">= 1.8.7"
s.required_rubygems_version = ">= 1.8.0"
s.files = FileList["README.md", "LICENCE", "rakefile.rb",
"lib/**/*.rb", "test/**/test*.rb"]
end
Gem::PackageTask.new gemspec do |pkg|
end
Rake::RDocTask.new do |rd|
rd.main = "README.md"
rd.rdoc_files.include("README.md", "lib/**/*.rb")
end
Rake::TestTask.new('test') do |t|
t.libs << 'test'
t.pattern = 'test/**/test*.rb'
t.verbose = true
end
task :default => [:test]
Bump version to 0.1.4
require 'rubygems/package_task'
require 'rake/testtask'
require 'rdoc/task'
gemspec = Gem::Specification.new do |s|
s.name = "gem-patch"
s.version = "0.1.4"
s.platform = Gem::Platform::RUBY
s.summary = "RubyGems plugin for patching gems."
s.description = <<-EOF
`gem-patch` is a RubyGems plugin that helps to patch gems without manually opening and rebuilding them.
It opens a given .gem file, extracts it, patches it with system `patch` command,
clones its spec, updates the file list and builds the patched gem.
EOF
s.homepage = "http://github.com/strzibny/gem-patch"
s.licenses = ["MIT"]
s.author = "Josef Stribny"
s.email = "jstribny@redhat.com"
s.required_ruby_version = ">= 1.8.7"
s.required_rubygems_version = ">= 1.8.0"
s.files = FileList["README.md", "LICENCE", "rakefile.rb",
"lib/**/*.rb", "test/**/test*.rb"]
end
Gem::PackageTask.new gemspec do |pkg|
end
Rake::RDocTask.new do |rd|
rd.main = "README.md"
rd.rdoc_files.include("README.md", "lib/**/*.rb")
end
Rake::TestTask.new('test') do |t|
t.libs << 'test'
t.pattern = 'test/**/test*.rb'
t.verbose = true
end
task :default => [:test]
|
total_coverage_file = 'coverage.txt' # This path is specified by codecov.
task :build do
sh 'go build -o bin/tisp src/cmd/tisp/main.go'
end
task :fast_unit_test do
sh 'go test ./...'
end
task :unit_test do
coverage_file = "/tmp/tisp-unit-test-#{Process.pid}.coverage"
`go list ./...`.split.each do |package|
sh %W[go test
-covermode atomic
-coverprofile #{coverage_file}
-race
#{package}].join ' '
verbose false do
if File.exist? coverage_file
sh "cat #{coverage_file} >> #{total_coverage_file}"
rm coverage_file
end
end
end
end
task :test_build do
sh %w[go test -c -cover
-coverpkg $(go list ./... | perl -0777 -pe 's/\\n(.)/,\\1/g')
./src/cmd/tisp].join ' '
mkdir_p 'bin'
mv 'tisp.test', 'bin'
File.write 'bin/tisp', [
'#!/bin/sh',
'file=/tmp/tisp-test-$$.out',
'coverage_file=/tmp/tisp-test-$$.coverage',
%(ARGS="$@" #{File.absolute_path 'bin/tisp.test'} )\
+ '-test.coverprofile $coverage_file > $file &&',
"cat $file | perl -0777 -pe 's/(.*)PASS.*/\\1/s' &&",
'rm $file &&',
"cat $coverage_file >> #{total_coverage_file} &&",
'rm $coverage_file'
].join("\n") + "\n"
chmod 0o755, 'bin/tisp'
end
task command_test: :test_build do
tmp_dir = 'tmp'
mkdir_p tmp_dir
Dir.glob('test/*.tisp').each do |file|
shell_script = file.ext '.sh'
if File.exist? shell_script
sh "sh #{shell_script}"
next
end
in_file = file.ext '.in'
expected_out_file = file.ext '.out'
actual_out_file = File.join(tmp_dir, File.basename(expected_out_file))
sh %W[
bin/tisp #{file}
#{File.exist?(in_file) ? "< #{in_file}" : ''}
#{File.exist?(expected_out_file) ? "> #{actual_out_file}" : ''}
].join ' '
sh "diff #{expected_out_file} #{actual_out_file}" \
if File.exist? expected_out_file
end
Dir.glob 'test/xfail/*.tisp' do |file|
sh "! bin/tisp #{file} > /dev/null 2>&1"
end
end
task test: %i[unit_test command_test]
task :lint do
verbose false do
[
'go vet',
'golint',
'gosimple',
'unused',
'staticcheck',
'interfacer'
].each do |command|
puts "# #{command}"
sh "#{command} ./..."
end
end
end
task :format do
sh 'go fix ./...'
sh 'go fmt ./...'
Dir.glob '**/*.go' do |file|
sh "goimports -w #{file}"
end
sh 'rubocop -a'
end
task :docker do
tag = 'tisplang/tisp-build'
sh "sudo docker build --no-cache -t #{tag} etc/docker"
sh "sudo docker push #{tag}"
end
task :install_deps do
sh %w[
go get -u
github.com/golang/lint/golint
github.com/kr/pretty
github.com/mvdan/interfacer/...
golang.org/x/tools/cmd/goimports
honnef.co/go/tools/...
].join ' '
sh 'go get -d -t ./...'
end
task install: %i[install_deps test build] do
sh 'go get ./...'
end
task :images do
Dir.glob 'img/*.svg' do |file|
sh "inkscape --export-area-drawing --export-png #{file.ext 'png'} #{file}"
end
end
task doc: :images do
sh 'convert -resize 16x16 img/icon.png doc/theme/img/favicon.ico'
cd 'doc'
sh 'mkdocs gh-deploy -m "[skip ci] on Wercker"'
end
task default: %i[test build]
task :clean do
sh 'git clean -dfx'
end
Enable race condition detector and atomic coverage in command test
total_coverage_file = 'coverage.txt' # This path is specified by codecov.
task :build do
sh 'go build -o bin/tisp src/cmd/tisp/main.go'
end
task :fast_unit_test do
sh 'go test ./...'
end
task :unit_test do
coverage_file = "/tmp/tisp-unit-test-#{Process.pid}.coverage"
`go list ./...`.split.each do |package|
sh %W[go test
-covermode atomic
-coverprofile #{coverage_file}
-race
#{package}].join ' '
verbose false do
if File.exist? coverage_file
sh "cat #{coverage_file} >> #{total_coverage_file}"
rm coverage_file
end
end
end
end
task :test_build do
sh %w[go test -race -covermode atomic -c -cover
-coverpkg $(go list ./... | perl -0777 -pe 's/\\n(.)/,\\1/g')
./src/cmd/tisp].join ' '
mkdir_p 'bin'
mv 'tisp.test', 'bin'
File.write 'bin/tisp', [
'#!/bin/sh',
'file=/tmp/tisp-test-$$.out',
'coverage_file=/tmp/tisp-test-$$.coverage',
%(ARGS="$@" #{File.absolute_path 'bin/tisp.test'} )\
+ '-test.coverprofile $coverage_file > $file &&',
"cat $file | perl -0777 -pe 's/(.*)PASS.*/\\1/s' &&",
'rm $file &&',
"cat $coverage_file >> #{total_coverage_file} &&",
'rm $coverage_file'
].join("\n") + "\n"
chmod 0o755, 'bin/tisp'
end
task command_test: :test_build do
tmp_dir = 'tmp'
mkdir_p tmp_dir
Dir.glob('test/*.tisp').each do |file|
shell_script = file.ext '.sh'
if File.exist? shell_script
sh "sh #{shell_script}"
next
end
in_file = file.ext '.in'
expected_out_file = file.ext '.out'
actual_out_file = File.join(tmp_dir, File.basename(expected_out_file))
sh %W[
bin/tisp #{file}
#{File.exist?(in_file) ? "< #{in_file}" : ''}
#{File.exist?(expected_out_file) ? "> #{actual_out_file}" : ''}
].join ' '
sh "diff #{expected_out_file} #{actual_out_file}" \
if File.exist? expected_out_file
end
Dir.glob 'test/xfail/*.tisp' do |file|
sh "! bin/tisp #{file} > /dev/null 2>&1"
end
end
task test: %i[unit_test command_test]
task :lint do
verbose false do
[
'go vet',
'golint',
'gosimple',
'unused',
'staticcheck',
'interfacer'
].each do |command|
puts "# #{command}"
sh "#{command} ./..."
end
end
end
task :format do
sh 'go fix ./...'
sh 'go fmt ./...'
Dir.glob '**/*.go' do |file|
sh "goimports -w #{file}"
end
sh 'rubocop -a'
end
task :docker do
tag = 'tisplang/tisp-build'
sh "sudo docker build --no-cache -t #{tag} etc/docker"
sh "sudo docker push #{tag}"
end
task :install_deps do
sh %w[
go get -u
github.com/golang/lint/golint
github.com/kr/pretty
github.com/mvdan/interfacer/...
golang.org/x/tools/cmd/goimports
honnef.co/go/tools/...
].join ' '
sh 'go get -d -t ./...'
end
task install: %i[install_deps test build] do
sh 'go get ./...'
end
task :images do
Dir.glob 'img/*.svg' do |file|
sh "inkscape --export-area-drawing --export-png #{file.ext 'png'} #{file}"
end
end
task doc: :images do
sh 'convert -resize 16x16 img/icon.png doc/theme/img/favicon.ico'
cd 'doc'
sh 'mkdocs gh-deploy -m "[skip ci] on Wercker"'
end
task default: %i[test build]
task :clean do
sh 'git clean -dfx'
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{fuel_purchase}
s.version = "0.0.3"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Andy Rossmeissl", "Seamus Abshere", "Ian Hough", "Matt Kling", "Derek Kastner"]
s.date = %q{2010-07-29}
s.description = %q{A software model in Ruby for the greenhouse gas emissions of a fuel purchase}
s.email = %q{andy@rossmeissl.net}
s.extra_rdoc_files = [
"LICENSE",
"README.rdoc"
]
s.files = [
"LICENSE",
"README.rdoc",
"lib/fuel_purchase.rb",
"lib/fuel_purchase/carbon_model.rb",
"lib/fuel_purchase/characterization.rb",
"lib/fuel_purchase/data.rb",
"lib/fuel_purchase/summarization.rb",
"lib/test_support/db/schema.rb",
"lib/test_support/fuel_purchase_record.rb"
]
s.homepage = %q{http://github.com/brighterplanet/fuel_purchase}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.7}
s.summary = %q{A carbon model}
s.test_files = [
"features/support/env.rb",
"features/fuel_purchase_committees.feature",
"features/fuel_purchase_emissions.feature",
"lib/test_support/db/schema.rb",
"lib/test_support/fuel_purchase_record.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<activerecord>, ["= 3.0.0.beta4"])
s.add_development_dependency(%q<bundler>, [">= 1.0.0.beta.2"])
s.add_development_dependency(%q<cucumber>, ["= 0.8.3"])
s.add_development_dependency(%q<jeweler>, ["= 1.4.0"])
s.add_development_dependency(%q<rake>, [">= 0"])
s.add_development_dependency(%q<rdoc>, [">= 0"])
s.add_development_dependency(%q<rspec>, ["= 2.0.0.beta.17"])
s.add_development_dependency(%q<sniff>, ["= 0.0.14"])
s.add_runtime_dependency(%q<characterizable>, ["= 0.0.12"])
s.add_runtime_dependency(%q<cohort_scope>, ["~> 0.0"])
s.add_runtime_dependency(%q<data_miner>, ["= 0.5.2"])
s.add_runtime_dependency(%q<earth>, [">= 0.0.7"])
s.add_runtime_dependency(%q<falls_back_on>, ["= 0.0.2"])
s.add_runtime_dependency(%q<fast_timestamp>, ["= 0.0.4"])
s.add_runtime_dependency(%q<leap>, ["= 0.4.1"])
s.add_runtime_dependency(%q<summary_judgement>, ["= 1.3.8"])
s.add_runtime_dependency(%q<timeframe>, ["= 0.0.8"])
s.add_runtime_dependency(%q<weighted_average>, ["= 0.0.4"])
else
s.add_dependency(%q<activerecord>, ["= 3.0.0.beta4"])
s.add_dependency(%q<bundler>, [">= 1.0.0.beta.2"])
s.add_dependency(%q<cucumber>, ["= 0.8.3"])
s.add_dependency(%q<jeweler>, ["= 1.4.0"])
s.add_dependency(%q<rake>, [">= 0"])
s.add_dependency(%q<rdoc>, [">= 0"])
s.add_dependency(%q<rspec>, ["= 2.0.0.beta.17"])
s.add_dependency(%q<sniff>, ["= 0.0.14"])
s.add_dependency(%q<characterizable>, ["= 0.0.12"])
s.add_dependency(%q<cohort_scope>, ["~> 0.0"])
s.add_dependency(%q<data_miner>, ["= 0.5.2"])
s.add_dependency(%q<earth>, [">= 0.0.7"])
s.add_dependency(%q<falls_back_on>, ["= 0.0.2"])
s.add_dependency(%q<fast_timestamp>, ["= 0.0.4"])
s.add_dependency(%q<leap>, ["= 0.4.1"])
s.add_dependency(%q<summary_judgement>, ["= 1.3.8"])
s.add_dependency(%q<timeframe>, ["= 0.0.8"])
s.add_dependency(%q<weighted_average>, ["= 0.0.4"])
end
else
s.add_dependency(%q<activerecord>, ["= 3.0.0.beta4"])
s.add_dependency(%q<bundler>, [">= 1.0.0.beta.2"])
s.add_dependency(%q<cucumber>, ["= 0.8.3"])
s.add_dependency(%q<jeweler>, ["= 1.4.0"])
s.add_dependency(%q<rake>, [">= 0"])
s.add_dependency(%q<rdoc>, [">= 0"])
s.add_dependency(%q<rspec>, ["= 2.0.0.beta.17"])
s.add_dependency(%q<sniff>, ["= 0.0.14"])
s.add_dependency(%q<characterizable>, ["= 0.0.12"])
s.add_dependency(%q<cohort_scope>, ["~> 0.0"])
s.add_dependency(%q<data_miner>, ["= 0.5.2"])
s.add_dependency(%q<earth>, [">= 0.0.7"])
s.add_dependency(%q<falls_back_on>, ["= 0.0.2"])
s.add_dependency(%q<fast_timestamp>, ["= 0.0.4"])
s.add_dependency(%q<leap>, ["= 0.4.1"])
s.add_dependency(%q<summary_judgement>, ["= 1.3.8"])
s.add_dependency(%q<timeframe>, ["= 0.0.8"])
s.add_dependency(%q<weighted_average>, ["= 0.0.4"])
end
end
Regenerated gemspec for version 0.0.4
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{fuel_purchase}
s.version = "0.0.4"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Andy Rossmeissl", "Seamus Abshere", "Ian Hough", "Matt Kling", "Derek Kastner"]
s.date = %q{2010-07-29}
s.description = %q{A software model in Ruby for the greenhouse gas emissions of a fuel purchase}
s.email = %q{andy@rossmeissl.net}
s.extra_rdoc_files = [
"LICENSE",
"README.rdoc"
]
s.files = [
"LICENSE",
"README.rdoc",
"lib/fuel_purchase.rb",
"lib/fuel_purchase/carbon_model.rb",
"lib/fuel_purchase/characterization.rb",
"lib/fuel_purchase/data.rb",
"lib/fuel_purchase/summarization.rb",
"lib/test_support/db/schema.rb",
"lib/test_support/fuel_purchase_record.rb"
]
s.homepage = %q{http://github.com/brighterplanet/fuel_purchase}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.7}
s.summary = %q{A carbon model}
s.test_files = [
"features/support/env.rb",
"features/fuel_purchase_committees.feature",
"features/fuel_purchase_emissions.feature",
"lib/test_support/db/schema.rb",
"lib/test_support/fuel_purchase_record.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<activerecord>, ["= 3.0.0.beta4"])
s.add_development_dependency(%q<bundler>, [">= 1.0.0.beta.2"])
s.add_development_dependency(%q<cucumber>, ["= 0.8.3"])
s.add_development_dependency(%q<jeweler>, ["= 1.4.0"])
s.add_development_dependency(%q<rake>, [">= 0"])
s.add_development_dependency(%q<rdoc>, [">= 0"])
s.add_development_dependency(%q<rspec>, ["= 2.0.0.beta.17"])
s.add_development_dependency(%q<sniff>, ["= 0.0.14"])
s.add_runtime_dependency(%q<characterizable>, ["= 0.0.12"])
s.add_runtime_dependency(%q<cohort_scope>, ["~> 0.0"])
s.add_runtime_dependency(%q<data_miner>, ["= 0.5.2"])
s.add_runtime_dependency(%q<earth>, [">= 0.0.7"])
s.add_runtime_dependency(%q<falls_back_on>, ["= 0.0.2"])
s.add_runtime_dependency(%q<fast_timestamp>, ["= 0.0.4"])
s.add_runtime_dependency(%q<leap>, ["= 0.4.1"])
s.add_runtime_dependency(%q<summary_judgement>, ["= 1.3.8"])
s.add_runtime_dependency(%q<timeframe>, ["= 0.0.8"])
s.add_runtime_dependency(%q<weighted_average>, ["= 0.0.4"])
else
s.add_dependency(%q<activerecord>, ["= 3.0.0.beta4"])
s.add_dependency(%q<bundler>, [">= 1.0.0.beta.2"])
s.add_dependency(%q<cucumber>, ["= 0.8.3"])
s.add_dependency(%q<jeweler>, ["= 1.4.0"])
s.add_dependency(%q<rake>, [">= 0"])
s.add_dependency(%q<rdoc>, [">= 0"])
s.add_dependency(%q<rspec>, ["= 2.0.0.beta.17"])
s.add_dependency(%q<sniff>, ["= 0.0.14"])
s.add_dependency(%q<characterizable>, ["= 0.0.12"])
s.add_dependency(%q<cohort_scope>, ["~> 0.0"])
s.add_dependency(%q<data_miner>, ["= 0.5.2"])
s.add_dependency(%q<earth>, [">= 0.0.7"])
s.add_dependency(%q<falls_back_on>, ["= 0.0.2"])
s.add_dependency(%q<fast_timestamp>, ["= 0.0.4"])
s.add_dependency(%q<leap>, ["= 0.4.1"])
s.add_dependency(%q<summary_judgement>, ["= 1.3.8"])
s.add_dependency(%q<timeframe>, ["= 0.0.8"])
s.add_dependency(%q<weighted_average>, ["= 0.0.4"])
end
else
s.add_dependency(%q<activerecord>, ["= 3.0.0.beta4"])
s.add_dependency(%q<bundler>, [">= 1.0.0.beta.2"])
s.add_dependency(%q<cucumber>, ["= 0.8.3"])
s.add_dependency(%q<jeweler>, ["= 1.4.0"])
s.add_dependency(%q<rake>, [">= 0"])
s.add_dependency(%q<rdoc>, [">= 0"])
s.add_dependency(%q<rspec>, ["= 2.0.0.beta.17"])
s.add_dependency(%q<sniff>, ["= 0.0.14"])
s.add_dependency(%q<characterizable>, ["= 0.0.12"])
s.add_dependency(%q<cohort_scope>, ["~> 0.0"])
s.add_dependency(%q<data_miner>, ["= 0.5.2"])
s.add_dependency(%q<earth>, [">= 0.0.7"])
s.add_dependency(%q<falls_back_on>, ["= 0.0.2"])
s.add_dependency(%q<fast_timestamp>, ["= 0.0.4"])
s.add_dependency(%q<leap>, ["= 0.4.1"])
s.add_dependency(%q<summary_judgement>, ["= 1.3.8"])
s.add_dependency(%q<timeframe>, ["= 0.0.8"])
s.add_dependency(%q<weighted_average>, ["= 0.0.4"])
end
end
|
require_relative "../../test_helper"
require "health_check/logging_config"
require "health_check/search_check"
Logging.logger.root.appenders = nil
module HealthCheck
class SearchCheckTest < ShouldaUnitTestCase
end
end
Add some simple testing for the SearchCheck struct
require_relative "../../test_helper"
require "health_check/search_check"
module HealthCheck
class SearchCheckTest < ShouldaUnitTestCase
def setup
@subject = SearchCheck.new
@search_results = ["any-old-thing"]
end
context "#result" do
should "delegate to it's corresponding results class" do
SearchCheckResult.expects(:new).with({check: @subject, search_results: @search_results})
@subject.result(@search_results)
end
end
context "#valid_imperative?" do
should "be true only for valid imperatives" do
assert @subject.tap { |c| c.imperative = "should" }.valid_imperative?
assert @subject.tap { |c| c.imperative = "should not" }.valid_imperative?
refute @subject.tap { |c| c.imperative = "anything else" }.valid_imperative?
end
end
context "#valid_path?" do
should "be true only for valid paths" do
assert @subject.tap { |c| c.path = "/" }.valid_path?
refute @subject.tap { |c| c.path = "foo" }.valid_path?
refute @subject.tap { |c| c.path = "" }.valid_path?
refute @subject.tap { |c| c.path = nil }.valid_path?
end
end
context "#valid_search_term?" do
should "be true only for non-blank search terms" do
assert @subject.tap { |c| c.search_term = "foo" }.valid_search_term?
refute @subject.tap { |c| c.search_term = "" }.valid_search_term?
refute @subject.tap { |c| c.search_term = nil }.valid_search_term?
end
end
context "valid_weight?" do
should "be true only for weights greater than 0" do
refute @subject.tap { |c| c.weight = -1 }.valid_weight?
refute @subject.tap { |c| c.weight = 0 }.valid_weight?
assert @subject.tap { |c| c.weight = 1 }.valid_weight?
end
end
end
end
|
# Tests for a generic Instruction
class TestInstructions < Minitest::Test
include TestHelper
def tested
@tested ||= build_tested
end
def build_tested
subject = PictureTag::Instructions::Instruction.new
subject.stubs(source: 'setting')
subject
end
def test_value
assert_equal 'setting', tested.value
end
def test_validation_fail
tested.stubs(valid?: false)
assert_raises(ArgumentError) { tested.value }
end
def test_coercion
tested.stubs(coerce: 'coerced')
assert_equal 'coerced', tested.value
end
end
Add EnvInstruction validation test
# Tests for a generic Instruction
class TestInstructions < Minitest::Test
include TestHelper
def tested
@tested ||= build_tested
end
def build_tested
subject = PictureTag::Instructions::Instruction.new
subject.stubs(source: 'setting')
subject
end
def test_value
assert_equal 'setting', tested.value
end
def test_validation_fail
tested.stubs(valid?: false)
assert_raises(ArgumentError) { tested.value }
end
def test_coercion
tested.stubs(coerce: 'coerced')
assert_equal 'coerced', tested.value
end
def test_env_arg
subject = PictureTag::Instructions::EnvInstruction.new
# Env instructions dont' accept numbers
subject.stubs(source: 42)
assert_raises(ArgumentError) { subject.value }
end
end
|
Added tests
require 'test_helper'
class ExchangerValidatable
include ActiveModel::Validations
attr_accessor :exchanger
validates :exchanger, exchanger: true
end
class ExchangerValidatableWithTransformMethod
include ActiveModel::Validations
attr_accessor :id
validates :id, exchanger: { transform: :exchanger_name }
def exchanger_name; end
end
class ExchangerValidatableWithTransformCallable
include ActiveModel::Validations
attr_accessor :id
validates :id, exchanger: { transform: ->(_record, _value) { 'other_exchanger_name' } }
end
class ExchangerValidatorTest < ActiveSupport::TestCase
setup do
@exchangers = ActiveExchanger::Base.exchangers
ActiveExchanger::Base.exchangers = {
valid_exchanger_name: Object,
other_exchanger_name: Object
}
end
teardown do
ActiveExchanger::Base.exchangers = @exchangers
end
test 'fails when exchanger name does not exist' do
record = ExchangerValidatable.new
record.exchanger = "invalid_name"
assert_not record.valid?
assert_equal 1, record.errors.messages[:exchanger].count
end
test 'valid when exchanger name exists' do
record = ExchangerValidatable.new
record.exchanger = "valid_exchanger_name"
assert record.valid?
end
test 'calls the method to get exchanger name when symbol is passed as transform parameter' do
record = ExchangerValidatableWithTransformMethod.new
record.stub :exchanger_name, "valid_exchanger_name" do
assert record.valid?
end
end
test 'use the callable to get exchanger name when callable is passed as transform parameter' do
record = ExchangerValidatableWithTransformCallable.new
assert record.valid?
end
end
|
require "xcodeproj"
module Fastlane
module Actions
class UpdateNativeSdksAction < Action
class << self
UI = FastlaneCore::UI
def run(params)
update_submodules
android_subdir = File.expand_path 'android', '.'
update_android_jar android_subdir
ios_subdir = File.expand_path 'ios', '.'
update_ios_branch_source ios_subdir
update_branch_podspec_from_submodule ios_subdir
adjust_rnbranch_xcodeproj ios_subdir
=begin
%w{
examples/testbed_native_ios
examples/webview_example_native_ios
.
}.each { |f| yarn f }
%w{
examples/testbed_native_ios
examples/webview_example_native_ios
native-tests/ios
}.each { |f| pod_install f }
=end
# commit
end
def available_options
[]
end
def commit
`git commit -a -m'[Fastlane] Branch native SDK update'`
end
def update_submodules
UI.message "Updating native SDK submodules..."
%w{android/native-sdk ios/native-sdk}.each do |folder|
Dir.chdir(folder) do
`git checkout -q master`
`git pull -q origin master`
checkout_last_git_tag
UI.message "Updated submodule in #{folder}"
end
end
end
def update_android_jar(android_subdir)
jar = Dir['android/native-sdk/Branch*.jar'].reject { |j| j =~ /core/ }.first
version = jar.sub(/^.*Branch-/, '').sub(/\.jar$/, '')
return if File.exist? "#{android_subdir}/libs/Branch-#{version}.jar"
# Remove the old and add the new (symlink)
Dir.chdir("#{android_subdir}/libs") do
`git rm -f Branch-*.jar`
File.symlink "../native-tests/Branch-#{version}.jar", "./Branch-#{version}.jar"
`git add Branch-#{version}.jar`
end
# Patch build.gradle
other_action.apply_patch(
files: "#{android_subdir}/build.gradle",
mode: :replace,
regexp: /Branch-.*\.jar/,
text: "Branch-#{version}.jar"
)
end
def update_ios_branch_source(ios_subdir)
end
def update_branch_podspec_from_submodule(ios_subdir)
branch_sdk_podspec_path = "#{ios_subdir}/Branch-SDK.podspec"
# Copy the podspec from the submodule
`cp #{ios_subdir}/native-sdk/Branch.podspec #{branch_sdk_podspec_path}`
UI.user_error! "Unable to update #{branch_sdk_podspec_path}" unless $?.exitstatus == 0
# Change the pod name to Branch-SDK
other_action.apply_patch(
files: branch_sdk_podspec_path,
regexp: /(s\.name\s*)= "Branch"/,
mode: :replace,
text: '\1= "Branch-SDK"'
)
# Add s.header_dir = "Branch" (also determines the module name)
other_action.apply_patch(
files: branch_sdk_podspec_path,
regexp: /s.requires_arc.*$/,
mode: :append,
text: "\n s.header_dir = \"Branch\""
)
UI.message "Updated ios/Branch-SDK.podspec"
end
def adjust_rnbranch_xcodeproj(ios_subdir)
@project = Xcodeproj::Project.open "#{ios_subdir}/RNBranch.xcodeproj"
ios_subdir_pathname = Pathname.new ios_subdir
# 1. Find all SDK .h, .m files and add any not already in the project.
Dir[File.expand_path "#{ios_subdir}/Branch-SDK/**/*.[hm]", ios_subdir].each do |filename|
# Avoid TestBed and tests. (alternatives: parse the podspec for the source_files or
# restructure the ios repo so that the SDK is well separated)
# Ignore any files already in the project.
next if filename =~ /Test/ || @project.files.find { |f| f.real_path.to_s == filename }
# New file. Look for the group.
group_pathname = Pathname.new(File.dirname(filename)).relative_path_from(ios_subdir_pathname)
group = ensure_group_at_path group_pathname
file_basename = File.basename filename
file = group.new_file file_basename
if filename =~ /\.h$/
copy_branch_sdk_headers_build_phase.add_file_reference file
else
source_build_phase.add_file_reference file
end
end
# check_file_refs
# 2. Make sure all files in the project still exist. Remove those that do not.
@project.files.each do |file|
next if File.exist? file.real_path
# file.remove_from_project # results in nil file_ref in build phases
file.parent.children.delete file
if file.path =~ /\.h$/
copy_branch_sdk_headers_build_phase.remove_file_reference file
else
source_build_phase.remove_file_reference file
end
end
# check_file_refs
# 3. Remove any empty groups from the project
remove_empty_groups @project.main_group
# check_file_refs
@project.save
UI.message "Updated ios/RNBranch.xcodeproj"
end
def ensure_group_at_path(pathname)
subgroup = @project.main_group[pathname.to_s]
return subgroup unless subgroup.nil?
dirname, basename = pathname.split
parent = ensure_group_at_path dirname
parent.new_group basename.to_s, basename.to_s
end
def remove_empty_groups(group)
group.groups.each { |g| remove_empty_groups g }
group.remove_from_project if group.empty?
end
def check_file_refs
[copy_branch_sdk_headers_build_phase, source_build_phase].each do |build_phase|
build_phase.files.each do |build_file|
raise "nil file_ref in #{build_phase.display_name}" if build_file.file_ref.nil?
end
end
end
def copy_branch_sdk_headers_build_phase
target = @project.targets.first
target.build_phases.find { |phase| phase.respond_to?(:name) && phase.name == "Copy Branch SDK Headers" }
end
def source_build_phase
@project.targets.first.source_build_phase
end
def checkout_last_git_tag
commit = `git rev-list --tags='[0-9]*.[0-9]*.[0-9]*' --max-count=1`
`git checkout -q #{commit}`
end
def yarn(folder)
Dir.chdir(folder) do
UI.message "Running yarn in #{folder} ..."
`yarn -s > /dev/null 2>&1`
UI.message "Done"
end
end
def pod_install(folder)
Dir.chdir(folder) do
`bundle exec pod install --silent`
`git add .`
UI.message "pod install complete in #{folder}"
end
end
end
end
end
end
Adjust to new submodule structure
require "xcodeproj"
module Fastlane
module Actions
class UpdateNativeSdksAction < Action
class << self
UI = FastlaneCore::UI
def run(params)
update_submodules
@android_subdir = File.expand_path 'android', '.'
@ios_subdir = File.expand_path 'ios', '.'
# Update embedded Android SDK
update_android_jar
# Update embedded iOS SDK
update_ios_branch_source
update_branch_podspec_from_submodule
adjust_rnbranch_xcodeproj
=begin
%w{
examples/testbed_native_ios
examples/webview_example_native_ios
.
}.each { |f| yarn f }
%w{
examples/testbed_native_ios
examples/webview_example_native_ios
native-tests/ios
}.each { |f| pod_install f }
=end
# commit
end
def available_options
[]
end
def commit
`git commit -a -m'[Fastlane] Branch native SDK update'`
end
def update_submodules
UI.message "Updating native SDK submodules..."
%w{native-sdks/android native-sdks/ios}.each do |folder|
Dir.chdir(folder) do
`git checkout -q master`
`git pull -q origin master`
checkout_last_git_tag
UI.message "Updated submodule in #{folder}"
end
end
end
def update_android_jar
jar = Dir['native-sdks/android/Branch*.jar'].reject { |j| j =~ /core/ }.first
version = jar.sub(/^.*Branch-/, '').sub(/\.jar$/, '')
return if File.exist? "#{@android_subdir}/libs/Branch-#{version}.jar"
# Remove the old and add the new
Dir.chdir("#{@android_subdir}/libs") do
`git rm -f Branch-*.jar`
`cp ../../native-sdks/android/Branch-#{version}.jar .`
`git add Branch-#{version}.jar`
end
# Patch build.gradle
other_action.apply_patch(
files: "#{@android_subdir}/build.gradle",
mode: :replace,
regexp: /Branch-.*\.jar/,
text: "Branch-#{version}.jar"
)
end
def update_ios_branch_source
`git rm -fr ios/Branch-SDK`
`cp -r native-sdks/ios/Branch-SDK ios`
`git add ios/Branch-SDK`
end
def update_branch_podspec_from_submodule
branch_sdk_podspec_path = "#{ios_subdir}/Branch-SDK.podspec"
# Copy the podspec from the submodule
`cp native-sdks/ios/Branch.podspec #{branch_sdk_podspec_path}`
UI.user_error! "Unable to update #{branch_sdk_podspec_path}" unless $?.exitstatus == 0
# Change the pod name to Branch-SDK
other_action.apply_patch(
files: branch_sdk_podspec_path,
regexp: /(s\.name\s*)= "Branch"/,
mode: :replace,
text: '\1= "Branch-SDK"'
)
# Add s.header_dir = "Branch" (also determines the module name)
other_action.apply_patch(
files: branch_sdk_podspec_path,
regexp: /s.requires_arc.*$/,
mode: :append,
text: "\n s.header_dir = \"Branch\""
)
UI.message "Updated ios/Branch-SDK.podspec"
end
def adjust_rnbranch_xcodeproj
@project = Xcodeproj::Project.open "#{ios_subdir}/RNBranch.xcodeproj"
ios_subdir_pathname = Pathname.new @ios_subdir
# 1. Find all SDK .h, .m files and add any not already in the project.
Dir[File.expand_path "#{@ios_subdir}/Branch-SDK/**/*.[hm]", @ios_subdir].each do |filename|
# Ignore any files already in the project.
next if @project.files.find { |f| f.real_path.to_s == filename }
# New file. Look for the group.
group_pathname = Pathname.new(File.dirname(filename)).relative_path_from(ios_subdir_pathname)
group = ensure_group_at_path group_pathname
file_basename = File.basename filename
file = group.new_file file_basename
if filename =~ /\.h$/
copy_branch_sdk_headers_build_phase.add_file_reference file
else
source_build_phase.add_file_reference file
end
end
# check_file_refs
# 2. Make sure all files in the project still exist. Remove those that do not.
@project.files.each do |file|
next if File.exist? file.real_path
# file.remove_from_project # results in nil file_ref in build phases
file.parent.children.delete file
if file.path =~ /\.h$/
copy_branch_sdk_headers_build_phase.remove_file_reference file
else
source_build_phase.remove_file_reference file
end
end
# check_file_refs
# 3. Remove any empty groups from the project
remove_empty_groups @project.main_group
# check_file_refs
@project.save
UI.message "Updated ios/RNBranch.xcodeproj"
end
def ensure_group_at_path(pathname)
subgroup = @project.main_group[pathname.to_s]
return subgroup unless subgroup.nil?
dirname, basename = pathname.split
parent = ensure_group_at_path dirname
parent.new_group basename.to_s, basename.to_s
end
def remove_empty_groups(group)
group.groups.each { |g| remove_empty_groups g }
group.remove_from_project if group.empty?
end
def check_file_refs
[copy_branch_sdk_headers_build_phase, source_build_phase].each do |build_phase|
build_phase.files.each do |build_file|
raise "nil file_ref in #{build_phase.display_name}" if build_file.file_ref.nil?
end
end
end
def copy_branch_sdk_headers_build_phase
target = @project.targets.first
target.build_phases.find { |phase| phase.respond_to?(:name) && phase.name == "Copy Branch SDK Headers" }
end
def source_build_phase
@project.targets.first.source_build_phase
end
def checkout_last_git_tag
commit = `git rev-list --tags='[0-9]*.[0-9]*.[0-9]*' --max-count=1`
`git checkout -q #{commit}`
end
def yarn(folder)
Dir.chdir(folder) do
UI.message "Running yarn in #{folder} ..."
`yarn -s > /dev/null 2>&1`
UI.message "Done"
end
end
def pod_install(folder)
Dir.chdir(folder) do
`bundle exec pod install --silent`
`git add .`
UI.message "pod install complete in #{folder}"
end
end
end
end
end
end
|
# -*- encoding: utf-8 -*-
$LOAD_PATH.push File.expand_path('../lib', __FILE__)
require 'pronto/rubocop/version'
require 'English'
Gem::Specification.new do |s|
s.name = 'pronto-rubocop'
s.version = Pronto::RubocopVersion::VERSION
s.platform = Gem::Platform::RUBY
s.author = 'Mindaugas Mozūras'
s.email = 'mindaugas.mozuras@gmail.com'
s.homepage = 'http://github.com/mmozuras/pronto-rubocop'
s.summary = 'Pronto runner for Rubocop, ruby code analyzer'
s.licenses = ['MIT']
s.required_ruby_version = '>= 2.0.0'
s.rubygems_version = '1.8.23'
s.files = `git ls-files`.split($RS).reject do |file|
file =~ %r{^(?:
spec/.*
|Gemfile
|Rakefile
|\.rspec
|\.gitignore
|\.rubocop.yml
|\.travis.yml
)$}x
end
s.test_files = []
s.extra_rdoc_files = ['LICENSE', 'README.md']
s.require_paths = ['lib']
s.add_runtime_dependency('rubocop', '~> 0.38', '>= 0.35.0')
s.add_runtime_dependency('pronto', '~> 0.9.0')
s.add_development_dependency('rake', '~> 12.0')
s.add_development_dependency('rspec', '~> 3.4')
s.add_development_dependency('rspec-its', '~> 1.2')
end
Update rubocop dependency to >= 0.49.1
Closes #34
# -*- encoding: utf-8 -*-
$LOAD_PATH.push File.expand_path('../lib', __FILE__)
require 'pronto/rubocop/version'
require 'English'
Gem::Specification.new do |s|
s.name = 'pronto-rubocop'
s.version = Pronto::RubocopVersion::VERSION
s.platform = Gem::Platform::RUBY
s.author = 'Mindaugas Mozūras'
s.email = 'mindaugas.mozuras@gmail.com'
s.homepage = 'http://github.com/mmozuras/pronto-rubocop'
s.summary = 'Pronto runner for Rubocop, ruby code analyzer'
s.licenses = ['MIT']
s.required_ruby_version = '>= 2.0.0'
s.rubygems_version = '1.8.23'
s.files = `git ls-files`.split($RS).reject do |file|
file =~ %r{^(?:
spec/.*
|Gemfile
|Rakefile
|\.rspec
|\.gitignore
|\.rubocop.yml
|\.travis.yml
)$}x
end
s.test_files = []
s.extra_rdoc_files = ['LICENSE', 'README.md']
s.require_paths = ['lib']
s.add_runtime_dependency('rubocop', '~> 0.50', '>= 0.49.1')
s.add_runtime_dependency('pronto', '~> 0.9.0')
s.add_development_dependency('rake', '~> 12.0')
s.add_development_dependency('rspec', '~> 3.4')
s.add_development_dependency('rspec-its', '~> 1.2')
end
|
ActiveAdmin.register AdminUser do
filter :email
index do
selectable_column
column :email
column :owner do |a|
AdminUser.true_admin? a.email
end
column :current_sign_in_at
column :last_sign_in_at
column :sign_in_count
actions if AdminUser.true_admin? current_admin_user.email
end
form do |f|
f.inputs "Admin Details" do
f.input :email
f.input :password
f.input :password_confirmation
end
f.actions
end
controller do
def destroy
if AdminUser.true_admin? current_admin_user.email
super
else
flash[:alert] = "Warning: You don't have enough privilege to delete"
render :index
end
end
def new
if AdminUser.true_admin? current_admin_user.email
super
else
flash[:alert] = "Warning: You don't have enough privilege to create another admin"
render :index
end
end
def show
if AdminUser.true_admin? current_admin_user.email
super
else
flash[:alert] = "Warning: You don't have enough privilege to view other admin"
render :index
end
end
def update
if AdminUser.true_admin? current_admin_user.email
super
else
flash[:alert] = "Warning: You don't have enough privilege to update this page"
render :index
end
end
def edit
if AdminUser.true_admin? current_admin_user.email
super
else
flash[:alert] = "Warning: You don't have enough privilege to edit another admin"
render :index
end
end
end
end
quick: fixed show admin route
use to_s
DRIVER: da0a816d46fee8c836212ff6606c18bb04f6a0cf@msn.com
OBSERVER: 8ca5a3b38c2e46b3b15fa466109ee8bf83d11fd5@berkeley.edu
ActiveAdmin.register AdminUser do
filter :email
index do
selectable_column
column :email
column :owner do |a|
AdminUser.true_admin? a.email
end
column :current_sign_in_at
column :last_sign_in_at
column :sign_in_count
actions if AdminUser.true_admin? current_admin_user.email
end
form do |f|
f.inputs "Admin Details" do
f.input :email
f.input :password
f.input :password_confirmation
end
f.actions
end
controller do
def destroy
if AdminUser.true_admin? current_admin_user.email
super
else
flash[:alert] = "Warning: You don't have enough privilege to delete"
render :index
end
end
def new
if AdminUser.true_admin? current_admin_user.email
super
else
flash[:alert] = "Warning: You don't have enough privilege to create another admin"
render :index
end
end
def show
if AdminUser.true_admin? current_admin_user.email or current_admin_user.id.to_s == params[:id].to_s
super
else
flash[:alert] = "Warning: You don't have enough privilege to view other admin"
render :index
end
end
def update
if AdminUser.true_admin? current_admin_user.email
super
else
flash[:alert] = "Warning: You don't have enough privilege to update this page"
render :index
end
end
def edit
if AdminUser.true_admin? current_admin_user.email
super
else
flash[:alert] = "Warning: You don't have enough privilege to edit another admin"
render :index
end
end
end
end
|
# -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
require 'pronto/rubocop/version'
Gem::Specification.new do |s|
s.name = 'pronto-rubocop'
s.version = Pronto::RubocopVersion::VERSION
s.platform = Gem::Platform::RUBY
s.author = 'Mindaugas Mozūras'
s.email = 'mindaugas.mozuras@gmail.com'
s.homepage = 'http://github.org/mmozuras/pronto-rubocop'
s.summary = 'Pronto runner for Rubocop, ruby code analyzer'
s.required_rubygems_version = '>= 1.3.6'
s.license = 'MIT'
s.files = Dir.glob('{lib}/**/*') + %w[LICENSE README.md]
s.test_files = `git ls-files -- {spec}/*`.split("\n")
s.require_paths = ['lib']
s.add_dependency 'rubocop', '~> 0.13.0'
s.add_dependency 'pronto', '~> 0.1.0'
s.add_development_dependency 'rake', '~> 10.1.0'
s.add_development_dependency 'rspec', '~> 2.14.0'
end
Update rubocop dependency version from 0.13.0 to 0.14.0
# -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
require 'pronto/rubocop/version'
Gem::Specification.new do |s|
s.name = 'pronto-rubocop'
s.version = Pronto::RubocopVersion::VERSION
s.platform = Gem::Platform::RUBY
s.author = 'Mindaugas Mozūras'
s.email = 'mindaugas.mozuras@gmail.com'
s.homepage = 'http://github.org/mmozuras/pronto-rubocop'
s.summary = 'Pronto runner for Rubocop, ruby code analyzer'
s.required_rubygems_version = '>= 1.3.6'
s.license = 'MIT'
s.files = Dir.glob('{lib}/**/*') + %w[LICENSE README.md]
s.test_files = `git ls-files -- {spec}/*`.split("\n")
s.require_paths = ['lib']
s.add_dependency 'rubocop', '~> 0.14.0'
s.add_dependency 'pronto', '~> 0.1.0'
s.add_development_dependency 'rake', '~> 10.1.0'
s.add_development_dependency 'rspec', '~> 2.14.0'
end
|
module PageObjectModel
class BookReaderPage < PageObjectModel::Page
trait "FrameLayout id:'content'"
element :bookmarker, "ImageView marked:'Reader bookmark'"
element :bookmark, "* id:'imageview_bookmark'"
element :options, "* id:'button_options'"
#TODO: Reading Options menu should be defined as a section or separate page
@@forward_tapping_point = {x: 90, y: 50}
@@backward_tapping_point = {x: 10, y: 50}
@optionsDisplayed = false
def turn_pages(number_of_pages)
point = number_of_pages.to_i >= 0 ? @@forward_tapping_point : @@backward_tapping_point
(number_of_pages.to_i.abs).times { tap(point[:x], point[:y]) }
end
def toggle_reader_options
tap(50, 50)
if !@optionsDisplayed
@optionsDisplayed = true
options.exists?
else
@optionsDisplayed = false
end
end
def open_options_menu
#This waiting for trait is due to the reader page having loaded but
#the content is asynchronous
Element.new("* id:'webview_reader'").wait_for_element_exists(timeout: 10)
toggle_reader_options
end
def toggle_bookmark
wait_for(:timeout => 5) {
bookmarker.touch
}
end
#TODO: should check for visibility not only existence?
def has_bookmark?
bookmark.exists?
end
def has_options?
options.exists?
end
end
def book_reader_page
@_book_reader_page ||= page(BookReaderPage)
end
end
removing exists that's not used
module PageObjectModel
class BookReaderPage < PageObjectModel::Page
trait "FrameLayout id:'content'"
element :bookmarker, "ImageView marked:'Reader bookmark'"
element :bookmark, "* id:'imageview_bookmark'"
element :options, "* id:'button_options'"
#TODO: Reading Options menu should be defined as a section or separate page
@@forward_tapping_point = {x: 90, y: 50}
@@backward_tapping_point = {x: 10, y: 50}
@optionsDisplayed = false
def turn_pages(number_of_pages)
point = number_of_pages.to_i >= 0 ? @@forward_tapping_point : @@backward_tapping_point
(number_of_pages.to_i.abs).times { tap(point[:x], point[:y]) }
end
def toggle_reader_options
tap(50, 50)
if !@optionsDisplayed
@optionsDisplayed = true
else
@optionsDisplayed = false
end
end
def open_options_menu
#This waiting for trait is due to the reader page having loaded but
#the content is asynchronous
Element.new("* id:'webview_reader'").wait_for_element_exists(timeout: 10)
toggle_reader_options
end
def toggle_bookmark
wait_for(:timeout => 5) {
bookmarker.touch
}
end
#TODO: should check for visibility not only existence?
def has_bookmark?
bookmark.exists?
end
def has_options?
options.exists?
end
end
def book_reader_page
@_book_reader_page ||= page(BookReaderPage)
end
end
|
Then(/^I run Vigia$/) do
Vigia.rspec!
@stdout.rewind
@stderr.rewind
@vigia_stdout = @stdout.read
@vigia_stderr = @stderr.read
RSpec.reset
end
Then(/^the output should contain the following:$/) do |text|
real_text = text.gsub('{SOURCE_FILE}', Vigia::Rspec.adapter.source_file)
expect(@vigia_stdout.lines.to_a).to include(*real_text.lines.to_a)
end
Then(/^the total tests line should equal "(.*?)"$/) do |totals_line|
total_time_line = @vigia_stdout.lines.select { |x| x.start_with?('Finished in ') }.last
total_output_line = @vigia_stdout.lines.to_a[@vigia_stdout.lines.to_a.index(total_time_line) + 1]
expect(total_output_line.strip).to eql(totals_line.strip)
end
Then(/^the error output should be empty$/) do
expect(@vigia_stderr).to be_empty
end
Make expectation message more readble in cucumber tests
Then(/^I run Vigia$/) do
Vigia.rspec!
@stdout.rewind
@stderr.rewind
@vigia_stdout = @stdout.read
@vigia_stderr = @stderr.read
RSpec.reset
end
Then(/^the output should contain the following:$/) do |text|
real_text = text.gsub('{SOURCE_FILE}', Vigia::Rspec.adapter.source_file)
expect(@vigia_stdout.lines.to_a).to include(*real_text.lines.to_a), -> do
"Could not find lines: \n #{ (real_text.lines.to_a - @vigia_stdout.lines.to_a).join("\n") }"
end
end
Then(/^the total tests line should equal "(.*?)"$/) do |totals_line|
total_time_line = @vigia_stdout.lines.select { |x| x.start_with?('Finished in ') }.last
total_output_line = @vigia_stdout.lines.to_a[@vigia_stdout.lines.to_a.index(total_time_line) + 1]
expect(total_output_line.strip).to eql(totals_line.strip)
end
Then(/^the error output should be empty$/) do
expect(@vigia_stderr).to be_empty
end
|
module ManualHelpers
def manual_repository
RepositoryRegistry.create.manual_repository
end
def create_manual(fields, save: true)
visit new_manual_path
fill_in_fields(fields)
yield if block_given?
save_as_draft if save
end
def create_manual_without_ui(fields, organisation_slug: "ministry-of-tea")
stub_organisation_details(organisation_slug)
manual_services = OrganisationalManualServiceRegistry.new(
organisation_slug: organisation_slug,
)
manual = manual_services.create(
fields.merge(organisation_slug: organisation_slug),
).call
manual_repository.fetch(manual.id)
end
def create_manual_document(manual_title, fields)
go_to_manual_page(manual_title)
click_on "Add section"
fill_in_fields(fields)
yield if block_given?
save_as_draft
end
def create_manual_document_without_ui(manual, fields, organisation_slug: "ministry-of-tea")
manual_document_services = OrganisationalSectionServiceRegistry.new(
organisation_slug: organisation_slug,
)
create_service_context = OpenStruct.new(
params: {
"manual_id" => manual.id,
"document" => fields,
}
)
_, document = manual_document_services.create(create_service_context).call
document
end
def edit_manual(manual_title, new_fields)
go_to_edit_page_for_manual(manual_title)
fill_in_fields(new_fields)
yield if block_given?
save_as_draft
end
def edit_manual_without_ui(manual, fields, organisation_slug: "ministry-of-tea")
stub_organisation_details(organisation_slug)
manual_services = OrganisationalManualServiceRegistry.new(
organisation_slug: organisation_slug,
)
manual = manual_services.update(
manual.id,
fields.merge(organisation_slug: organisation_slug),
).call
manual
end
def edit_manual_document(manual_title, section_title, new_fields)
go_to_manual_page(manual_title)
click_on section_title
click_on "Edit"
fill_in_fields(new_fields)
yield if block_given?
save_as_draft
end
def edit_manual_document_without_ui(manual, document, fields, organisation_slug: "ministry-of-tea")
manual_document_services = OrganisationalSectionServiceRegistry.new(
organisation_slug: organisation_slug,
)
service_context = OpenStruct.new(
params: {
"manual_id" => manual.id,
"id" => document.id,
"document" => fields,
}
)
_, document = manual_document_services.update(service_context).call
document
end
def edit_manual_original_publication_date(manual_title)
go_to_manual_page(manual_title)
click_on("Edit first publication date")
yield if block_given?
save_as_draft
end
def withdraw_manual_document(manual_title, section_title, change_note: nil, minor_update: true)
go_to_manual_page(manual_title)
click_on section_title
click_on "Withdraw"
fill_in "Change note", with: change_note unless change_note.blank?
if minor_update
choose "Minor update"
end
click_on "Yes"
end
def save_as_draft
click_on "Save as draft"
end
def publish_manual
click_on "Publish manual"
end
def stub_manual_publication_observers(organisation_slug)
stub_rummager
stub_publishing_api
stub_organisation_details(organisation_slug)
end
def publish_manual_without_ui(manual, organisation_slug: "ministry-of-tea")
stub_manual_publication_observers(organisation_slug)
manual_services = ManualServiceRegistry.new
manual_services.publish(manual.id, manual.version_number).call
end
def check_manual_exists_with(attributes)
go_to_manual_page(attributes.fetch(:title))
expect(page).to have_content(attributes.fetch(:summary))
end
def check_manual_does_not_exist_with(attributes)
visit manuals_path
expect(page).not_to have_content(attributes.fetch(:title))
end
def check_manual_document_exists_with(manual_title, attributes)
go_to_manual_page(manual_title)
click_on(attributes.fetch(:section_title))
attributes.values.each do |attr_val|
expect(page).to have_content(attr_val)
end
end
def check_section_exists(manual_id, section_id)
manual = manual_repository.fetch(manual_id)
manual.documents.any? { |document| document.id == section_id }
end
def check_section_was_removed(manual_id, section_id)
manual = manual_repository.fetch(manual_id)
manual.removed_documents.any? { |document| document.id == section_id }
end
def go_to_edit_page_for_manual(manual_title)
go_to_manual_page(manual_title)
click_on("Edit manual")
end
def check_for_errors_for_fields(field)
expect(page).to have_content("#{field.titlecase} can't be blank")
end
def check_content_preview_link(slug)
preview_url = "#{Plek.current.find('draft-origin')}/#{slug}"
expect(page).to have_link("Preview draft", href: preview_url)
end
def check_live_link(slug)
live_url = "#{Plek.current.website_root}/#{slug}"
expect(page).to have_link("View on website", href: live_url)
end
def go_to_manual_page(manual_title)
visit manuals_path
click_link manual_title
end
def check_manual_and_documents_were_published(manual, document, manual_attrs, document_attrs)
check_manual_is_published_to_publishing_api(manual.id)
check_manual_document_is_published_to_publishing_api(document.id)
check_manual_is_published_to_rummager(manual.slug, manual_attrs)
check_section_is_published_to_rummager(document.slug, document_attrs, manual_attrs)
end
def check_manual_was_published(manual)
check_manual_is_published_to_publishing_api(manual.id)
end
def check_manual_was_not_published(manual)
check_manual_is_not_published_to_publishing_api(manual.id)
end
def check_manual_document_was_published(document)
check_manual_document_is_published_to_publishing_api(document.id)
end
def check_manual_document_was_not_published(document)
check_manual_document_is_not_published_to_publishing_api(document.id)
end
def check_manual_document_was_withdrawn_with_redirect(document, redirect_path)
check_manual_document_is_unpublished_from_publishing_api(document.id, type: "redirect", alternative_path: redirect_path, discard_drafts: true)
check_manual_document_is_withdrawn_from_rummager(document)
end
def manual_document_repository(manual)
RepositoryRegistry.create.section_repository_factory.call(manual)
end
def check_manual_document_is_archived_in_db(manual, document_id)
expect(manual_document_repository(manual).fetch(document_id)).to be_withdrawn
end
def check_manual_is_published_to_rummager(slug, attrs)
expect(fake_rummager).to have_received(:add_document)
.with(
ManualIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{slug}",
hash_including(
title: attrs.fetch(:title),
link: "/#{slug}",
indexable_content: attrs.fetch(:summary),
)
).at_least(:once)
end
def check_manual_is_not_published_to_rummager(slug)
expect(fake_rummager).not_to have_received(:add_document)
.with(
ManualIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{slug}",
anything
)
end
def check_manual_is_not_published_to_rummager_with_attrs(slug, attrs)
expect(fake_rummager).not_to have_received(:add_document)
.with(
ManualIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{slug}",
hash_including(
title: attrs.fetch(:title),
link: "/#{slug}",
indexable_content: attrs.fetch(:summary),
)
)
end
def check_manual_is_drafted_to_publishing_api(content_id, extra_attributes: {}, number_of_drafts: 1, with_matcher: nil)
raise ArgumentError, "can't specify both extra_attributes and with_matcher" if with_matcher.present? && !extra_attributes.empty?
if with_matcher.nil?
attributes = {
"schema_name" => ManualPublishingAPIExporter::PUBLISHING_API_SCHEMA_NAME,
"document_type" => ManualPublishingAPIExporter::PUBLISHING_API_DOCUMENT_TYPE,
"rendering_app" => "manuals-frontend",
"publishing_app" => "manuals-publisher",
}.merge(extra_attributes)
with_matcher = request_json_including(attributes)
end
assert_publishing_api_put_content(content_id, with_matcher, number_of_drafts)
end
def check_manual_is_published_to_publishing_api(content_id, times: 1)
assert_publishing_api_publish(content_id, nil, times)
end
def check_manual_is_not_published_to_publishing_api(content_id)
assert_publishing_api_publish(content_id, nil, 0)
end
def check_draft_has_been_discarded_in_publishing_api(content_id)
assert_publishing_api_discard_draft(content_id)
end
def check_manual_document_is_drafted_to_publishing_api(content_id, extra_attributes: {}, number_of_drafts: 1, with_matcher: nil)
raise ArgumentError, "can't specify both extra_attributes and with_matcher" if with_matcher.present? && !extra_attributes.empty?
if with_matcher.nil?
attributes = {
"schema_name" => SectionPublishingAPIExporter::PUBLISHING_API_SCHEMA_NAME,
"document_type" => SectionPublishingAPIExporter::PUBLISHING_API_DOCUMENT_TYPE,
"rendering_app" => "manuals-frontend",
"publishing_app" => "manuals-publisher",
}.merge(extra_attributes)
with_matcher = request_json_including(attributes)
end
assert_publishing_api_put_content(content_id, with_matcher, number_of_drafts)
end
def check_manual_document_is_published_to_publishing_api(content_id, times: 1)
assert_publishing_api_publish(content_id, nil, times)
end
def check_manual_document_is_not_published_to_publishing_api(content_id)
assert_publishing_api_publish(content_id, nil, 0)
end
def check_manual_document_is_unpublished_from_publishing_api(content_id, unpublishing_attributes)
assert_publishing_api_unpublish(content_id, unpublishing_attributes)
end
def check_section_is_published_to_rummager(slug, attrs, manual_attrs)
expect(fake_rummager).to have_received(:add_document)
.with(
SectionIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{slug}",
hash_including(
title: "#{manual_attrs.fetch(:title)}: #{attrs.fetch(:section_title)}",
link: "/#{slug}",
indexable_content: attrs.fetch(:section_body),
)
).at_least(:once)
end
def check_section_is_not_published_to_rummager(slug)
expect(fake_rummager).not_to have_received(:add_document)
.with(
SectionIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{slug}",
anything
)
end
def check_section_is_not_published_to_rummager_with_attrs(slug, attrs, manual_attrs)
expect(fake_rummager).not_to have_received(:add_document)
.with(
SectionIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{slug}",
hash_including(
title: "#{manual_attrs.fetch(:title)}: #{attrs.fetch(:section_title)}",
link: "/#{slug}",
indexable_content: attrs.fetch(:section_body),
)
)
end
def check_for_document_body_preview(text)
within(".preview") do
expect(page).to have_css("p", text: text)
end
end
def copy_embed_code_for_attachment_and_paste_into_manual_document_body(title)
snippet = within(".attachments") do
page
.find("li", text: /#{title}/)
.find("span.snippet")
.text
end
body_text = find("#document_body").value
fill_in("Section body", with: body_text + snippet)
end
def check_change_note_value(manual_title, document_title, expected_value)
go_to_manual_page(manual_title)
click_on document_title
click_on "Edit section"
change_note_field_value = page.find("textarea[name='document[change_note]']").text
expect(change_note_field_value).to eq(expected_value)
end
def check_that_change_note_fields_are_present(note_field_only: false, minor_update: false, note: "")
unless note_field_only
expect(page).to have_field("Minor update", checked: minor_update)
expect(page).to have_field("Major update", checked: !minor_update)
# the note field is only visible for major updates, so we have to reveal it
# if we think it will be a minor update alread
choose("Major update") if minor_update
end
expect(page).to have_field("Change note", with: note)
end
def check_manual_can_be_created
@manual_fields = {
title: "Example Manual Title",
summary: "Nullam quis risus eget urna mollis ornare vel eu leo.",
}
create_manual(@manual_fields)
check_manual_exists_with(@manual_fields)
end
def check_manual_cannot_be_published
document_fields = {
section_title: "Section 1",
section_summary: "Section 1 summary",
section_body: "Section 1 body",
}
create_manual_document(@manual_fields.fetch(:title), document_fields)
go_to_manual_page(@manual_fields.fetch(:title))
expect(page).not_to have_button("Publish")
end
def change_manual_without_saving(title, fields)
go_to_edit_page_for_manual(title)
fill_in_fields(fields)
end
def check_for_manual_body_preview
expect(current_path).to match(%r{/manuals/([0-9a-f-]+|new)})
within(".preview") do
expect(page).to have_css("p", text: "Body for preview")
end
end
def check_for_clashing_section_slugs
expect(page).to have_content("Warning: There are duplicate section slugs in this manual")
end
def stub_manual_withdrawal_observers
stub_rummager
stub_publishing_api
end
def withdraw_manual_without_ui(manual)
stub_manual_withdrawal_observers
manual_services = ManualServiceRegistry.new
manual_services.withdraw(manual.id).call
end
def check_manual_is_withdrawn(manual, documents)
assert_publishing_api_unpublish(manual.id, type: "gone")
documents.each { |d| assert_publishing_api_unpublish(d.id, type: "gone") }
check_manual_is_withdrawn_from_rummager(manual, documents)
end
def check_manual_is_withdrawn_from_rummager(manual, documents)
expect(fake_rummager).to have_received(:delete_document)
.with(
ManualIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{manual.slug}",
)
documents.each do |document|
expect(fake_rummager).to have_received(:delete_document)
.with(
SectionIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{document.slug}",
)
end
end
def check_manual_document_is_withdrawn_from_rummager(document)
expect(fake_rummager).to have_received(:delete_document)
.with(
SectionIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{document.slug}",
)
end
def check_manual_has_organisation_slug(attributes, organisation_slug)
go_to_manual_page(attributes.fetch(:title))
expect(page.body).to have_content(organisation_slug)
end
def create_documents_for_manual(count:, manual_fields:)
attributes_for_documents = (1..count).map do |n|
title = "Section #{n}"
{
title: title,
slug: "guidance/example-manual-title/section-#{n}",
fields: {
section_title: title,
section_summary: "Section #{n} summary",
section_body: "Section #{n} body",
}
}
end
attributes_for_documents.each do |attributes|
create_manual_document(manual_fields.fetch(:title), attributes[:fields])
end
attributes_for_documents
end
def create_documents_for_manual_without_ui(manual:, count:)
(1..count).map do |n|
attributes = {
title: "Section #{n}",
summary: "Section #{n} summary",
body: "Section #{n} body"
}
create_manual_document_without_ui(manual, attributes)
end
end
def most_recently_created_manual
RepositoryRegistry.create.manual_repository.all.first
end
def document_fields(document)
{
section_title: document.title,
section_summary: document.summary,
section_body: document.body,
}
end
def check_document_withdraw_link_not_visible(manual, document)
# Don't give them the option...
go_to_manual_page(manual.title)
click_on document.title
expect(page).not_to have_button("Withdraw")
# ...and if they get here anyway, throw them out
visit withdraw_manual_document_path(manual, document)
expect(current_path).to eq manual_document_path(manual.id, document.id)
expect(page).to have_text("You don't have permission to withdraw manual sections.")
end
def change_notes_sent_to_publishing_api_include_document(document)
->(request) do
data = JSON.parse(request.body)
change_notes = data["details"]["change_notes"]
change_notes.detect { |change_note|
(change_note["base_path"] == "/#{document.slug}") &&
(change_note["title"] == document.title) &&
(change_note["change_note"] == document.change_note)
}.present?
end
end
def check_manual_is_drafted_and_published_with_first_published_date_only(manual, expected_date, how_many_times: 1)
# We don't use the update_type on the publish API, we fallback to what we set
# when drafting the content
check_manual_document_is_drafted_to_publishing_api(
manual.id,
with_matcher: ->(request) do
data = JSON.parse(request.body)
(data["first_published_at"] == expected_date.iso8601) &&
!data.key?("public_updated_at")
end,
number_of_drafts: how_many_times
)
check_manual_was_published(manual)
end
def check_manual_document_is_drafted_and_published_with_first_published_date_only(document, expected_date, how_many_times: 1)
# We don't use the update_type on the publish API, we fallback to what we set
# when drafting the content
check_manual_document_is_drafted_to_publishing_api(
document.id,
with_matcher: ->(request) do
data = JSON.parse(request.body)
(data["first_published_at"] == expected_date.iso8601) &&
!data.key?("public_updated_at")
end,
number_of_drafts: how_many_times
)
check_manual_document_was_published(document)
end
def check_manual_is_drafted_and_published_with_all_public_timestamps(manual, expected_date, how_many_times: 1)
# We don't use the update_type on the publish API, we fallback to what we set
# when drafting the content
check_manual_document_is_drafted_to_publishing_api(
manual.id,
with_matcher: ->(request) do
data = JSON.parse(request.body)
(data["first_published_at"] == expected_date.iso8601) &&
(data["public_updated_at"] == expected_date.iso8601)
end,
number_of_drafts: how_many_times
)
check_manual_was_published(manual)
end
def check_manual_document_is_drafted_and_published_with_all_public_timestamps(document, expected_date, how_many_times: 1)
# We don't use the update_type on the publish API, we fallback to what we set
# when drafting the content
check_manual_document_is_drafted_to_publishing_api(
document.id,
with_matcher: ->(request) do
data = JSON.parse(request.body)
(data["first_published_at"] == expected_date.iso8601) &&
(data["public_updated_at"] == expected_date.iso8601)
end,
number_of_drafts: how_many_times
)
check_manual_document_was_published(document)
end
def check_manual_is_drafted_and_published_with_no_public_timestamps(manual, how_many_times: 1)
# We don't use the update_type on the publish API, we fallback to what we set
# when drafting the content
check_manual_document_is_drafted_to_publishing_api(
manual.id,
with_matcher: ->(request) do
data = JSON.parse(request.body)
!data.key?("first_published_at") &&
!data.key?("public_updated_at")
end,
number_of_drafts: how_many_times
)
check_manual_was_published(manual)
end
def check_manual_document_is_drafted_and_published_with_no_public_timestamps(document, how_many_times: 1)
# We don't use the update_type on the publish API, we fallback to what we set
# when drafting the content
check_manual_document_is_drafted_to_publishing_api(
document.id,
with_matcher: ->(request) do
data = JSON.parse(request.body)
!data.key?("first_published_at") &&
!data.key?("public_updated_at")
end,
number_of_drafts: how_many_times
)
check_manual_document_was_published(document)
end
end
RSpec.configuration.include ManualHelpers, type: :feature
Remove unused manual spec helper
The
`check_manual_document_is_drafted_and_published_with_all_public_timestamps`
helper does not appear to be used anywhere.
module ManualHelpers
def manual_repository
RepositoryRegistry.create.manual_repository
end
def create_manual(fields, save: true)
visit new_manual_path
fill_in_fields(fields)
yield if block_given?
save_as_draft if save
end
def create_manual_without_ui(fields, organisation_slug: "ministry-of-tea")
stub_organisation_details(organisation_slug)
manual_services = OrganisationalManualServiceRegistry.new(
organisation_slug: organisation_slug,
)
manual = manual_services.create(
fields.merge(organisation_slug: organisation_slug),
).call
manual_repository.fetch(manual.id)
end
def create_manual_document(manual_title, fields)
go_to_manual_page(manual_title)
click_on "Add section"
fill_in_fields(fields)
yield if block_given?
save_as_draft
end
def create_manual_document_without_ui(manual, fields, organisation_slug: "ministry-of-tea")
manual_document_services = OrganisationalSectionServiceRegistry.new(
organisation_slug: organisation_slug,
)
create_service_context = OpenStruct.new(
params: {
"manual_id" => manual.id,
"document" => fields,
}
)
_, document = manual_document_services.create(create_service_context).call
document
end
def edit_manual(manual_title, new_fields)
go_to_edit_page_for_manual(manual_title)
fill_in_fields(new_fields)
yield if block_given?
save_as_draft
end
def edit_manual_without_ui(manual, fields, organisation_slug: "ministry-of-tea")
stub_organisation_details(organisation_slug)
manual_services = OrganisationalManualServiceRegistry.new(
organisation_slug: organisation_slug,
)
manual = manual_services.update(
manual.id,
fields.merge(organisation_slug: organisation_slug),
).call
manual
end
def edit_manual_document(manual_title, section_title, new_fields)
go_to_manual_page(manual_title)
click_on section_title
click_on "Edit"
fill_in_fields(new_fields)
yield if block_given?
save_as_draft
end
def edit_manual_document_without_ui(manual, document, fields, organisation_slug: "ministry-of-tea")
manual_document_services = OrganisationalSectionServiceRegistry.new(
organisation_slug: organisation_slug,
)
service_context = OpenStruct.new(
params: {
"manual_id" => manual.id,
"id" => document.id,
"document" => fields,
}
)
_, document = manual_document_services.update(service_context).call
document
end
def edit_manual_original_publication_date(manual_title)
go_to_manual_page(manual_title)
click_on("Edit first publication date")
yield if block_given?
save_as_draft
end
def withdraw_manual_document(manual_title, section_title, change_note: nil, minor_update: true)
go_to_manual_page(manual_title)
click_on section_title
click_on "Withdraw"
fill_in "Change note", with: change_note unless change_note.blank?
if minor_update
choose "Minor update"
end
click_on "Yes"
end
def save_as_draft
click_on "Save as draft"
end
def publish_manual
click_on "Publish manual"
end
def stub_manual_publication_observers(organisation_slug)
stub_rummager
stub_publishing_api
stub_organisation_details(organisation_slug)
end
def publish_manual_without_ui(manual, organisation_slug: "ministry-of-tea")
stub_manual_publication_observers(organisation_slug)
manual_services = ManualServiceRegistry.new
manual_services.publish(manual.id, manual.version_number).call
end
def check_manual_exists_with(attributes)
go_to_manual_page(attributes.fetch(:title))
expect(page).to have_content(attributes.fetch(:summary))
end
def check_manual_does_not_exist_with(attributes)
visit manuals_path
expect(page).not_to have_content(attributes.fetch(:title))
end
def check_manual_document_exists_with(manual_title, attributes)
go_to_manual_page(manual_title)
click_on(attributes.fetch(:section_title))
attributes.values.each do |attr_val|
expect(page).to have_content(attr_val)
end
end
def check_section_exists(manual_id, section_id)
manual = manual_repository.fetch(manual_id)
manual.documents.any? { |document| document.id == section_id }
end
def check_section_was_removed(manual_id, section_id)
manual = manual_repository.fetch(manual_id)
manual.removed_documents.any? { |document| document.id == section_id }
end
def go_to_edit_page_for_manual(manual_title)
go_to_manual_page(manual_title)
click_on("Edit manual")
end
def check_for_errors_for_fields(field)
expect(page).to have_content("#{field.titlecase} can't be blank")
end
def check_content_preview_link(slug)
preview_url = "#{Plek.current.find('draft-origin')}/#{slug}"
expect(page).to have_link("Preview draft", href: preview_url)
end
def check_live_link(slug)
live_url = "#{Plek.current.website_root}/#{slug}"
expect(page).to have_link("View on website", href: live_url)
end
def go_to_manual_page(manual_title)
visit manuals_path
click_link manual_title
end
def check_manual_and_documents_were_published(manual, document, manual_attrs, document_attrs)
check_manual_is_published_to_publishing_api(manual.id)
check_manual_document_is_published_to_publishing_api(document.id)
check_manual_is_published_to_rummager(manual.slug, manual_attrs)
check_section_is_published_to_rummager(document.slug, document_attrs, manual_attrs)
end
def check_manual_was_published(manual)
check_manual_is_published_to_publishing_api(manual.id)
end
def check_manual_was_not_published(manual)
check_manual_is_not_published_to_publishing_api(manual.id)
end
def check_manual_document_was_published(document)
check_manual_document_is_published_to_publishing_api(document.id)
end
def check_manual_document_was_not_published(document)
check_manual_document_is_not_published_to_publishing_api(document.id)
end
def check_manual_document_was_withdrawn_with_redirect(document, redirect_path)
check_manual_document_is_unpublished_from_publishing_api(document.id, type: "redirect", alternative_path: redirect_path, discard_drafts: true)
check_manual_document_is_withdrawn_from_rummager(document)
end
def manual_document_repository(manual)
RepositoryRegistry.create.section_repository_factory.call(manual)
end
def check_manual_document_is_archived_in_db(manual, document_id)
expect(manual_document_repository(manual).fetch(document_id)).to be_withdrawn
end
def check_manual_is_published_to_rummager(slug, attrs)
expect(fake_rummager).to have_received(:add_document)
.with(
ManualIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{slug}",
hash_including(
title: attrs.fetch(:title),
link: "/#{slug}",
indexable_content: attrs.fetch(:summary),
)
).at_least(:once)
end
def check_manual_is_not_published_to_rummager(slug)
expect(fake_rummager).not_to have_received(:add_document)
.with(
ManualIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{slug}",
anything
)
end
def check_manual_is_not_published_to_rummager_with_attrs(slug, attrs)
expect(fake_rummager).not_to have_received(:add_document)
.with(
ManualIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{slug}",
hash_including(
title: attrs.fetch(:title),
link: "/#{slug}",
indexable_content: attrs.fetch(:summary),
)
)
end
def check_manual_is_drafted_to_publishing_api(content_id, extra_attributes: {}, number_of_drafts: 1, with_matcher: nil)
raise ArgumentError, "can't specify both extra_attributes and with_matcher" if with_matcher.present? && !extra_attributes.empty?
if with_matcher.nil?
attributes = {
"schema_name" => ManualPublishingAPIExporter::PUBLISHING_API_SCHEMA_NAME,
"document_type" => ManualPublishingAPIExporter::PUBLISHING_API_DOCUMENT_TYPE,
"rendering_app" => "manuals-frontend",
"publishing_app" => "manuals-publisher",
}.merge(extra_attributes)
with_matcher = request_json_including(attributes)
end
assert_publishing_api_put_content(content_id, with_matcher, number_of_drafts)
end
def check_manual_is_published_to_publishing_api(content_id, times: 1)
assert_publishing_api_publish(content_id, nil, times)
end
def check_manual_is_not_published_to_publishing_api(content_id)
assert_publishing_api_publish(content_id, nil, 0)
end
def check_draft_has_been_discarded_in_publishing_api(content_id)
assert_publishing_api_discard_draft(content_id)
end
def check_manual_document_is_drafted_to_publishing_api(content_id, extra_attributes: {}, number_of_drafts: 1, with_matcher: nil)
raise ArgumentError, "can't specify both extra_attributes and with_matcher" if with_matcher.present? && !extra_attributes.empty?
if with_matcher.nil?
attributes = {
"schema_name" => SectionPublishingAPIExporter::PUBLISHING_API_SCHEMA_NAME,
"document_type" => SectionPublishingAPIExporter::PUBLISHING_API_DOCUMENT_TYPE,
"rendering_app" => "manuals-frontend",
"publishing_app" => "manuals-publisher",
}.merge(extra_attributes)
with_matcher = request_json_including(attributes)
end
assert_publishing_api_put_content(content_id, with_matcher, number_of_drafts)
end
def check_manual_document_is_published_to_publishing_api(content_id, times: 1)
assert_publishing_api_publish(content_id, nil, times)
end
def check_manual_document_is_not_published_to_publishing_api(content_id)
assert_publishing_api_publish(content_id, nil, 0)
end
def check_manual_document_is_unpublished_from_publishing_api(content_id, unpublishing_attributes)
assert_publishing_api_unpublish(content_id, unpublishing_attributes)
end
def check_section_is_published_to_rummager(slug, attrs, manual_attrs)
expect(fake_rummager).to have_received(:add_document)
.with(
SectionIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{slug}",
hash_including(
title: "#{manual_attrs.fetch(:title)}: #{attrs.fetch(:section_title)}",
link: "/#{slug}",
indexable_content: attrs.fetch(:section_body),
)
).at_least(:once)
end
def check_section_is_not_published_to_rummager(slug)
expect(fake_rummager).not_to have_received(:add_document)
.with(
SectionIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{slug}",
anything
)
end
def check_section_is_not_published_to_rummager_with_attrs(slug, attrs, manual_attrs)
expect(fake_rummager).not_to have_received(:add_document)
.with(
SectionIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{slug}",
hash_including(
title: "#{manual_attrs.fetch(:title)}: #{attrs.fetch(:section_title)}",
link: "/#{slug}",
indexable_content: attrs.fetch(:section_body),
)
)
end
def check_for_document_body_preview(text)
within(".preview") do
expect(page).to have_css("p", text: text)
end
end
def copy_embed_code_for_attachment_and_paste_into_manual_document_body(title)
snippet = within(".attachments") do
page
.find("li", text: /#{title}/)
.find("span.snippet")
.text
end
body_text = find("#document_body").value
fill_in("Section body", with: body_text + snippet)
end
def check_change_note_value(manual_title, document_title, expected_value)
go_to_manual_page(manual_title)
click_on document_title
click_on "Edit section"
change_note_field_value = page.find("textarea[name='document[change_note]']").text
expect(change_note_field_value).to eq(expected_value)
end
def check_that_change_note_fields_are_present(note_field_only: false, minor_update: false, note: "")
unless note_field_only
expect(page).to have_field("Minor update", checked: minor_update)
expect(page).to have_field("Major update", checked: !minor_update)
# the note field is only visible for major updates, so we have to reveal it
# if we think it will be a minor update alread
choose("Major update") if minor_update
end
expect(page).to have_field("Change note", with: note)
end
def check_manual_can_be_created
@manual_fields = {
title: "Example Manual Title",
summary: "Nullam quis risus eget urna mollis ornare vel eu leo.",
}
create_manual(@manual_fields)
check_manual_exists_with(@manual_fields)
end
def check_manual_cannot_be_published
document_fields = {
section_title: "Section 1",
section_summary: "Section 1 summary",
section_body: "Section 1 body",
}
create_manual_document(@manual_fields.fetch(:title), document_fields)
go_to_manual_page(@manual_fields.fetch(:title))
expect(page).not_to have_button("Publish")
end
def change_manual_without_saving(title, fields)
go_to_edit_page_for_manual(title)
fill_in_fields(fields)
end
def check_for_manual_body_preview
expect(current_path).to match(%r{/manuals/([0-9a-f-]+|new)})
within(".preview") do
expect(page).to have_css("p", text: "Body for preview")
end
end
def check_for_clashing_section_slugs
expect(page).to have_content("Warning: There are duplicate section slugs in this manual")
end
def stub_manual_withdrawal_observers
stub_rummager
stub_publishing_api
end
def withdraw_manual_without_ui(manual)
stub_manual_withdrawal_observers
manual_services = ManualServiceRegistry.new
manual_services.withdraw(manual.id).call
end
def check_manual_is_withdrawn(manual, documents)
assert_publishing_api_unpublish(manual.id, type: "gone")
documents.each { |d| assert_publishing_api_unpublish(d.id, type: "gone") }
check_manual_is_withdrawn_from_rummager(manual, documents)
end
def check_manual_is_withdrawn_from_rummager(manual, documents)
expect(fake_rummager).to have_received(:delete_document)
.with(
ManualIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{manual.slug}",
)
documents.each do |document|
expect(fake_rummager).to have_received(:delete_document)
.with(
SectionIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{document.slug}",
)
end
end
def check_manual_document_is_withdrawn_from_rummager(document)
expect(fake_rummager).to have_received(:delete_document)
.with(
SectionIndexableFormatter::RUMMAGER_DOCUMENT_TYPE,
"/#{document.slug}",
)
end
def check_manual_has_organisation_slug(attributes, organisation_slug)
go_to_manual_page(attributes.fetch(:title))
expect(page.body).to have_content(organisation_slug)
end
def create_documents_for_manual(count:, manual_fields:)
attributes_for_documents = (1..count).map do |n|
title = "Section #{n}"
{
title: title,
slug: "guidance/example-manual-title/section-#{n}",
fields: {
section_title: title,
section_summary: "Section #{n} summary",
section_body: "Section #{n} body",
}
}
end
attributes_for_documents.each do |attributes|
create_manual_document(manual_fields.fetch(:title), attributes[:fields])
end
attributes_for_documents
end
def create_documents_for_manual_without_ui(manual:, count:)
(1..count).map do |n|
attributes = {
title: "Section #{n}",
summary: "Section #{n} summary",
body: "Section #{n} body"
}
create_manual_document_without_ui(manual, attributes)
end
end
def most_recently_created_manual
RepositoryRegistry.create.manual_repository.all.first
end
def document_fields(document)
{
section_title: document.title,
section_summary: document.summary,
section_body: document.body,
}
end
def check_document_withdraw_link_not_visible(manual, document)
# Don't give them the option...
go_to_manual_page(manual.title)
click_on document.title
expect(page).not_to have_button("Withdraw")
# ...and if they get here anyway, throw them out
visit withdraw_manual_document_path(manual, document)
expect(current_path).to eq manual_document_path(manual.id, document.id)
expect(page).to have_text("You don't have permission to withdraw manual sections.")
end
def change_notes_sent_to_publishing_api_include_document(document)
->(request) do
data = JSON.parse(request.body)
change_notes = data["details"]["change_notes"]
change_notes.detect { |change_note|
(change_note["base_path"] == "/#{document.slug}") &&
(change_note["title"] == document.title) &&
(change_note["change_note"] == document.change_note)
}.present?
end
end
def check_manual_is_drafted_and_published_with_first_published_date_only(manual, expected_date, how_many_times: 1)
# We don't use the update_type on the publish API, we fallback to what we set
# when drafting the content
check_manual_document_is_drafted_to_publishing_api(
manual.id,
with_matcher: ->(request) do
data = JSON.parse(request.body)
(data["first_published_at"] == expected_date.iso8601) &&
!data.key?("public_updated_at")
end,
number_of_drafts: how_many_times
)
check_manual_was_published(manual)
end
def check_manual_document_is_drafted_and_published_with_first_published_date_only(document, expected_date, how_many_times: 1)
# We don't use the update_type on the publish API, we fallback to what we set
# when drafting the content
check_manual_document_is_drafted_to_publishing_api(
document.id,
with_matcher: ->(request) do
data = JSON.parse(request.body)
(data["first_published_at"] == expected_date.iso8601) &&
!data.key?("public_updated_at")
end,
number_of_drafts: how_many_times
)
check_manual_document_was_published(document)
end
def check_manual_is_drafted_and_published_with_all_public_timestamps(manual, expected_date, how_many_times: 1)
# We don't use the update_type on the publish API, we fallback to what we set
# when drafting the content
check_manual_document_is_drafted_to_publishing_api(
manual.id,
with_matcher: ->(request) do
data = JSON.parse(request.body)
(data["first_published_at"] == expected_date.iso8601) &&
(data["public_updated_at"] == expected_date.iso8601)
end,
number_of_drafts: how_many_times
)
check_manual_was_published(manual)
end
def check_manual_document_is_drafted_and_published_with_all_public_timestamps(document, expected_date, how_many_times: 1)
# We don't use the update_type on the publish API, we fallback to what we set
# when drafting the content
check_manual_document_is_drafted_to_publishing_api(
document.id,
with_matcher: ->(request) do
data = JSON.parse(request.body)
(data["first_published_at"] == expected_date.iso8601) &&
(data["public_updated_at"] == expected_date.iso8601)
end,
number_of_drafts: how_many_times
)
check_manual_document_was_published(document)
end
def check_manual_is_drafted_and_published_with_no_public_timestamps(manual, how_many_times: 1)
# We don't use the update_type on the publish API, we fallback to what we set
# when drafting the content
check_manual_document_is_drafted_to_publishing_api(
manual.id,
with_matcher: ->(request) do
data = JSON.parse(request.body)
!data.key?("first_published_at") &&
!data.key?("public_updated_at")
end,
number_of_drafts: how_many_times
)
check_manual_was_published(manual)
end
end
RSpec.configuration.include ManualHelpers, type: :feature
|
# snapshot books
Before do |scenario|
#take a snapshot
step "I take a snapshot \"#{short_name(scenario.name)}\""
end
After do |scenario|
#take a snapshot if the scenario fails
name = short_name(scenario.name)
if(scenario.failed?)
step "I take a snapshot \"#{name}_failed\""
else
#nothing happened, delete snapshot as we dont need it
$sshout = ""
$sshout = `echo | ssh root@$VHOST rm -f $IMGDIR/#{name}.qcow2`
raise "Failed to remove snapshot" unless $?.success?
end
end
def short_name(name)
name.downcase.delete('^a-zA-z0-9 ').tr(' ','_').slice(0..35)
end
made snapshots optional if $VHOST is not set
# snapshot books
Before do |scenario|
#take a snapshot
if ENV['VHOST']
step "I take a snapshot \"#{short_name(scenario.name)}\""
end
end
After do |scenario|
#take a snapshot if the scenario fails
if ENV['VHOST']
name = short_name(scenario.name)
if(scenario.failed?)
step "I take a snapshot \"#{name}_failed\""
else
#nothing happened, delete snapshot as we dont need it
$sshout = ""
$sshout = `echo | ssh root@$VHOST rm -f $IMGDIR/#{name}.qcow2`
raise "Failed to remove snapshot" unless $?.success?
end
end
end
def short_name(name)
name.downcase.delete('^a-zA-z0-9 ').tr(' ','_').slice(0..35)
end
|
# Where's autoloader when we need it
require_relative "condition/condition"
require_relative "condition/condition_simple"
require_relative "condition/condition_format"
require_relative "condition/condition_print"
require_relative "condition/condition_regexp"
Dir["#{__dir__}/condition/condition_*.rb"].sort.each do |path| require_relative path end
require_relative "query_tokenizer"
class QueryParser
def parse(query_string)
str = query_string.strip
if str =~ /\A(\+\+)?!(.*)\z/
if $1 == "++"
metadata = {ungrouped: true}
else
metadata = {}
end
name = $2
# These cards need special treatment:
# * "Ach! Hans, Run!"
# * Look at Me, I'm R&D
# * R&D's Secret Lair
unless name =~ /Ach.*Hans.*Run/
name = name.sub(/\A"(.*)"\z/) { $1 }
end
if name =~ %r[&|/] && name !~ /R&D/
cond = ConditionExactMultipart.new(name)
else
cond = ConditionExact.new(name)
end
[cond, metadata, []]
else
@tokens, @warnings = QueryTokenizer.new.tokenize(str)
@metadata = {}
query = parse_query
[query, @metadata, @warnings]
end
end
private
def conds_to_query(conds)
if conds.empty?
nil
elsif conds.size == 1
conds[0]
else
ConditionAnd.new(*conds)
end
end
def parse_query
old_time, @time = @time, nil
cond = parse_cond_list
if @time
printed_early = ConditionPrint.new("<=", @time)
cond = conds_to_query([cond, printed_early])
cond.metadata! :time, @time
cond
else
cond
end
ensure
@time = old_time
end
def parse_cond_list
conds = []
until @tokens.empty?
case @tokens[0][0]
when :close
# Do not eat token
break
when :or
@tokens.shift
# This is optimization,
# Condition.new(:or, [conds, right_conds])
# would work just as well
if conds.empty?
# Ignore
else
right_query = parse_cond_list
if right_query
return ConditionOr.new(conds_to_query(conds), right_query)
else
break
end
end
when :slash_slash
@tokens.shift
# This is semantically meaningful
left_query = conds_to_query(conds)
right_query = parse_cond_list
if left_query and right_query
return ConditionPart.new(ConditionAnd.new(left_query, ConditionOther.new(right_query)))
else
query = left_query || right_query
if query
return ConditionPart.new(query)
else
return ConditionIsMultipart.new
end
end
# includes open / not
else
subquery = parse_cond
if subquery
conds << subquery
else
break
end
end
end
conds_to_query(conds)
end
def parse_cond
return nil if @tokens.empty?
case @tokens[0][0]
when :open
@tokens.shift
subquery = parse_query
@tokens.shift if @tokens[0] == [:close] # Ignore mismatched
subquery
when :close
return
when :not, :other, :part, :related, :alt
tok, = @tokens.shift
cond = parse_cond
if cond
klass = Kernel.const_get("Condition#{tok.capitalize}")
klass.new(cond)
else
# Parse error like "-)" or final "-"
nil
end
when :or
# Parse error like "- or"
@tokens.shift
parse_cond
when :test
@tokens.shift[1]
when :metadata
# Quietly eat it
@metadata.merge!(@tokens.shift[1])
parse_cond
when :time
# Quietly eat it, for now
@warnings << "Multiple time: clauses in same subquery" if @time
@time = @tokens.shift[1]
parse_cond
else
@warnings << "Unknown token type #{@tokens[0]}"
end
end
end
Assume current date unless specified otherwise
# Where's autoloader when we need it
require_relative "condition/condition"
require_relative "condition/condition_simple"
require_relative "condition/condition_format"
require_relative "condition/condition_print"
require_relative "condition/condition_regexp"
Dir["#{__dir__}/condition/condition_*.rb"].sort.each do |path| require_relative path end
require_relative "query_tokenizer"
class QueryParser
def parse(query_string)
str = query_string.strip
if str =~ /\A(\+\+)?!(.*)\z/
if $1 == "++"
metadata = {ungrouped: true}
else
metadata = {}
end
name = $2
# These cards need special treatment:
# * "Ach! Hans, Run!"
# * Look at Me, I'm R&D
# * R&D's Secret Lair
unless name =~ /Ach.*Hans.*Run/
name = name.sub(/\A"(.*)"\z/) { $1 }
end
if name =~ %r[&|/] && name !~ /R&D/
cond = ConditionExactMultipart.new(name)
else
cond = ConditionExact.new(name)
end
[cond, metadata, []]
else
@tokens, @warnings = QueryTokenizer.new.tokenize(str)
@metadata = {}
query = parse_query
[query, @metadata, @warnings]
end
end
private
def conds_to_query(conds)
if conds.empty?
nil
elsif conds.size == 1
conds[0]
else
ConditionAnd.new(*conds)
end
end
def parse_query
old_time, @time = @time, Date.today
cond = parse_cond_list
if @time
printed_early = ConditionPrint.new("<=", @time)
cond = conds_to_query([cond, printed_early])
cond.metadata! :time, @time
cond
else
cond
end
ensure
@time = old_time
end
def parse_cond_list
conds = []
until @tokens.empty?
case @tokens[0][0]
when :close
# Do not eat token
break
when :or
@tokens.shift
# This is optimization,
# Condition.new(:or, [conds, right_conds])
# would work just as well
if conds.empty?
# Ignore
else
right_query = parse_cond_list
if right_query
return ConditionOr.new(conds_to_query(conds), right_query)
else
break
end
end
when :slash_slash
@tokens.shift
# This is semantically meaningful
left_query = conds_to_query(conds)
right_query = parse_cond_list
if left_query and right_query
return ConditionPart.new(ConditionAnd.new(left_query, ConditionOther.new(right_query)))
else
query = left_query || right_query
if query
return ConditionPart.new(query)
else
return ConditionIsMultipart.new
end
end
# includes open / not
else
subquery = parse_cond
if subquery
conds << subquery
else
break
end
end
end
conds_to_query(conds)
end
def parse_cond
return nil if @tokens.empty?
case @tokens[0][0]
when :open
@tokens.shift
subquery = parse_query
@tokens.shift if @tokens[0] == [:close] # Ignore mismatched
subquery
when :close
return
when :not, :other, :part, :related, :alt
tok, = @tokens.shift
cond = parse_cond
if cond
klass = Kernel.const_get("Condition#{tok.capitalize}")
klass.new(cond)
else
# Parse error like "-)" or final "-"
nil
end
when :or
# Parse error like "- or"
@tokens.shift
parse_cond
when :test
@tokens.shift[1]
when :metadata
# Quietly eat it
@metadata.merge!(@tokens.shift[1])
parse_cond
when :time
# Quietly eat it, for now
@warnings << "Multiple time: clauses in same subquery" if @time
@time = @tokens.shift[1]
parse_cond
else
@warnings << "Unknown token type #{@tokens[0]}"
end
end
end
|
class FirstController < UIViewController
def viewDidLoad
@typewriter = TypewriterView.alloc.initWithFrame([[0, 0], [320, 480]])
@typewriter.backgroundColor = UIColor.darkGrayColor
@typewriter.margin = 8
@typewriter.spacing = 4
@typewriter.min_width = 40
@typewriter.min_height = 40
self.view.addSubview(@typewriter)
96.times do
width = (rand() * 30).to_i + 10 # between 10 and 40
height = (rand() * 50).to_i + 10 # between 10 and 60
the_view = UIView.alloc.initWithFrame([[0, 0], [width, height]])
red = rand
green = rand
blue = rand
the_view.backgroundColor = UIColor.colorWithRed(red, green:green, blue:blue, alpha:1)
@typewriter.addSubview(the_view)
end
end
def shouldAutorotateToInterfaceOrientation(orientation)
true
end
def willAnimateRotationToInterfaceOrientation(orientation, duration:duration)
bframe = @typewriter.frame
w, h = bframe.size.width, bframe.size.height
bframe.size = h, w
@typewriter.frame = bframe
@typewriter.setNeedsLayout
end
end
orientation-specific
class FirstController < UIViewController
def viewDidLoad
@typewriter = TypewriterView.alloc.initWithFrame([[0, 0], [320, 480]])
@typewriter.backgroundColor = UIColor.darkGrayColor
style_portrait
self.view.addSubview(@typewriter)
96.times do
width = (rand() * 30).to_i + 10 # between 10 and 40
height = (rand() * 50).to_i + 10 # between 10 and 60
the_view = UIView.alloc.initWithFrame([[0, 0], [width, height]])
red = rand
green = rand
blue = rand
the_view.backgroundColor = UIColor.colorWithRed(red, green:green, blue:blue, alpha:1)
@typewriter.addSubview(the_view)
end
end
def style_portrait
@typewriter.margin = 8
@typewriter.spacing = 4
@typewriter.min_width = 40
@typewriter.min_height = 40
end
def style_landscape
@typewriter.margin = 13
@typewriter.spacing = 6
@typewriter.min_width = 40
@typewriter.min_height = 40
end
def shouldAutorotateToInterfaceOrientation(orientation)
true
end
def willAnimateRotationToInterfaceOrientation(orientation, duration:duration)
bframe = @typewriter.frame
w, h = bframe.size.width, bframe.size.height
bframe.size = h, w
@typewriter.frame = bframe
if orientation == UIInterfaceOrientationPortrait or orientation == UIInterfaceOrientationPortraitUpsideDown
style_portrait
else
style_landscape
end
@typewriter.setNeedsLayout
end
end
|
#!/usr/bin/env ruby
require 'mysql2'
require 'net/smtp'
require 'erb'
require 'ostruct'
require 'set'
email_tmpl = File.open('email.erb').read
mysql = Mysql2::Client.new(:host => "dutihr",
:username => ARGV[1],
:password => ARGV[2],
:database => "ghtorrent")
if ARGV[0].nil?
puts 'A list of repositories is required'
exit(1)
end
@used_email_addresses = SortedSet.new
@num_send = 0
def q_top_mergers(owner, repo)
"select u1.login as login, u1.name as name, u1.company as company,
u1.email as email, count(*) as count
from pull_requests pr, projects p, users u,
pull_request_history prh, users u1
where pr.id = prh.pull_request_id
and u.id = p.owner_id
and prh.action='merged'
and prh.actor_id = u1.id
and pr.base_repo_id = p.id
<<<<<<< Updated upstream
and year(prh.created_at) = 2013
and p.name = '#{repo}'
and u.login = '#{owner}'
=======
and p.name = '#{owner}'
and u.login = '#{repo}'
>>>>>>> Stashed changes
group by u1.id
order by count(*) desc
limit 10"
end
def q_top_submitters(owner, repo)
"select u1.login as login, u1.name as name, u1.company as company,
u1.email as email, count(*) as count
from pull_requests pr, projects p, users u,
pull_request_history prh, users u1
where pr.id = prh.pull_request_id
and u.id = p.owner_id
and prh.action='opened'
and prh.actor_id = u1.id
and pr.base_repo_id = p.id
and year(prh.created_at) = 2013
and p.name = '#{repo}'
and u.login = '#{owner}'
group by u1.id
order by count(*) desc
limit 10"
end
def render_erb(template, locals)
ERB.new(template).result(OpenStruct.new(locals).instance_eval { binding })
end
def send_spam(db, tmpl, owner, repo)
top_mergers = db.query(q_top_mergers(owner, repo), :symbolize_keys => true)
top_submitters = db.query(q_top_submitters(owner, repo), :symbolize_keys => true)
top_mergers.to_a.reverse[0..1].each do |m|
if m[:email].nil? or @used_email_addresses.include? m[:email]
next
end
email = render_erb(tmpl, :name => m[:name], :email => m[:email], :login => m[:login],
:role => 'integrators', :repo => "#{owner}/#{repo}",
:link => 'https://www.surveymonkey.com/s/pullreq-handlers',
:perflink => "http://ghtorrent.org/pullreq-perf/#{owner}-#{repo}/")
Net::SMTP.start('localhost', 25, 'ghtorrent.org') do |smtp|
begin
smtp.send_message(email, 'Georgios Gousios <G.Gousios@tudelft.nl>',
m[:email])
puts "Sent email to #{m[:email]}, merger at #{owner}/#{repo}, sent #{@num_send}"
rescue
puts "Cannot send email to #{m[:email]}"
end
@num_send += 1
end
@used_email_addresses << m[:email]
end
top_submitters.to_a.reverse[0..1].each do |m|
if m[:email].nil? or @used_email_addresses.include? m[:email]
next
end
email = render_erb(tmpl, :name => m[:name], :email => m[:email], :login => m[:login],
:role => 'integrators', :repo => "#{owner}/#{repo}",
:link => 'https://www.surveymonkey.com/s/pullreqs-contrib',
:perflink => "http://ghtorrent.org/pullreq-perf/#{owner}-#{repo}/")
Net::SMTP.start('localhost', 25, 'ghtorrent.org') do |smtp|
begin
smtp.send_message(email, 'Georgios Gousios <G.Gousios@tudelft.nl>',
m[:email])
puts "Sent email to #{m[:email]}, merger at #{owner}/#{repo}, sent #{@num_send}"
rescue
puts "Cannot send email to #{m[:email]}"
end
@num_send += 1
end
@used_email_addresses << m[:email]
end
end
if File.exists? 'used-emails.txt'
File.open("used-emails.txt").each do |line|
@used_email_addresses << line.strip
end
end
File.open(ARGV[0]).each do |line|
owner, repo = line.split(/ /)
if @num_send > 100
break
end
send_spam(mysql, email_tmpl, owner.strip, repo.strip)
end
File.open("used-emails.txt", 'w+') do |f|
@used_email_addresses.each do |email|
f.write("#{email}\n")
end
end
Resolve conflict
#!/usr/bin/env ruby
require 'mysql2'
require 'net/smtp'
require 'erb'
require 'ostruct'
require 'set'
email_tmpl = File.open('email.erb').read
mysql = Mysql2::Client.new(:host => "dutihr",
:username => ARGV[1],
:password => ARGV[2],
:database => "ghtorrent")
if ARGV[0].nil?
puts 'A list of repositories is required'
exit(1)
end
@used_email_addresses = SortedSet.new
@num_send = 0
def q_top_mergers(owner, repo)
"select u1.login as login, u1.name as name, u1.company as company,
u1.email as email, count(*) as count
from pull_requests pr, projects p, users u,
pull_request_history prh, users u1
where pr.id = prh.pull_request_id
and u.id = p.owner_id
and prh.action='merged'
and prh.actor_id = u1.id
and pr.base_repo_id = p.id
and year(prh.created_at) = 2013
and p.name = '#{repo}'
and u.login = '#{owner}'
group by u1.id
order by count(*) desc
limit 10"
end
def q_top_submitters(owner, repo)
"select u1.login as login, u1.name as name, u1.company as company,
u1.email as email, count(*) as count
from pull_requests pr, projects p, users u,
pull_request_history prh, users u1
where pr.id = prh.pull_request_id
and u.id = p.owner_id
and prh.action='opened'
and prh.actor_id = u1.id
and pr.base_repo_id = p.id
and year(prh.created_at) = 2013
and p.name = '#{repo}'
and u.login = '#{owner}'
group by u1.id
order by count(*) desc
limit 10"
end
def render_erb(template, locals)
ERB.new(template).result(OpenStruct.new(locals).instance_eval { binding })
end
def send_spam(db, tmpl, owner, repo)
top_mergers = db.query(q_top_mergers(owner, repo), :symbolize_keys => true)
top_submitters = db.query(q_top_submitters(owner, repo), :symbolize_keys => true)
top_mergers.to_a.reverse[0..1].each do |m|
if m[:email].nil? or @used_email_addresses.include? m[:email]
next
end
email = render_erb(tmpl, :name => m[:name], :email => m[:email], :login => m[:login],
:role => 'integrators', :repo => "#{owner}/#{repo}",
:link => 'https://www.surveymonkey.com/s/pullreq-handlers',
:perflink => "http://ghtorrent.org/pullreq-perf/#{owner}-#{repo}/")
Net::SMTP.start('localhost', 25, 'ghtorrent.org') do |smtp|
begin
smtp.send_message(email, 'Georgios Gousios <G.Gousios@tudelft.nl>',
m[:email])
puts "Sent email to #{m[:email]}, merger at #{owner}/#{repo}, sent #{@num_send}"
rescue
puts "Cannot send email to #{m[:email]}"
end
@num_send += 1
end
@used_email_addresses << m[:email]
end
top_submitters.to_a.reverse[0..1].each do |m|
if m[:email].nil? or @used_email_addresses.include? m[:email]
next
end
email = render_erb(tmpl, :name => m[:name], :email => m[:email], :login => m[:login],
:role => 'integrators', :repo => "#{owner}/#{repo}",
:link => 'https://www.surveymonkey.com/s/pullreqs-contrib',
:perflink => "http://ghtorrent.org/pullreq-perf/#{owner}-#{repo}/")
Net::SMTP.start('localhost', 25, 'ghtorrent.org') do |smtp|
begin
smtp.send_message(email, 'Georgios Gousios <G.Gousios@tudelft.nl>',
m[:email])
puts "Sent email to #{m[:email]}, merger at #{owner}/#{repo}, sent #{@num_send}"
rescue
puts "Cannot send email to #{m[:email]}"
end
@num_send += 1
end
@used_email_addresses << m[:email]
end
end
if File.exists? 'used-emails.txt'
File.open("used-emails.txt").each do |line|
@used_email_addresses << line.strip
end
end
File.open(ARGV[0]).each do |line|
owner, repo = line.split(/ /)
if @num_send > 100
break
end
send_spam(mysql, email_tmpl, owner.strip, repo.strip)
end
File.open("used-emails.txt", 'w+') do |f|
@used_email_addresses.each do |email|
f.write("#{email}\n")
end
end
|
# typed: false
RSpec::Support.require_rspec_support "ruby_features"
module RSpec
# Consistent implementation for "cleaning" the caller method to strip out
# non-rspec lines. This enables errors to be reported at the call site in
# the code using the library, which is far more useful than the particular
# internal method that raised an error.
class CallerFilter
RSPEC_LIBS = %w[
core
mocks
expectations
support
matchers
rails
]
ADDITIONAL_TOP_LEVEL_FILES = %w[ autorun ]
LIB_REGEX = %r{/lib/rspec/(#{(RSPEC_LIBS + ADDITIONAL_TOP_LEVEL_FILES).join('|')})(\.rb|/)}
# rubygems/core_ext/kernel_require.rb isn't actually part of rspec (obviously) but we want
# it ignored when we are looking for the first meaningful line of the backtrace outside
# of RSpec. It can show up in the backtrace as the immediate first caller
# when `CallerFilter.first_non_rspec_line` is called from the top level of a required
# file, but it depends on if rubygems is loaded or not. We don't want to have to deal
# with this complexity in our `RSpec.deprecate` calls, so we ignore it here.
IGNORE_REGEX = Regexp.union(LIB_REGEX, "rubygems/core_ext/kernel_require.rb")
if RSpec::Support::RubyFeatures.caller_locations_supported?
# This supports args because it's more efficient when the caller specifies
# these. It allows us to skip frames the caller knows are part of RSpec,
# and to decrease the increment size if the caller is confident the line will
# be found in a small number of stack frames from `skip_frames`.
#
# Note that there is a risk to passing a `skip_frames` value that is too high:
# If it skippped the first non-rspec line, then this method would return the
# 2nd or 3rd (or whatever) non-rspec line. Thus, you generally shouldn't pass
# values for these parameters, particularly since most places that use this are
# not hot spots (generally it gets used for deprecation warnings). However,
# if you do have a hot spot that calls this, passing `skip_frames` can make
# a significant difference. Just make sure that that particular use is tested
# so that if the provided `skip_frames` changes to no longer be accurate in
# such a way that would return the wrong stack frame, a test will fail to tell you.
#
# See benchmarks/skip_frames_for_caller_filter.rb for measurements.
def self.first_non_rspec_line(skip_frames=3, increment=5)
# Why a default `skip_frames` of 3?
# By the time `caller_locations` is called below, the first 3 frames are:
# lib/rspec/support/caller_filter.rb:63:in `block in first_non_rspec_line'
# lib/rspec/support/caller_filter.rb:62:in `loop'
# lib/rspec/support/caller_filter.rb:62:in `first_non_rspec_line'
# `caller` is an expensive method that scales linearly with the size of
# the stack. The performance hit for fetching it in chunks is small,
# and since the target line is probably near the top of the stack, the
# overall improvement of a chunked search like this is significant.
#
# See benchmarks/caller.rb for measurements.
# The default increment of 5 for this method are mostly arbitrary, but
# is chosen to give good performance on the common case of creating a double.
loop do
stack = caller_locations(skip_frames, increment)
raise "No non-lib lines in stack" unless stack
line = stack.find { |l| l.path !~ IGNORE_REGEX }
return line.to_s if line
skip_frames += increment
increment *= 2 # The choice of two here is arbitrary.
end
end
else
# Earlier rubies do not support the two argument form of `caller`. This
# fallback is logically the same, but slower.
def self.first_non_rspec_line(*)
caller.find { |line| line !~ IGNORE_REGEX }
end
end
end
end
Apply google specific modifications to third party code
module Google
module Ads
module GoogleAds
class Deprecation
Error = Class.new(StandardError)
def initialize(
treat_deprecation_warnings_as_errors,
warn_on_all_deprecations
)
@treat_deprecation_warnings_as_errors = treat_deprecation_warnings_as_errors
@warn_on_all_deprecations = warn_on_all_deprecations
@silenced_sites = {}
end
def deprecate(deprecation)
return unless should_warn?
if @treat_deprecation_warnings_as_errors
raise Error, deprecation
else
Warning.warn("#{deprecation}. Called from: #{CallerFilter.first_non_google_ads_line}")
end
end
private
# Determines if we should issue a deprecation warning, silencing
# on each user call site after the first warning.
def should_warn?
return true if @warn_on_all_deprecations
if !@silenced_sites.include?(CallerFilter.first_non_google_ads_line)
@silenced_sites[CallerFilter.first_non_google_ads_line] ||= true
true
else
false
end
end
end
# @api private
# Portions of this implementation were copied from RSpec, under the
# MIT license: https://git.io/fjR7i
class CallerFilter
LIB_REGEX = /lib\/google\/ads\/google_ads/
IGNORE_REGEX = Regexp.union(LIB_REGEX, "rubygems/core_ext/kernel_require.rb")
# This method finds the first line from the current stack trace that
# doesn't originate from lib/google/ads/google_ads. It does this by
# running backwards through the current stack trace in chunks. The
# reason for this is that pulling the entire stack trace is O(n) on
# the depth of the stack (which is in practice very expensive in Rails
# applications, because rails ads a lot stack frames on to every
# request).
#
# The chunking algorithm works by skipping a certain number of frames,
# and then pulling a static number, consider a stack trace as folows,
# where frame 17 is the one we're interested in, and we're actually,
# thousands of frames deep.
# *
# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#
# the first iteration of this will skip frames 0-2 and pull frames
# 3-7 (skip_frames = 3, increment = 5, 3 + 5 -1 = 7). Skipping is free,
# and pulling chunks is O(n) on the size of the chunk.
#
# *
# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# ^_______^
#
# if the relevant stack frame isn't found, skip is incremented, to
# point at frame 8, and the increment is doubled, doubling the size
# of the search window, causing it to point at frame 17
# *
# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# ^________________________^
#
# here, we've performed 15 lookup operations to find the item we're
# looking for, instead of 1000. The reason we use this chunk and doubling
# strategy is that pulling stack frames has some fixed overhead, and so
# in practice, doing a linear scan from frame 0 to the one we're interested
# in is also slower than this methodology, even though the doubling
# strategy may result in strictly more lookups thn necessary.
def self.first_non_google_ads_line
skip_frames = 3
increment = 5
loop do
stack = caller_locations(skip_frames, increment)
raise "No non-lib lines in stack" unless stack
line = stack.find { |l| l.path !~ IGNORE_REGEX }
return line.to_s if line
skip_frames += increment
increment *= 2 # The choice of two here is arbitrary.
end
end
end
end
end
end
|
Pod::Spec.new do |s|
s.name = "CoreDataKit"
s.version = "0.6.0"
s.license = "MIT"
s.summary = "CoreDataKit makes common operations on objects and importing into CoreData a breeze."
s.description = <<-DESC
CoreDataKit takes care of the hard and verbose parts of CoreData. It manages child contexts for you and helps to easily fetch, create and delete objects.
DESC
s.authors = { "Mathijs Kadijk" => "mkadijk@gmail.com" }
s.social_media_url = "http://twitter.com/mac_cain13"
s.homepage = "https://github.com/mac-cain13/CoreDataKit"
s.source = { :git => "https://github.com/mac-cain13/CoreDataKit.git", :tag => s.version }
s.platform = :ios, "8.0"
s.requires_arc = true
s.source_files = "CoreDataKit/*.swift"
end
Include Importing subdirectory files in podspec
Pod::Spec.new do |s|
s.name = "CoreDataKit"
s.version = "0.6.1"
s.license = "MIT"
s.summary = "CoreDataKit makes common operations on objects and importing into CoreData a breeze."
s.description = <<-DESC
CoreDataKit takes care of the hard and verbose parts of CoreData. It manages child contexts for you and helps to easily fetch, create and delete objects.
DESC
s.authors = { "Mathijs Kadijk" => "mkadijk@gmail.com" }
s.social_media_url = "http://twitter.com/mac_cain13"
s.homepage = "https://github.com/mac-cain13/CoreDataKit"
s.source = { :git => "https://github.com/mac-cain13/CoreDataKit.git", :tag => s.version }
s.platform = :ios, "8.0"
s.requires_arc = true
s.source_files = "CoreDataKit/**/*.swift"
end
|
Pod::Spec.new do |s|
s.name = "Cucumberish"
s.version = "0.0.5"
s.summary = "Cucumberish is an automated test framework for iOS and Mac OS X that uses the most possible human friendly language to define your automated test cases"
s.description = <<-DESC
Cucumberish is Objective-C and Swift framework for Behaviour Driven Development inspired by the amazing way of writing automated test cases introduced originally by Cucumber. With Cucumberish, you write your test cases in almost plain English language.
DESC
s.homepage = "https://github.com/Ahmed-Ali/Cucumberish"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Ahmed Ali" => "eng.ahmed.ali.awad@gmail.com" }
s.social_media_url = "https://www.linkedin.com/in/engahmedali"
s.ios.deployment_target = "7.0"
s.osx.deployment_target = "10.9"
s.source = { :git => "/Volumes/MyFiles/Projects/MyProjects/Cucumberish", :tag => "v#{s.version}"}
s.source_files = 'Cucumberish/*.{h,m}', 'Cucumberish/Core/Managers/*.{h,m}', 'Cucumberish/Core/Models/*.{h,m}', 'Cucumberish/Utils/*.{h,m}', 'Cucumberish/Dependencies/Gherkin', 'Cucumberish/Core/CCIBlockDefinitions.h'
s.public_header_files = 'Cucumberish/Cucumberish.h', 'Cucumberish/Core/Managers/CCIStepsManager.h', 'Cucumberish/Core/CCIBlockDefinitions.h', 'Cucumberish/Core/Models/CCIScenarioDefinition.h'
s.resource_bundles = {
'Gherkin' => ['Cucumberish/Dependencies/Gherkin/gherkin-languages.json'],
}
s.framework = "XCTest"
s.requires_arc = true
s.xcconfig = { "GCC_PREPROCESSOR_DEFINITIONS" => "SRC_ROOT=$(SRCROOT)" }
end
pod spec update
Pod::Spec.new do |s|
s.name = "Cucumberish"
s.version = "0.0.5"
s.summary = "Cucumberish is an automated test framework for iOS and Mac OS X that uses the most possible human friendly language to define your automated test cases"
s.description = <<-DESC
Cucumberish is Objective-C and Swift framework for Behaviour Driven Development inspired by the amazing way of writing automated test cases introduced originally by Cucumber. With Cucumberish, you write your test cases in almost plain English language.
DESC
s.homepage = "https://github.com/Ahmed-Ali/Cucumberish"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Ahmed Ali" => "eng.ahmed.ali.awad@gmail.com" }
s.social_media_url = "https://www.linkedin.com/in/engahmedali"
s.ios.deployment_target = "7.0"
s.osx.deployment_target = "10.9"
s.source = { :git => "https://github.com/Ahmed-Ali/Cucumberish.git", :tag => "v#{s.version}"}
s.source_files = 'Cucumberish/*.{h,m}', 'Cucumberish/Core/Managers/*.{h,m}', 'Cucumberish/Core/Models/*.{h,m}', 'Cucumberish/Utils/*.{h,m}', 'Cucumberish/Dependencies/Gherkin', 'Cucumberish/Core/CCIBlockDefinitions.h'
s.public_header_files = 'Cucumberish/Cucumberish.h', 'Cucumberish/Core/Managers/CCIStepsManager.h', 'Cucumberish/Core/CCIBlockDefinitions.h', 'Cucumberish/Core/Models/CCIScenarioDefinition.h'
s.resource_bundles = {
'Gherkin' => ['Cucumberish/Dependencies/Gherkin/gherkin-languages.json'],
}
s.framework = "XCTest"
s.requires_arc = true
s.xcconfig = { "GCC_PREPROCESSOR_DEFINITIONS" => "SRC_ROOT=$(SRCROOT)" }
end
|
Pod::Spec.new do |s|
s.name = "DCDataViews"
s.version = "0.1.1"
s.summary = "Wrappers around UITableView and UICollectionView to make simpler to use."
s.homepage = "https://github.com/daltoniam/DCDataViews"
s.license = 'Apache License, Version 2.0'
s.author = { "Dalton Cherry" => "daltoniam@gmail.com" }
s.source = { :git => "https://github.com/daltoniam/DCDataViews.git", :tag => "0.1.1" }
s.ios.deployment_target = '5.0'
s.source_files = 'DCDataViews.h'
s.public_header_files = '*.h'
s.requires_arc = true
s.subspec 'CollectionView' do |ss|
ss.source_files = 'CollectionView/*.{h,m}'
ss.framework = 'CoreGraphics'
end
s.subspec 'TableView' do |ss|
ss.source_files = 'TableView/*.{h,m}'
ss.framework = 'CoreGraphics'
end
end
bumped podspec
Pod::Spec.new do |s|
s.name = "DCDataViews"
s.version = "0.1.2"
s.summary = "Wrappers around UITableView and UICollectionView to make simpler to use."
s.homepage = "https://github.com/daltoniam/DCDataViews"
s.license = 'Apache License, Version 2.0'
s.author = { "Dalton Cherry" => "daltoniam@gmail.com" }
s.source = { :git => "https://github.com/daltoniam/DCDataViews.git", :tag => "0.1.2" }
s.ios.deployment_target = '5.0'
s.source_files = 'DCDataViews.h'
s.public_header_files = '*.h'
s.requires_arc = true
s.subspec 'CollectionView' do |ss|
ss.source_files = 'CollectionView/*.{h,m}'
ss.framework = 'CoreGraphics'
end
s.subspec 'TableView' do |ss|
ss.source_files = 'TableView/*.{h,m}'
ss.framework = 'CoreGraphics'
end
end
|
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
class Notifier < ActionMailer::Base
default :from => "GloboDNS <globodns@globodns.com>",
:to => GloboDns::Config::MAIL_RECIPIENTS
def import_successful(message_body)
Logger.new().info("Inicio do message_body")
Logger.new().info(message_body)
Logger.new().info("Fim do message_body")
@message_body = message_body
mail(:subject => I18n.t(:mail_subject_import_successful, :dns_group => GloboDns::Config::DNS_GROUP ,:env => Rails.env ))
end
def import_failed(message_body)
@message_body = message_body
mail(:subject => I18n.t(:mail_subject_import_failed, :dns_group => GloboDns::Config::DNS_GROUP ,:env => Rails.env ))
end
def export_successful(message_body)
@message_body = message_body
mail(:subject => I18n.t(:mail_subject_export_successful, :dns_group => GloboDns::Config::DNS_GROUP ,:env => Rails.env ))
end
def export_failed(message_body)
@message_body = message_body
mail(:subject => I18n.t(:mail_subject_export_failed, :dns_group => GloboDns::Config::DNS_GROUP ,:env => Rails.env ))
end
end
loggando o que é enviado por email
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
class Notifier < ActionMailer::Base
default :from => "GloboDNS <globodns@globodns.com>",
:to => GloboDns::Config::MAIL_RECIPIENTS
def import_successful(message_body)
@message_body = message_body
mail(:subject => I18n.t(:mail_subject_import_successful, :dns_group => GloboDns::Config::DNS_GROUP ,:env => Rails.env ))
end
def import_failed(message_body)
@message_body = message_body
mail(:subject => I18n.t(:mail_subject_import_failed, :dns_group => GloboDns::Config::DNS_GROUP ,:env => Rails.env ))
end
def export_successful(message_body)
@message_body = message_body
mail(:subject => I18n.t(:mail_subject_export_successful, :dns_group => GloboDns::Config::DNS_GROUP ,:env => Rails.env ))
end
def export_failed(message_body)
@message_body = message_body
mail(:subject => I18n.t(:mail_subject_export_failed, :dns_group => GloboDns::Config::DNS_GROUP ,:env => Rails.env ))
end
end
|
Add 1Password
desc '1password' do
doc = html('https://agilebits.com/onepassword')
url = doc.at_css('.downloadbutton')[:href]
version = url.match(/1Password-([\d\.]+).zip/)[1]
{version => url}
end
|
Add pdfshaver
desc 'pdfshaver' do
latest = github('tparry', 'PDFShaver.app').first
version = latest.tag_name.gsub(/^v/, '')
url = latest.assets.first.browser_download_url
Latest.new version: version, url: url
end
|
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/flipper/version', __FILE__)
require File.expand_path('../lib/flipper/metadata', __FILE__)
flipper_cloud_files = lambda do |file|
file =~ /cloud/
end
Gem::Specification.new do |gem|
gem.authors = ['John Nunemaker']
gem.email = ['nunemaker@gmail.com']
gem.summary = 'FlipperCloud.io adapter for Flipper'
gem.license = 'MIT'
gem.homepage = 'https://github.com/jnunemaker/flipper'
extra_files = [
'lib/flipper/version.rb',
]
gem.files = `git ls-files`.split("\n").select(&flipper_cloud_files) + extra_files
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n").select(&flipper_cloud_files)
gem.name = 'flipper-cloud'
gem.require_paths = ['lib']
gem.version = Flipper::VERSION
gem.metadata = Flipper::METADATA
gem.add_dependency 'flipper', "~> #{Flipper::VERSION}"
gem.add_dependency "brow", "~> 0.2.0"
end
Update brow dependency to latest
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/flipper/version', __FILE__)
require File.expand_path('../lib/flipper/metadata', __FILE__)
flipper_cloud_files = lambda do |file|
file =~ /cloud/
end
Gem::Specification.new do |gem|
gem.authors = ['John Nunemaker']
gem.email = ['nunemaker@gmail.com']
gem.summary = 'FlipperCloud.io adapter for Flipper'
gem.license = 'MIT'
gem.homepage = 'https://github.com/jnunemaker/flipper'
extra_files = [
'lib/flipper/version.rb',
]
gem.files = `git ls-files`.split("\n").select(&flipper_cloud_files) + extra_files
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n").select(&flipper_cloud_files)
gem.name = 'flipper-cloud'
gem.require_paths = ['lib']
gem.version = Flipper::VERSION
gem.metadata = Flipper::METADATA
gem.add_dependency 'flipper', "~> #{Flipper::VERSION}"
gem.add_dependency "brow", "~> 0.3.0"
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{ffi-libelf}
s.version = "0.1.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Postmodern"]
s.date = %q{2010-02-16}
s.description = %q{}
s.email = %q{postmodern.mod3@gmail.com}
s.extra_rdoc_files = [
"ChangeLog.md",
"LICENSE.txt",
"README.md"
]
s.files = [
".gitignore",
".specopts",
".yardopts",
"ChangeLog.md",
"LICENSE.txt",
"README.md",
"Rakefile",
"lib/elf.rb",
"lib/elf/32/aux_vec.rb",
"lib/elf/32/dyn.rb",
"lib/elf/32/file_header.rb",
"lib/elf/32/lib.rb",
"lib/elf/32/m68k.rb",
"lib/elf/32/move.rb",
"lib/elf/32/note_header.rb",
"lib/elf/32/program_header.rb",
"lib/elf/32/rel.rb",
"lib/elf/32/rel_addend.rb",
"lib/elf/32/section_header.rb",
"lib/elf/32/sym.rb",
"lib/elf/32/sym_info.rb",
"lib/elf/32/typedefs.rb",
"lib/elf/32/ver_def.rb",
"lib/elf/32/ver_def_aux.rb",
"lib/elf/32/ver_need.rb",
"lib/elf/32/ver_need_aux.rb",
"lib/elf/64/aux_vec.rb",
"lib/elf/64/dyn.rb",
"lib/elf/64/file_header.rb",
"lib/elf/64/lib.rb",
"lib/elf/64/move.rb",
"lib/elf/64/note_header.rb",
"lib/elf/64/program_header.rb",
"lib/elf/64/rel.rb",
"lib/elf/64/rel_addend.rb",
"lib/elf/64/section_header.rb",
"lib/elf/64/sym.rb",
"lib/elf/64/sym_info.rb",
"lib/elf/64/typedefs.rb",
"lib/elf/64/ver_def.rb",
"lib/elf/64/ver_def_aux.rb",
"lib/elf/64/ver_need.rb",
"lib/elf/64/ver_need_aux.rb",
"lib/elf/archive_header.rb",
"lib/elf/archive_symbol.rb",
"lib/elf/aux_vec.rb",
"lib/elf/commands.rb",
"lib/elf/data.rb",
"lib/elf/dyn.rb",
"lib/elf/ffi.rb",
"lib/elf/file_header.rb",
"lib/elf/file_types.rb",
"lib/elf/flags.rb",
"lib/elf/lib.rb",
"lib/elf/m64k.rb",
"lib/elf/move.rb",
"lib/elf/note_header.rb",
"lib/elf/program_header.rb",
"lib/elf/rel.rb",
"lib/elf/rel_addend.rb",
"lib/elf/section_header.rb",
"lib/elf/sym.rb",
"lib/elf/sym_info.rb",
"lib/elf/typedefs.rb",
"lib/elf/types.rb",
"lib/elf/ver_def.rb",
"lib/elf/ver_def_aux.rb",
"lib/elf/ver_need.rb",
"lib/elf/ver_need_aux.rb",
"lib/elf/version.rb",
"spec/libelf_spec.rb",
"spec/spec_helper.rb"
]
s.has_rdoc = %q{yard}
s.homepage = %q{http://github.com/postmodern/ffi-libelf}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.5}
s.summary = %q{FFI bindings to libelf.}
s.test_files = [
"spec/spec_helper.rb",
"spec/libelf_spec.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<ffi>, [">= 0.6.0"])
s.add_development_dependency(%q<rspec>, [">= 1.3.0"])
s.add_development_dependency(%q<yard>, [">= 0.5.3"])
else
s.add_dependency(%q<ffi>, [">= 0.6.0"])
s.add_dependency(%q<rspec>, [">= 1.3.0"])
s.add_dependency(%q<yard>, [">= 0.5.3"])
end
else
s.add_dependency(%q<ffi>, [">= 0.6.0"])
s.add_dependency(%q<rspec>, [">= 1.3.0"])
s.add_dependency(%q<yard>, [">= 0.5.3"])
end
end
Updated the gemspec.
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{ffi-libelf}
s.version = "0.1.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Postmodern"]
s.date = %q{2010-02-16}
s.description = %q{Ruby FFI bindings for libelf.}
s.email = %q{postmodern.mod3@gmail.com}
s.extra_rdoc_files = [
"ChangeLog.md",
"LICENSE.txt",
"README.md"
]
s.files = [
".gitignore",
".specopts",
".yardopts",
"ChangeLog.md",
"LICENSE.txt",
"README.md",
"Rakefile",
"ffi-libelf.gemspec",
"lib/elf.rb",
"lib/elf/archive_header.rb",
"lib/elf/archive_symbol.rb",
"lib/elf/aux_vec.rb",
"lib/elf/data.rb",
"lib/elf/dyn.rb",
"lib/elf/ffi.rb",
"lib/elf/file_header.rb",
"lib/elf/lib.rb",
"lib/elf/m64k.rb",
"lib/elf/move.rb",
"lib/elf/note_header.rb",
"lib/elf/program_header.rb",
"lib/elf/rel.rb",
"lib/elf/rel_addend.rb",
"lib/elf/section_header.rb",
"lib/elf/sym.rb",
"lib/elf/sym_info.rb",
"lib/elf/types.rb",
"lib/elf/ver_def.rb",
"lib/elf/ver_def_aux.rb",
"lib/elf/ver_need.rb",
"lib/elf/ver_need_aux.rb",
"lib/elf/version.rb",
"lib/elf32.rb",
"lib/elf32/aux_vec.rb",
"lib/elf32/dyn.rb",
"lib/elf32/ffi.rb",
"lib/elf32/file_header.rb",
"lib/elf32/lib.rb",
"lib/elf32/m68k.rb",
"lib/elf32/move.rb",
"lib/elf32/note_header.rb",
"lib/elf32/program_header.rb",
"lib/elf32/rel.rb",
"lib/elf32/rel_addend.rb",
"lib/elf32/section_header.rb",
"lib/elf32/sym.rb",
"lib/elf32/sym_info.rb",
"lib/elf32/types.rb",
"lib/elf32/ver_def.rb",
"lib/elf32/ver_def_aux.rb",
"lib/elf32/ver_need.rb",
"lib/elf32/ver_need_aux.rb",
"lib/elf64.rb",
"lib/elf64/aux_vec.rb",
"lib/elf64/dyn.rb",
"lib/elf64/ffi.rb",
"lib/elf64/file_header.rb",
"lib/elf64/lib.rb",
"lib/elf64/move.rb",
"lib/elf64/note_header.rb",
"lib/elf64/program_header.rb",
"lib/elf64/rel.rb",
"lib/elf64/rel_addend.rb",
"lib/elf64/section_header.rb",
"lib/elf64/sym.rb",
"lib/elf64/sym_info.rb",
"lib/elf64/types.rb",
"lib/elf64/ver_def.rb",
"lib/elf64/ver_def_aux.rb",
"lib/elf64/ver_need.rb",
"lib/elf64/ver_need_aux.rb",
"spec/libelf_spec.rb",
"spec/spec_helper.rb"
]
s.has_rdoc = %q{yard}
s.homepage = %q{http://github.com/postmodern/ffi-libelf}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.5}
s.summary = %q{FFI bindings to libelf.}
s.test_files = [
"spec/spec_helper.rb",
"spec/libelf_spec.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<ffi>, [">= 0.6.0"])
s.add_development_dependency(%q<rspec>, [">= 1.3.0"])
s.add_development_dependency(%q<yard>, [">= 0.5.3"])
else
s.add_dependency(%q<ffi>, [">= 0.6.0"])
s.add_dependency(%q<rspec>, [">= 1.3.0"])
s.add_dependency(%q<yard>, [">= 0.5.3"])
end
else
s.add_dependency(%q<ffi>, [">= 0.6.0"])
s.add_dependency(%q<rspec>, [">= 1.3.0"])
s.add_dependency(%q<yard>, [">= 0.5.3"])
end
end
|
# import some logic/helpers from lib/*.rb
include NanoBox::Engine
include NanoBox::Output
# before
logtap.print (bullet("Running before hook..."), 'debug')
if boxfile[:before]
logtap.print (bullet("'Before' detected, running now..."), 'debug')
if boxfile[:before].is_a?(String)
boxfile[:before]=[boxfile[:before]]
end
boxfile[:before].each_with_index do |before_hook, i|
logtap.print subtask_start "Running before hook #{i}"
logtap.print bullet_info "$ #{before_hook}"
execute "before code" do
command before_hook
cwd "#{CODE_DIR}"
path GONANO_PATH
user 'gonano'
stream true
on_data {|data| logtap.print data}
on_exit { |code| logtap.print code == 0 ? subtask_success : subtask_fail }
end
end
end
# build
logtap.print(bullet("Running build hook..."), 'debug')
# By this point, engine should be set in the registry
engine = registry('engine')
if not ::File.exist? "#{ENGINE_DIR}/#{engine}/bin/build"
logtap.print fatal('Build script is required, but missing')
exit Hookit::Exit::ABORT
end
logtap.print(bullet("Build script detected, running now..."), 'debug')
execute "build code" do
command %Q(#{ENGINE_DIR}/#{engine}/bin/build '#{engine_payload}')
cwd "#{ENGINE_DIR}/#{engine}/bin"
path GONANO_PATH
user 'gonano'
stream true
on_data {|data| logtap.print data}
end
# after
logtap.print (bullet("Running after hook..."), 'debug')
if boxfile[:after]
logtap.print (bullet("'After' detected, running now..."), 'debug')
if boxfile[:after].is_a?(String)
boxfile[:after]=[boxfile[:after]]
end
boxfile[:after].each_with_index do |after_hook, i|
logtap.print subtask_start "Running after hook #{i}"
logtap.print bullet_info "$ #{after_hook}"
execute "after code" do
command after_hook
cwd "#{CODE_DIR}"
path GONANO_PATH
user 'gonano'
stream true
on_data {|data| logtap.print data}
on_exit { |code| logtap.print code == 0 ? subtask_success : subtask_fail }
end
end
end
Remove space between function call and parenthesis
# import some logic/helpers from lib/*.rb
include NanoBox::Engine
include NanoBox::Output
# before
logtap.print(bullet("Running before hook..."), 'debug')
if boxfile[:before]
logtap.print(bullet("'Before' detected, running now..."), 'debug')
if boxfile[:before].is_a?(String)
boxfile[:before]=[boxfile[:before]]
end
boxfile[:before].each_with_index do |before_hook, i|
logtap.print subtask_start "Running before hook #{i}"
logtap.print bullet_info "$ #{before_hook}"
execute "before code" do
command before_hook
cwd "#{CODE_DIR}"
path GONANO_PATH
user 'gonano'
stream true
on_data {|data| logtap.print data}
on_exit { |code| logtap.print code == 0 ? subtask_success : subtask_fail }
end
end
end
# build
logtap.print(bullet("Running build hook..."), 'debug')
# By this point, engine should be set in the registry
engine = registry('engine')
if not ::File.exist? "#{ENGINE_DIR}/#{engine}/bin/build"
logtap.print fatal('Build script is required, but missing')
exit Hookit::Exit::ABORT
end
logtap.print(bullet("Build script detected, running now..."), 'debug')
execute "build code" do
command %Q(#{ENGINE_DIR}/#{engine}/bin/build '#{engine_payload}')
cwd "#{ENGINE_DIR}/#{engine}/bin"
path GONANO_PATH
user 'gonano'
stream true
on_data {|data| logtap.print data}
end
# after
logtap.print(bullet("Running after hook..."), 'debug')
if boxfile[:after]
logtap.print(bullet("'After' detected, running now..."), 'debug')
if boxfile[:after].is_a?(String)
boxfile[:after]=[boxfile[:after]]
end
boxfile[:after].each_with_index do |after_hook, i|
logtap.print subtask_start "Running after hook #{i}"
logtap.print bullet_info "$ #{after_hook}"
execute "after code" do
command after_hook
cwd "#{CODE_DIR}"
path GONANO_PATH
user 'gonano'
stream true
on_data {|data| logtap.print data}
on_exit { |code| logtap.print code == 0 ? subtask_success : subtask_fail }
end
end
end
|
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
Gem::Specification.new do |s|
s.name = "fluent-plugin-keep-forward"
s.version = "0.0.2"
s.authors = ["Naotoshi SEO"]
s.email = ["sonots@gmail.com"]
s.homepage = "https://github.com/sonots/fluent-plugin-keep-forward"
s.summary = "out_foward extension to keep forwarding to a node"
s.description = s.summary
s.rubyforge_project = "fluent-plugin-keep-forward"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_runtime_dependency "fluentd"
s.add_development_dependency "rake"
s.add_development_dependency "rspec"
s.add_development_dependency "pry"
end
v0.0.3
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
Gem::Specification.new do |s|
s.name = "fluent-plugin-keep-forward"
s.version = "0.0.3"
s.authors = ["Naotoshi SEO"]
s.email = ["sonots@gmail.com"]
s.homepage = "https://github.com/sonots/fluent-plugin-keep-forward"
s.summary = "out_foward extension to keep forwarding to a node"
s.description = s.summary
s.rubyforge_project = "fluent-plugin-keep-forward"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_runtime_dependency "fluentd"
s.add_development_dependency "rake"
s.add_development_dependency "rspec"
s.add_development_dependency "pry"
end
|
require 'formula'
class Hub < Formula
homepage "http://hub.github.com/"
url "https://github.com/github/hub/releases/download/v2.2.0-rc1/hub-mac-amd64-2.2.0-rc1.tar.gz"
sha1 "413ce80d32f6313cef010e0edb1e664e1fff7427"
def install
bin.install "hub"
man1.install Dir["man/*"]
bash_completion.install "etc/hub.bash_completion.sh"
zsh_completion.install "etc/hub.zsh_completion" => "_hub"
end
test do
HOMEBREW_REPOSITORY.cd do
assert shell_output("#{bin}/hub version").split("\n").include?("hub version #{version}")
end
end
end
Update to `hub` 2.2.0
require 'formula'
class Hub < Formula
homepage "http://hub.github.com/"
url "https://github.com/github/hub/releases/download/v2.2.0/hub-mac-amd64-2.2.0.tar.gz"
sha1 "72f7bcb8893287dcbd63ed903ddddd55d239e96a"
def install
bin.install "hub"
man1.install Dir["man/*"]
bash_completion.install "etc/hub.bash_completion.sh"
zsh_completion.install "etc/hub.zsh_completion" => "_hub"
end
test do
HOMEBREW_REPOSITORY.cd do
assert shell_output("#{bin}/hub version").split("\n").include?("hub version #{version}")
end
end
end
|
Gem::Specification.new do |s|
s.name = "http-protocol"
s.version = '0.1.0'
s.summary = "HTTP protocol library designed to facilitate custom HTTP clients"
s.description = ' '
s.authors = ['Obsidian Software, Inc']
s.email = 'opensource@obsidianexchange.com'
s.homepage = 'https://github.com/obsidian-btc/http-protocol'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.add_runtime_dependency 'telemetry-logger'
s.add_development_dependency 'minitest'
s.add_development_dependency 'minitest-spec-context'
s.add_development_dependency 'pry'
s.add_development_dependency 'runner'
end
Package version is increased from 0.1.0 to 0.1.1
Gem::Specification.new do |s|
s.name = "http-protocol"
s.version = '0.1.1'
s.summary = "HTTP protocol library designed to facilitate custom HTTP clients"
s.description = ' '
s.authors = ['Obsidian Software, Inc']
s.email = 'opensource@obsidianexchange.com'
s.homepage = 'https://github.com/obsidian-btc/http-protocol'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.add_runtime_dependency 'telemetry-logger'
s.add_development_dependency 'minitest'
s.add_development_dependency 'minitest-spec-context'
s.add_development_dependency 'pry'
s.add_development_dependency 'runner'
end
|
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{resource_controller}
s.version = "0.6.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["James Golick"]
s.date = %q{2009-03-31}
s.description = %q{}
s.email = %q{james@giraffesoft.ca}
s.extra_rdoc_files = ["README.rdoc", "LICENSE"]
s.files = ["README.rdoc", "VERSION.yml", "generators/scaffold_resource", "generators/scaffold_resource/scaffold_resource_generator.rb", "generators/scaffold_resource/templates", "generators/scaffold_resource/templates/controller.rb", "generators/scaffold_resource/templates/fixtures.yml", "generators/scaffold_resource/templates/functional_test.rb", "generators/scaffold_resource/templates/helper.rb", "generators/scaffold_resource/templates/migration.rb", "generators/scaffold_resource/templates/model.rb", "generators/scaffold_resource/templates/old_migration.rb", "generators/scaffold_resource/templates/rspec", "generators/scaffold_resource/templates/rspec/functional_spec.rb", "generators/scaffold_resource/templates/rspec/helper_spec.rb", "generators/scaffold_resource/templates/rspec/routing_spec.rb", "generators/scaffold_resource/templates/rspec/unit_spec.rb", "generators/scaffold_resource/templates/rspec/views", "generators/scaffold_resource/templates/rspec/views/edit_spec.rb", "generators/scaffold_resource/templates/rspec/views/index_spec.rb", "generators/scaffold_resource/templates/rspec/views/new_spec.rb", "generators/scaffold_resource/templates/rspec/views/show_spec.rb", "generators/scaffold_resource/templates/shoulda_functional_test.rb", "generators/scaffold_resource/templates/unit_test.rb", "generators/scaffold_resource/templates/view__form.erb", "generators/scaffold_resource/templates/view__form.haml", "generators/scaffold_resource/templates/view_edit.erb", "generators/scaffold_resource/templates/view_edit.haml", "generators/scaffold_resource/templates/view_index.erb", "generators/scaffold_resource/templates/view_index.haml", "generators/scaffold_resource/templates/view_new.erb", "generators/scaffold_resource/templates/view_new.haml", "generators/scaffold_resource/templates/view_show.erb", "generators/scaffold_resource/templates/view_show.haml", "generators/scaffold_resource/USAGE", "lib/resource_controller", "lib/resource_controller/accessors.rb", "lib/resource_controller/action_options.rb", "lib/resource_controller/actions.rb", "lib/resource_controller/base.rb", "lib/resource_controller/class_methods.rb", "lib/resource_controller/controller.rb", "lib/resource_controller/failable_action_options.rb", "lib/resource_controller/helpers", "lib/resource_controller/helpers/current_objects.rb", "lib/resource_controller/helpers/internal.rb", "lib/resource_controller/helpers/nested.rb", "lib/resource_controller/helpers/singleton_customizations.rb", "lib/resource_controller/helpers/urls.rb", "lib/resource_controller/helpers.rb", "lib/resource_controller/response_collector.rb", "lib/resource_controller/singleton.rb", "lib/resource_controller.rb", "lib/urligence.rb", "test/app", "test/app/controllers", "test/app/controllers/accounts_controller.rb", "test/app/controllers/application_controller.rb", "test/app/controllers/cms", "test/app/controllers/cms/options_controller.rb", "test/app/controllers/cms/personnel_controller.rb", "test/app/controllers/cms/photos_controller.rb", "test/app/controllers/cms/products_controller.rb", "test/app/controllers/comments_controller.rb", "test/app/controllers/images_controller.rb", "test/app/controllers/options_controller.rb", "test/app/controllers/people_controller.rb", "test/app/controllers/photos_controller.rb", "test/app/controllers/posts_controller.rb", "test/app/controllers/projects_controller.rb", "test/app/controllers/somethings_controller.rb", "test/app/controllers/tags_controller.rb", "test/app/controllers/users_controller.rb", "test/app/helpers", "test/app/helpers/accounts_helper.rb", "test/app/helpers/application_helper.rb", "test/app/helpers/cms", "test/app/helpers/cms/products_helper.rb", "test/app/helpers/comments_helper.rb", "test/app/helpers/images_helper.rb", "test/app/helpers/options_helper.rb", "test/app/helpers/people_helper.rb", "test/app/helpers/photos_helper.rb", "test/app/helpers/posts_helper.rb", "test/app/helpers/projects_helper.rb", "test/app/helpers/somethings_helper.rb", "test/app/helpers/tags_helper.rb", "test/app/helpers/users_helper.rb", "test/app/models", "test/app/models/account.rb", "test/app/models/comment.rb", "test/app/models/image.rb", "test/app/models/option.rb", "test/app/models/personnel.rb", "test/app/models/photo.rb", "test/app/models/post.rb", "test/app/models/product.rb", "test/app/models/project.rb", "test/app/models/something.rb", "test/app/models/tag.rb", "test/app/models/user.rb", "test/app/views", "test/app/views/accounts", "test/app/views/accounts/_form.html.erb", "test/app/views/accounts/edit.html.erb", "test/app/views/accounts/new.html.erb", "test/app/views/accounts/show.html.erb", "test/app/views/cms", "test/app/views/cms/options", "test/app/views/cms/options/edit.rhtml", "test/app/views/cms/options/index.rhtml", "test/app/views/cms/options/new.rhtml", "test/app/views/cms/options/show.rhtml", "test/app/views/cms/photos", "test/app/views/cms/photos/edit.rhtml", "test/app/views/cms/photos/index.rhtml", "test/app/views/cms/photos/new.rhtml", "test/app/views/cms/photos/show.rhtml", "test/app/views/cms/products", "test/app/views/cms/products/edit.rhtml", "test/app/views/cms/products/index.rhtml", "test/app/views/cms/products/new.rhtml", "test/app/views/cms/products/show.rhtml", "test/app/views/comments", "test/app/views/comments/edit.rhtml", "test/app/views/comments/index.rhtml", "test/app/views/comments/new.rhtml", "test/app/views/comments/show.rhtml", "test/app/views/images", "test/app/views/images/_form.html.erb", "test/app/views/images/edit.html.erb", "test/app/views/images/new.html.erb", "test/app/views/layouts", "test/app/views/layouts/application.rhtml", "test/app/views/layouts/comments.rhtml", "test/app/views/layouts/options.rhtml", "test/app/views/layouts/people.rhtml", "test/app/views/layouts/photos.rhtml", "test/app/views/layouts/projects.rhtml", "test/app/views/layouts/somethings.rhtml", "test/app/views/layouts/tags.rhtml", "test/app/views/options", "test/app/views/options/_form.html.erb", "test/app/views/options/edit.html.erb", "test/app/views/options/index.html.erb", "test/app/views/options/new.html.erb", "test/app/views/options/show.html.erb", "test/app/views/people", "test/app/views/people/edit.rhtml", "test/app/views/people/index.rhtml", "test/app/views/people/new.rhtml", "test/app/views/people/show.rhtml", "test/app/views/photos", "test/app/views/photos/edit.rhtml", "test/app/views/photos/index.rhtml", "test/app/views/photos/new.rhtml", "test/app/views/photos/show.rhtml", "test/app/views/posts", "test/app/views/posts/edit.rhtml", "test/app/views/posts/index.rhtml", "test/app/views/posts/new.rhtml", "test/app/views/posts/show.rhtml", "test/app/views/projects", "test/app/views/projects/edit.rhtml", "test/app/views/projects/index.rhtml", "test/app/views/projects/new.rhtml", "test/app/views/projects/show.rhtml", "test/app/views/somethings", "test/app/views/somethings/edit.rhtml", "test/app/views/somethings/index.rhtml", "test/app/views/somethings/new.rhtml", "test/app/views/somethings/show.rhtml", "test/app/views/tags", "test/app/views/tags/edit.rhtml", "test/app/views/tags/index.rhtml", "test/app/views/tags/index.rjs", "test/app/views/tags/new.rhtml", "test/app/views/tags/show.rhtml", "test/app/views/users", "test/app/views/users/edit.rhtml", "test/app/views/users/index.rhtml", "test/app/views/users/new.rhtml", "test/app/views/users/show.rhtml", "test/config", "test/config/boot.rb", "test/config/database.yml", "test/config/environment.rb", "test/config/environments", "test/config/environments/development.rb", "test/config/environments/test.rb", "test/config/initializers", "test/config/initializers/inflections.rb", "test/config/routes.rb", "test/db", "test/db/migrate", "test/db/migrate/001_create_posts.rb", "test/db/migrate/002_create_products.rb", "test/db/migrate/003_create_comments.rb", "test/db/migrate/004_create_options.rb", "test/db/migrate/005_create_photos.rb", "test/db/migrate/006_create_tags.rb", "test/db/migrate/007_create_somethings.rb", "test/db/migrate/008_create_accounts.rb", "test/db/migrate/009_add_account_id_to_photos.rb", "test/db/migrate/010_create_projects.rb", "test/db/migrate/011_create_images.rb", "test/db/migrate/012_create_users.rb", "test/db/migrate/013_create_personnel.rb", "test/db/migrate/014_add_personnel_id_to_photos.rb", "test/db/schema.rb", "test/db/test.sqlite3", "test/log", "test/log/development.log", "test/log/test.log", "test/Rakefile", "test/script", "test/script/console", "test/script/destroy", "test/script/generate", "test/script/server", "test/test", "test/test/fixtures", "test/test/fixtures/accounts.yml", "test/test/fixtures/comments.yml", "test/test/fixtures/images.yml", "test/test/fixtures/options.yml", "test/test/fixtures/personnel.yml", "test/test/fixtures/photos.yml", "test/test/fixtures/photos_tags.yml", "test/test/fixtures/posts.yml", "test/test/fixtures/products.yml", "test/test/fixtures/projects.yml", "test/test/fixtures/somethings.yml", "test/test/fixtures/tags.yml", "test/test/fixtures/users.yml", "test/test/functional", "test/test/functional/cms", "test/test/functional/cms/options_controller_test.rb", "test/test/functional/cms/photos_controller_test.rb", "test/test/functional/cms/products_controller_test.rb", "test/test/functional/comments_controller_test.rb", "test/test/functional/images_controller_test.rb", "test/test/functional/people_controller_test.rb", "test/test/functional/photos_controller_test.rb", "test/test/functional/posts_controller_test.rb", "test/test/functional/projects_controller_test.rb", "test/test/functional/somethings_controller_test.rb", "test/test/functional/tags_controller_test.rb", "test/test/functional/users_controller_test.rb", "test/test/test_helper.rb", "test/test/unit", "test/test/unit/accessors_test.rb", "test/test/unit/account_test.rb", "test/test/unit/action_options_test.rb", "test/test/unit/base_test.rb", "test/test/unit/comment_test.rb", "test/test/unit/failable_action_options_test.rb", "test/test/unit/helpers", "test/test/unit/helpers/current_objects_test.rb", "test/test/unit/helpers/internal_test.rb", "test/test/unit/helpers/nested_test.rb", "test/test/unit/helpers/singleton_current_objects_test.rb", "test/test/unit/helpers/singleton_nested_test.rb", "test/test/unit/helpers/singleton_urls_test.rb", "test/test/unit/helpers/urls_test.rb", "test/test/unit/helpers_test.rb", "test/test/unit/image_test.rb", "test/test/unit/option_test.rb", "test/test/unit/photo_test.rb", "test/test/unit/post_test.rb", "test/test/unit/project_test.rb", "test/test/unit/response_collector_test.rb", "test/test/unit/something_test.rb", "test/test/unit/tag_test.rb", "test/test/unit/urligence_test.rb", "test/tmp", "test/vendor", "test/vendor/gems", "test/vendor/gems/resource_controller-10.0.0", "rails/init.rb", "LICENSE"]
s.has_rdoc = true
s.homepage = %q{http://jamesgolick.com/resource_controller}
s.rdoc_options = ["--inline-source", "--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.1}
s.summary = %q{Rails RESTful controller abstraction plugin.}
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 2
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
Regenerated gemspec for version 0.6.2
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{resource_controller}
s.version = "0.6.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["James Golick"]
s.date = %q{2009-05-31}
s.description = %q{}
s.email = %q{james@giraffesoft.ca}
s.extra_rdoc_files = ["README.rdoc", "LICENSE"]
s.files = ["README.rdoc", "VERSION.yml", "generators/scaffold_resource", "generators/scaffold_resource/scaffold_resource_generator.rb", "generators/scaffold_resource/templates", "generators/scaffold_resource/templates/controller.rb", "generators/scaffold_resource/templates/fixtures.yml", "generators/scaffold_resource/templates/functional_test.rb", "generators/scaffold_resource/templates/helper.rb", "generators/scaffold_resource/templates/migration.rb", "generators/scaffold_resource/templates/model.rb", "generators/scaffold_resource/templates/old_migration.rb", "generators/scaffold_resource/templates/rspec", "generators/scaffold_resource/templates/rspec/functional_spec.rb", "generators/scaffold_resource/templates/rspec/helper_spec.rb", "generators/scaffold_resource/templates/rspec/routing_spec.rb", "generators/scaffold_resource/templates/rspec/unit_spec.rb", "generators/scaffold_resource/templates/rspec/views", "generators/scaffold_resource/templates/rspec/views/edit_spec.rb", "generators/scaffold_resource/templates/rspec/views/index_spec.rb", "generators/scaffold_resource/templates/rspec/views/new_spec.rb", "generators/scaffold_resource/templates/rspec/views/show_spec.rb", "generators/scaffold_resource/templates/shoulda_functional_test.rb", "generators/scaffold_resource/templates/unit_test.rb", "generators/scaffold_resource/templates/view__form.erb", "generators/scaffold_resource/templates/view__form.haml", "generators/scaffold_resource/templates/view_edit.erb", "generators/scaffold_resource/templates/view_edit.haml", "generators/scaffold_resource/templates/view_index.erb", "generators/scaffold_resource/templates/view_index.haml", "generators/scaffold_resource/templates/view_new.erb", "generators/scaffold_resource/templates/view_new.haml", "generators/scaffold_resource/templates/view_show.erb", "generators/scaffold_resource/templates/view_show.haml", "generators/scaffold_resource/USAGE", "lib/resource_controller", "lib/resource_controller/accessors.rb", "lib/resource_controller/action_options.rb", "lib/resource_controller/actions.rb", "lib/resource_controller/base.rb", "lib/resource_controller/class_methods.rb", "lib/resource_controller/controller.rb", "lib/resource_controller/failable_action_options.rb", "lib/resource_controller/helpers", "lib/resource_controller/helpers/current_objects.rb", "lib/resource_controller/helpers/internal.rb", "lib/resource_controller/helpers/nested.rb", "lib/resource_controller/helpers/singleton_customizations.rb", "lib/resource_controller/helpers/urls.rb", "lib/resource_controller/helpers.rb", "lib/resource_controller/response_collector.rb", "lib/resource_controller/singleton.rb", "lib/resource_controller.rb", "lib/urligence.rb", "test/app", "test/app/controllers", "test/app/controllers/accounts_controller.rb", "test/app/controllers/application_controller.rb", "test/app/controllers/cms", "test/app/controllers/cms/options_controller.rb", "test/app/controllers/cms/personnel_controller.rb", "test/app/controllers/cms/photos_controller.rb", "test/app/controllers/cms/products_controller.rb", "test/app/controllers/comments_controller.rb", "test/app/controllers/images_controller.rb", "test/app/controllers/options_controller.rb", "test/app/controllers/people_controller.rb", "test/app/controllers/photos_controller.rb", "test/app/controllers/posts_controller.rb", "test/app/controllers/projects_controller.rb", "test/app/controllers/somethings_controller.rb", "test/app/controllers/tags_controller.rb", "test/app/controllers/users_controller.rb", "test/app/helpers", "test/app/helpers/accounts_helper.rb", "test/app/helpers/application_helper.rb", "test/app/helpers/cms", "test/app/helpers/cms/products_helper.rb", "test/app/helpers/comments_helper.rb", "test/app/helpers/images_helper.rb", "test/app/helpers/options_helper.rb", "test/app/helpers/people_helper.rb", "test/app/helpers/photos_helper.rb", "test/app/helpers/posts_helper.rb", "test/app/helpers/projects_helper.rb", "test/app/helpers/somethings_helper.rb", "test/app/helpers/tags_helper.rb", "test/app/helpers/users_helper.rb", "test/app/models", "test/app/models/account.rb", "test/app/models/comment.rb", "test/app/models/image.rb", "test/app/models/option.rb", "test/app/models/personnel.rb", "test/app/models/photo.rb", "test/app/models/post.rb", "test/app/models/product.rb", "test/app/models/project.rb", "test/app/models/something.rb", "test/app/models/tag.rb", "test/app/models/user.rb", "test/app/views", "test/app/views/accounts", "test/app/views/accounts/_form.html.erb", "test/app/views/accounts/edit.html.erb", "test/app/views/accounts/new.html.erb", "test/app/views/accounts/show.html.erb", "test/app/views/cms", "test/app/views/cms/options", "test/app/views/cms/options/edit.rhtml", "test/app/views/cms/options/index.rhtml", "test/app/views/cms/options/new.rhtml", "test/app/views/cms/options/show.rhtml", "test/app/views/cms/photos", "test/app/views/cms/photos/edit.rhtml", "test/app/views/cms/photos/index.rhtml", "test/app/views/cms/photos/new.rhtml", "test/app/views/cms/photos/show.rhtml", "test/app/views/cms/products", "test/app/views/cms/products/edit.rhtml", "test/app/views/cms/products/index.rhtml", "test/app/views/cms/products/new.rhtml", "test/app/views/cms/products/show.rhtml", "test/app/views/comments", "test/app/views/comments/edit.rhtml", "test/app/views/comments/index.rhtml", "test/app/views/comments/new.rhtml", "test/app/views/comments/show.rhtml", "test/app/views/images", "test/app/views/images/_form.html.erb", "test/app/views/images/edit.html.erb", "test/app/views/images/new.html.erb", "test/app/views/layouts", "test/app/views/layouts/application.rhtml", "test/app/views/layouts/comments.rhtml", "test/app/views/layouts/options.rhtml", "test/app/views/layouts/people.rhtml", "test/app/views/layouts/photos.rhtml", "test/app/views/layouts/projects.rhtml", "test/app/views/layouts/somethings.rhtml", "test/app/views/layouts/tags.rhtml", "test/app/views/options", "test/app/views/options/_form.html.erb", "test/app/views/options/edit.html.erb", "test/app/views/options/index.html.erb", "test/app/views/options/new.html.erb", "test/app/views/options/show.html.erb", "test/app/views/people", "test/app/views/people/edit.rhtml", "test/app/views/people/index.rhtml", "test/app/views/people/new.rhtml", "test/app/views/people/show.rhtml", "test/app/views/photos", "test/app/views/photos/edit.rhtml", "test/app/views/photos/index.rhtml", "test/app/views/photos/new.rhtml", "test/app/views/photos/show.rhtml", "test/app/views/posts", "test/app/views/posts/edit.rhtml", "test/app/views/posts/index.rhtml", "test/app/views/posts/new.rhtml", "test/app/views/posts/show.rhtml", "test/app/views/projects", "test/app/views/projects/edit.rhtml", "test/app/views/projects/index.rhtml", "test/app/views/projects/new.rhtml", "test/app/views/projects/show.rhtml", "test/app/views/somethings", "test/app/views/somethings/edit.rhtml", "test/app/views/somethings/index.rhtml", "test/app/views/somethings/new.rhtml", "test/app/views/somethings/show.rhtml", "test/app/views/tags", "test/app/views/tags/edit.rhtml", "test/app/views/tags/index.rhtml", "test/app/views/tags/index.rjs", "test/app/views/tags/new.rhtml", "test/app/views/tags/show.rhtml", "test/app/views/users", "test/app/views/users/edit.rhtml", "test/app/views/users/index.rhtml", "test/app/views/users/new.rhtml", "test/app/views/users/show.rhtml", "test/config", "test/config/boot.rb", "test/config/database.yml", "test/config/environment.rb", "test/config/environments", "test/config/environments/development.rb", "test/config/environments/test.rb", "test/config/initializers", "test/config/initializers/inflections.rb", "test/config/routes.rb", "test/db", "test/db/migrate", "test/db/migrate/001_create_posts.rb", "test/db/migrate/002_create_products.rb", "test/db/migrate/003_create_comments.rb", "test/db/migrate/004_create_options.rb", "test/db/migrate/005_create_photos.rb", "test/db/migrate/006_create_tags.rb", "test/db/migrate/007_create_somethings.rb", "test/db/migrate/008_create_accounts.rb", "test/db/migrate/009_add_account_id_to_photos.rb", "test/db/migrate/010_create_projects.rb", "test/db/migrate/011_create_images.rb", "test/db/migrate/012_create_users.rb", "test/db/migrate/013_create_personnel.rb", "test/db/migrate/014_add_personnel_id_to_photos.rb", "test/db/schema.rb", "test/db/test.sqlite3", "test/log", "test/log/development.log", "test/log/test.log", "test/Rakefile", "test/script", "test/script/console", "test/script/destroy", "test/script/generate", "test/script/server", "test/test", "test/test/fixtures", "test/test/fixtures/accounts.yml", "test/test/fixtures/comments.yml", "test/test/fixtures/images.yml", "test/test/fixtures/options.yml", "test/test/fixtures/personnel.yml", "test/test/fixtures/photos.yml", "test/test/fixtures/photos_tags.yml", "test/test/fixtures/posts.yml", "test/test/fixtures/products.yml", "test/test/fixtures/projects.yml", "test/test/fixtures/somethings.yml", "test/test/fixtures/tags.yml", "test/test/fixtures/users.yml", "test/test/functional", "test/test/functional/cms", "test/test/functional/cms/options_controller_test.rb", "test/test/functional/cms/photos_controller_test.rb", "test/test/functional/cms/products_controller_test.rb", "test/test/functional/comments_controller_test.rb", "test/test/functional/images_controller_test.rb", "test/test/functional/people_controller_test.rb", "test/test/functional/photos_controller_test.rb", "test/test/functional/posts_controller_test.rb", "test/test/functional/projects_controller_test.rb", "test/test/functional/somethings_controller_test.rb", "test/test/functional/tags_controller_test.rb", "test/test/functional/users_controller_test.rb", "test/test/test_helper.rb", "test/test/unit", "test/test/unit/accessors_test.rb", "test/test/unit/account_test.rb", "test/test/unit/action_options_test.rb", "test/test/unit/base_test.rb", "test/test/unit/comment_test.rb", "test/test/unit/failable_action_options_test.rb", "test/test/unit/helpers", "test/test/unit/helpers/current_objects_test.rb", "test/test/unit/helpers/internal_test.rb", "test/test/unit/helpers/nested_test.rb", "test/test/unit/helpers/singleton_current_objects_test.rb", "test/test/unit/helpers/singleton_nested_test.rb", "test/test/unit/helpers/singleton_urls_test.rb", "test/test/unit/helpers/urls_test.rb", "test/test/unit/helpers_test.rb", "test/test/unit/image_test.rb", "test/test/unit/option_test.rb", "test/test/unit/photo_test.rb", "test/test/unit/post_test.rb", "test/test/unit/project_test.rb", "test/test/unit/response_collector_test.rb", "test/test/unit/something_test.rb", "test/test/unit/tag_test.rb", "test/test/unit/urligence_test.rb", "test/tmp", "test/vendor", "test/vendor/gems", "test/vendor/gems/resource_controller-10.0.0", "rails/init.rb", "LICENSE"]
s.has_rdoc = true
s.homepage = %q{http://jamesgolick.com/resource_controller}
s.rdoc_options = ["--inline-source", "--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.1}
s.summary = %q{Rails RESTful controller abstraction plugin.}
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 2
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
|
Added podspec file. Currently pointing to dev branch for sources.
Pod::Spec.new do |s|
s.name = 'EZClockView'
s.version = '1.0.0'
s.license = 'MIT'
s.summary = 'iOS framework to display and customize a clock.'
s.homepage = 'https://github.com/notbenoit/EZClockView'
s.social_media_url = 'http://twitter.com/notbenoit'
s.authors = { 'Benoit Layer' => 'benoit.layer@gmail.com' }
s.source = { :git => 'https://github.com/notbenoit/EZClockView.git', :tag => s.version }
s.ios.deployment_target = '7.0'
s.source_files = 'Source/*.swift'
s.requires_arc = true
end
|
# University of Washington, Programming Languages, Homework 6, hw6runner.rb
# This is the only file you turn in, so do not modify the other files as
# part of your solution.
class MyPiece < Piece
All_My_Pieces = [[[[0, 0], [1, 0], [0, 1], [1, 1]]],
rotations([[0, 0], [-1, 0], [1, 0], [0, -1]]), # T
[[[0, 0], [-1, 0], [1, 0], [2, 0]], # long (only needs two)
[[0, 0], [0, -1], [0, 1], [0, 2]]],
rotations([[0, 0], [0, -1], [0, 1], [1, 1]]), # L
rotations([[0, 0], [0, -1], [0, 1], [-1, 1]]), # inverted L
rotations([[0, 0], [-1, 0], [0, -1], [1, -1]]), # S
rotations([[0, 0], [1, 0], [0, -1], [-1, -1]]),
[[[0, 0], [-1, 0], [1, 0], [2, 0], [3, 0]], # extra #2 very long (only needs two)
[[0, 0], [0, -1], [0, 1], [0, 2], [0, 3]]],
rotations([[0, 0], [1, 0], [0, -1], [0, 1], [1, 1]]), # extra #1
rotations([[0,0], [0,1], [1,0]]) #extra #3
]
def self.next_piece(board)
MyPiece.new(All_My_Pieces.sample, board)
end
def self.cheat_piece(board)
MyPiece.new([[[0, 0]]], board)
end
end
class MyBoard < Board
def initialize(game)
super
@current_block = MyPiece.next_piece(self)
end
def next_piece
if self.cheated?
@current_block = MyPiece.cheat_piece(self)
@cheated = false
else
@current_block = MyPiece.next_piece(self)
end
@current_pos = nil
end
def store_current
locations = @current_block.current_rotation
displacement = @current_block.position
locations.each_with_index do |current, index|
@grid[current[1]+displacement[1]][current[0]+displacement[0]] =
@current_pos[index]
end
remove_filled
@delay = [@delay - 2, 80].max
end
def cheat
if @score > 100 && !self.cheated?
@score -= 100
@cheated = true
end
end
def cheated?
@cheated ||= false
@cheated
end
end
class MyTetris < Tetris
def set_board
@canvas = TetrisCanvas.new
@board = MyBoard.new(self)
@canvas.place(@board.block_size * @board.num_rows + 3,
@board.block_size * @board.num_columns + 6, 24, 80)
@board.draw
end
def key_bindings
@root.bind('u', proc { 2.times { @board.rotate_clockwise } })
@root.bind('c', proc { @board.cheat })
super
end
end
fix first extra piece
# University of Washington, Programming Languages, Homework 6, hw6runner.rb
# This is the only file you turn in, so do not modify the other files as
# part of your solution.
class MyPiece < Piece
All_My_Pieces = [[[[0, 0], [1, 0], [0, 1], [1, 1]]],
rotations([[0, 0], [-1, 0], [1, 0], [0, -1]]), # T
[[[0, 0], [-1, 0], [1, 0], [2, 0]], # long (only needs two)
[[0, 0], [0, -1], [0, 1], [0, 2]]],
rotations([[0, 0], [0, -1], [0, 1], [1, 1]]), # L
rotations([[0, 0], [0, -1], [0, 1], [-1, 1]]), # inverted L
rotations([[0, 0], [-1, 0], [0, -1], [1, -1]]), # S
rotations([[0, 0], [1, 0], [0, -1], [-1, -1]]),
[[[0, 0], [-1, 0], [1, 0], [2, 0], [3, 0]], # extra #2 very long (only needs two)
[[0, 0], [0, -1], [0, 1], [0, 2], [0, 3]]],
rotations([[0, 0], [-1, 0], [0, -1], [0, 1], [-1, 1]]), # extra #1
rotations([[0,0], [0,1], [1,0]]) #extra #3
]
def self.next_piece(board)
MyPiece.new(All_My_Pieces.sample, board)
end
def self.cheat_piece(board)
MyPiece.new([[[0, 0]]], board)
end
end
class MyBoard < Board
def initialize(game)
super
@current_block = MyPiece.next_piece(self)
end
def next_piece
if self.cheated?
@current_block = MyPiece.cheat_piece(self)
@cheated = false
else
@current_block = MyPiece.next_piece(self)
end
@current_pos = nil
end
def store_current
locations = @current_block.current_rotation
displacement = @current_block.position
locations.each_with_index do |current, index|
@grid[current[1]+displacement[1]][current[0]+displacement[0]] =
@current_pos[index]
end
remove_filled
@delay = [@delay - 2, 80].max
end
def cheat
if @score > 100 && !self.cheated?
@score -= 100
@cheated = true
end
end
def cheated?
@cheated ||= false
@cheated
end
end
class MyTetris < Tetris
def set_board
@canvas = TetrisCanvas.new
@board = MyBoard.new(self)
@canvas.place(@board.block_size * @board.num_rows + 3,
@board.block_size * @board.num_columns + 6, 24, 80)
@board.draw
end
def key_bindings
@root.bind('u', proc { 2.times { @board.rotate_clockwise } })
@root.bind('c', proc { @board.cheat })
super
end
end
|
#
# Be sure to run `pod spec lint Evrythng-iOS.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "EvrythngiOS"
s.version = "0.0.1"
s.summary = "iOS variant of the Evrythng Platform SDK"
s.description = 'evrythng-ios-sdk is an SDK to be used when developing iOS enabled Applications using the Evrythng Platform.'
s.homepage = 'https://github.com/imfree-jdcastro/Evrythng-iOS-SDK'
s.license = { :type => 'MIT', :file => 'license.md'}
s.authors = { 'JD Castro' => 'jd@imfreemobile.com' }
s.platform = :ios, '10.0'
s.source = { :git => 'https://github.com/imfree-jdcastro/Evrythng-iOS-SDK.git', :tag => '0.0.103' }
s.source_files = 'Evrythng-iOS', 'Evrythng-iOS/**/*.{h,m,swift}'
s.exclude_files = 'Classes/Exclude'
#s.resources = 'Evrythng-iOS/*.mp3'
s.ios.deployment_target = '10.0'
s.ios.framework = 'UIKit'
s.requires_arc = true
s.default_subspecs = 'All'
s.subspec 'All' do |all|
all.dependency 'EvrythngiOS/Scan'
end
s.subspec 'Scan' do |scan|
scan.ios.vendored_frameworks = ['Pods/GoogleInterchangeUtilities/Frameworks/frameworks/GoogleInterchangeUtilities.framework',
'Pods/GoogleMobileVision/BarcodeDetector/Frameworks/frameworks/BarcodeDetector.framework',
'Pods/GoogleMobileVision/Detector/Frameworks/frameworks/GoogleMobileVision.framework',
'Pods/GoogleNetworkingUtilities/Frameworks/frameworks/GoogleNetworkingUtilities.framework',
'Pods/GoogleSymbolUtilities/Frameworks/frameworks/GoogleSymbolUtilities.framework',
'Pods/GoogleUtilities/Frameworks/frameworks/GoogleUtilities.framework',
]
#scan.source_files = ['Pods/GoogleMobileVision/Detector/Frameworks/frameworks/GoogleMobileVision.framework/Headers/*.h']
scan.source_files = ['EvrythngiOSFrameworks/GoogleMobileVision.framework/Headers/*.h']
#scan.public_header_files = ['EvrythngiOSFrameworks/GoogleMobileVision.framework/Headers/GMVDetector.h',
# 'EvrythngiOSFrameworks/GoogleMobileVision.framework/Headers/GMVDetectorConstants.h',
# 'EvrythngiOSFrameworks/GoogleMobileVision.framework/Headers/GMVFeature.h',
# 'EvrythngiOSFrameworks/GoogleMobileVision.framework/Headers/GMVUtility.h']
scan.dependency 'GooglegMobileVision/BarcodeDetector'
end
s.pod_target_xcconfig = { 'SWIFT_VERSION' => '3' }
s.dependency 'Alamofire', '~> 4.4'
s.dependency 'AlamofireObjectMapper', '~> 4.1'
s.dependency 'SwiftyJSON', '~> 3.1'
s.dependency 'Moya', '~> 8.0.3'
s.dependency 'MoyaSugar', '~> 0.4'
s.dependency 'Moya-SwiftyJSONMapper', '~> 2.2'
s.dependency 'KRProgressHUD'
end
0.0.104
#
# Be sure to run `pod spec lint Evrythng-iOS.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "EvrythngiOS"
s.version = "0.0.1"
s.summary = "iOS variant of the Evrythng Platform SDK"
s.description = 'evrythng-ios-sdk is an SDK to be used when developing iOS enabled Applications using the Evrythng Platform.'
s.homepage = 'https://github.com/imfree-jdcastro/Evrythng-iOS-SDK'
s.license = { :type => 'MIT', :file => 'license.md'}
s.authors = { 'JD Castro' => 'jd@imfreemobile.com' }
s.platform = :ios, '10.0'
s.source = { :git => 'https://github.com/imfree-jdcastro/Evrythng-iOS-SDK.git', :tag => '0.0.104' }
s.source_files = 'Evrythng-iOS', 'Evrythng-iOS/**/*.{h,m,swift}'
s.exclude_files = 'Classes/Exclude'
#s.resources = 'Evrythng-iOS/*.mp3'
s.ios.deployment_target = '10.0'
s.ios.framework = 'UIKit'
s.requires_arc = true
s.default_subspecs = 'All'
s.subspec 'All' do |all|
all.dependency 'EvrythngiOS/Scan'
end
s.subspec 'Scan' do |scan|
scan.ios.vendored_frameworks = ['Pods/GoogleInterchangeUtilities/Frameworks/frameworks/GoogleInterchangeUtilities.framework',
'Pods/GoogleMobileVision/BarcodeDetector/Frameworks/frameworks/BarcodeDetector.framework',
'Pods/GoogleMobileVision/Detector/Frameworks/frameworks/GoogleMobileVision.framework',
'Pods/GoogleNetworkingUtilities/Frameworks/frameworks/GoogleNetworkingUtilities.framework',
'Pods/GoogleSymbolUtilities/Frameworks/frameworks/GoogleSymbolUtilities.framework',
'Pods/GoogleUtilities/Frameworks/frameworks/GoogleUtilities.framework',
]
#scan.source_files = ['Pods/GoogleMobileVision/Detector/Frameworks/frameworks/GoogleMobileVision.framework/Headers/*.h']
scan.source_files = ['EvrythngiOSFrameworks/GoogleMobileVision.framework/Headers/*.h']
#scan.public_header_files = ['EvrythngiOSFrameworks/GoogleMobileVision.framework/Headers/GMVDetector.h',
# 'EvrythngiOSFrameworks/GoogleMobileVision.framework/Headers/GMVDetectorConstants.h',
# 'EvrythngiOSFrameworks/GoogleMobileVision.framework/Headers/GMVFeature.h',
# 'EvrythngiOSFrameworks/GoogleMobileVision.framework/Headers/GMVUtility.h']
scan.dependency 'GoogleMobileVision/BarcodeDetector'
end
s.pod_target_xcconfig = { 'SWIFT_VERSION' => '3' }
s.dependency 'Alamofire', '~> 4.4'
s.dependency 'AlamofireObjectMapper', '~> 4.1'
s.dependency 'SwiftyJSON', '~> 3.1'
s.dependency 'Moya', '~> 8.0.3'
s.dependency 'MoyaSugar', '~> 0.4'
s.dependency 'Moya-SwiftyJSONMapper', '~> 2.2'
s.dependency 'KRProgressHUD'
end
|
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/seeclickfix/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = 'seeclickfix'
gem.version = SeeClickFix::VERSION
gem.author = "Ryan Resella"
gem.email = 'ryan@codeforamerica.org'
gem.homepage = 'https://github.com/codeforamerica/seeclickfix_rb'
gem.summary = gem.description
gem.description = %q{A Ruby wrapper for the SeeClickFix API}
gem.files = `git ls-files`.split("\n")
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)}
gem.require_paths = ['lib']
gem.add_development_dependency 'maruku', '~> 0.6'
gem.add_development_dependency 'rake', '~> 0.9'
gem.add_development_dependency 'rspec', '~> 2.6'
gem.add_development_dependency 'simplecov', '~> 0.5.3'
gem.add_development_dependency 'webmock', '~> 1.7'
gem.add_development_dependency 'yard', '~> 0.7'
gem.add_runtime_dependency 'addressable', '~> 2.2.6'
gem.add_runtime_dependency 'faraday', '~> 0.7.4'
gem.add_runtime_dependency 'faraday_middleware', '~> 0.6.0'
gem.add_runtime_dependency 'hashie', '~> 1.0.0'
gem.add_runtime_dependency 'multi_json', '~> 1.0.2'
gem.add_runtime_dependency 'rash', '~> 0.3.0'
end
Udpate faraday_middleware to 0.7.0
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/seeclickfix/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = 'seeclickfix'
gem.version = SeeClickFix::VERSION
gem.author = "Ryan Resella"
gem.email = 'ryan@codeforamerica.org'
gem.homepage = 'https://github.com/codeforamerica/seeclickfix_rb'
gem.summary = gem.description
gem.description = %q{A Ruby wrapper for the SeeClickFix API}
gem.files = `git ls-files`.split("\n")
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)}
gem.require_paths = ['lib']
gem.add_development_dependency 'maruku', '~> 0.6'
gem.add_development_dependency 'rake', '~> 0.9'
gem.add_development_dependency 'rspec', '~> 2.6'
gem.add_development_dependency 'simplecov', '~> 0.5.3'
gem.add_development_dependency 'webmock', '~> 1.7'
gem.add_development_dependency 'yard', '~> 0.7'
gem.add_runtime_dependency 'addressable', '~> 2.2.6'
gem.add_runtime_dependency 'faraday', '~> 0.7.4'
gem.add_runtime_dependency 'faraday_middleware', '~> 0.7.0'
gem.add_runtime_dependency 'hashie', '~> 1.0.0'
gem.add_runtime_dependency 'multi_json', '~> 1.0.2'
gem.add_runtime_dependency 'rash', '~> 0.3.0'
end
|
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{selenium-rc}
s.version = "1.0.20090112"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Pivotal Labs", "Nate Clark", "Brian Takita", "Chad Woolley"]
s.date = %q{2009-05-11}
s.default_executable = %q{selenium-rc}
s.description = %q{The Selenium RC Server packaged as a gem}
s.email = %q{pivotallabsopensource@googlegroups.com}
s.executables = ["selenium-rc"]
s.extensions = ["Rakefile"]
s.extra_rdoc_files = ["README.markdown"]
s.files = ["Rakefile", "README.markdown", "VERSION.yml", "bin/selenium-rc", "lib/selenium_rc", "lib/selenium_rc/server.rb", "lib/selenium_rc.rb", "spec/install_and_run_spec.rb", "spec/spec_helper.rb", "spec/spec_suite.rb", "vendor/empty.txt", "vendor/selenium-server.jar"]
s.homepage = %q{http://github.com/pivotal/selenium-rc}
s.rdoc_options = ["--inline-source", "--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.3}
s.summary = %q{The Selenium RC Server packaged as a gem.}
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
Regenerated gemspec for version 1.1.0
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{selenium-rc}
s.version = "1.1.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Pivotal Labs", "Nate Clark", "Brian Takita", "Chad Woolley"]
s.date = %q{2009-05-11}
s.default_executable = %q{selenium-rc}
s.description = %q{The Selenium RC Server packaged as a gem}
s.email = %q{pivotallabsopensource@googlegroups.com}
s.executables = ["selenium-rc"]
s.extensions = ["Rakefile"]
s.extra_rdoc_files = ["README.markdown"]
s.files = ["Rakefile", "README.markdown", "VERSION.yml", "bin/selenium-rc", "lib/selenium_rc", "lib/selenium_rc/server.rb", "lib/selenium_rc.rb", "spec/install_and_run_spec.rb", "spec/spec_helper.rb", "spec/spec_suite.rb", "vendor/empty.txt", "vendor/selenium-server.jar"]
s.homepage = %q{http://github.com/pivotal/selenium-rc}
s.rdoc_options = ["--inline-source", "--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.3}
s.summary = %q{The Selenium RC Server packaged as a gem.}
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<rubyzip>, [">= 0"])
else
s.add_dependency(%q<rubyzip>, [">= 0"])
end
else
s.add_dependency(%q<rubyzip>, [">= 0"])
end
end
|
#
# Author:: Jake Vanderdray <jvanderdray@customink.com>
# Cookbook Name:: nagios
# Provider:: nrpecheck
#
# Copyright 2011, CustomInk LLC
#
# 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.
action :add do
Chef::Log.info "Adding #{new_resource.command_name} to #{node['nagios']['nrpe']['conf_dir']}/nrpe.d/"
command = new_resource.command || "#{node['nagios']['plugin_dir']}/#{new_resource.command_name}"
template "#{node['nagios']['nrpe']['conf_dir']}/nrpe.d/#{new_resource.command_name}.cfg" do
source "nrpe_command.cfg.erb"
owner "root"
group "root"
mode 0644
variables(
:command_name => new_resource.command_name,
:command => command,
:warning_condition => new_resource.warning_condition,
:critical_condition => new_resource.critical_condition,
:parameters => new_resource.parameters
)
notifies :restart, "service[nagios-nrpe-server]"
end
end
action :remove do
if ::File.exists?("#{node['nagios']['nrpe']['conf_dir']}/nrpe.d/#{new_resource.command_name}.cfg")
Chef::Log.info "Removing #{new_resource.command_name} from #{node['nagios']['nrpe']['conf_dir']}/nrpe.d/"
file "#{node['nagios']['nrpe']['conf_dir']}/nrpe.d/#{new_resource.command_name}.cfg" do
action :delete
notifies :restart, "service[nagios-nrpe-server]"
end
end
end
Adding some protection in case the nagios_services data bag doesn't exist or is empty.
#
# Author:: Jake Vanderdray <jvanderdray@customink.com>
# Cookbook Name:: nagios
# Provider:: nrpecheck
#
# Copyright 2011, CustomInk LLC
#
# 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.
action :add do
Chef::Log.info "Adding #{new_resource.command_name} to #{node['nagios']['nrpe']['conf_dir']}/nrpe.d/"
command = new_resource.command || "#{node['nagios']['plugin_dir']}/#{new_resource.command_name}"
template "#{node['nagios']['nrpe']['conf_dir']}/nrpe.d/#{new_resource.command_name}.cfg" do
source "nrpe_command.cfg.erb"
owner "root"
group "root"
mode 0644
variables(
:command_name => new_resource.command_name,
:command => command,
:warning_condition => new_resource.warning_condition,
:critical_condition => new_resource.critical_condition,
:parameters => new_resource.parameters
)
notifies :restart, resources(:service => "nagios-nrpe-server")
end
end
action :remove do
if ::File.exists?("#{node['nagios']['nrpe']['conf_dir']}/nrpe.d/#{new_resource.command_name}.cfg")
Chef::Log.info "Removing #{new_resource.command_name} from #{node['nagios']['nrpe']['conf_dir']}/nrpe.d/"
file "#{node['nagios']['nrpe']['conf_dir']}/nrpe.d/#{new_resource.command_name}.cfg" do
action :delete
notifies :restart, "service[nagios-nrpe-server]"
end
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
# stub: git_presenter 1.2.0 ruby lib
Gem::Specification.new do |s|
s.name = "git_presenter"
s.version = "1.2.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Colin Gemmell"]
s.date = "2014-07-09"
s.description = "Code presentation tool using git"
s.email = "pythonandchips@gmail.com"
s.executables = ["git-presenter"]
s.extra_rdoc_files = [
"LICENSE.txt",
"README.markdown"
]
s.files = [
".rspec",
".travis.yml",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.markdown",
"Rakefile",
"VERSION",
"bin/git-presenter",
"git_presenter.gemspec",
"lib/git_presenter.rb",
"lib/git_presenter/controller.rb",
"lib/git_presenter/presentation.rb",
"lib/git_presenter/shell.rb",
"lib/git_presenter/slide.rb",
"spec/bugs/max_10_commits_being_parsed_spec.rb",
"spec/integration/initialize_presentation_spec.rb",
"spec/integration/moving_through_presentation_spec.rb",
"spec/integration/start_presentation_spec.rb",
"spec/integration/update_presentation_spec.rb",
"spec/lib/git_presenter/controller_spec.rb",
"spec/lib/git_presenter/presentation_spec.rb",
"spec/lib/git_presenter/slide_spec.rb",
"spec/spec_helper.rb",
"spec/support/command_line_helper.rb",
"spec/support/git_helpers.rb"
]
s.homepage = "http://github.com/pythonandchips/git-presenter"
s.licenses = ["MIT"]
s.rubygems_version = "2.2.2"
s.summary = "Code presentation tool using git"
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<git>, [">= 0"])
s.add_runtime_dependency(%q<launchy>, ["~> 2.1"])
s.add_development_dependency(%q<pry>, [">= 0"])
s.add_development_dependency(%q<rspec>, ["~> 2.7"])
s.add_development_dependency(%q<bundler>, [">= 0"])
s.add_development_dependency(%q<jeweler>, ["~> 1.6"])
else
s.add_dependency(%q<git>, [">= 0"])
s.add_dependency(%q<launchy>, ["~> 2.1"])
s.add_dependency(%q<pry>, [">= 0"])
s.add_dependency(%q<rspec>, ["~> 2.7"])
s.add_dependency(%q<bundler>, [">= 0"])
s.add_dependency(%q<jeweler>, ["~> 1.6"])
end
else
s.add_dependency(%q<git>, [">= 0"])
s.add_dependency(%q<launchy>, ["~> 2.1"])
s.add_dependency(%q<pry>, [">= 0"])
s.add_dependency(%q<rspec>, ["~> 2.7"])
s.add_dependency(%q<bundler>, [">= 0"])
s.add_dependency(%q<jeweler>, ["~> 1.6"])
end
end
Regenerate gemspec for version 1.3.0
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
# stub: git_presenter 1.3.0 ruby lib
Gem::Specification.new do |s|
s.name = "git_presenter".freeze
s.version = "1.3.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Colin Gemmell".freeze]
s.date = "2021-01-11"
s.description = "Code presentation tool using git".freeze
s.email = "pythonandchips@gmail.com".freeze
s.executables = ["git-presenter".freeze]
s.extra_rdoc_files = [
"LICENSE.txt",
"README.markdown"
]
s.files = [
".rspec",
".travis.yml",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.markdown",
"Rakefile",
"VERSION",
"bin/git-presenter",
"git_presenter.gemspec",
"lib/git_presenter.rb",
"lib/git_presenter/controller.rb",
"lib/git_presenter/presentation.rb",
"lib/git_presenter/shell.rb",
"lib/git_presenter/slide.rb",
"spec/bugs/max_10_commits_being_parsed_spec.rb",
"spec/integration/initialize_presentation_spec.rb",
"spec/integration/moving_through_presentation_spec.rb",
"spec/integration/start_presentation_spec.rb",
"spec/integration/update_presentation_spec.rb",
"spec/lib/git_presenter/controller_spec.rb",
"spec/lib/git_presenter/presentation_spec.rb",
"spec/lib/git_presenter/slide_spec.rb",
"spec/spec_helper.rb",
"spec/support/command_line_helper.rb",
"spec/support/git_helpers.rb"
]
s.homepage = "http://github.com/pythonandchips/git-presenter".freeze
s.licenses = ["MIT".freeze]
s.rubygems_version = "3.2.3".freeze
s.summary = "Code presentation tool using git".freeze
if s.respond_to? :specification_version then
s.specification_version = 4
end
if s.respond_to? :add_runtime_dependency then
s.add_runtime_dependency(%q<git>.freeze, [">= 0"])
s.add_runtime_dependency(%q<launchy>.freeze, ["~> 2.5"])
s.add_development_dependency(%q<pry>.freeze, [">= 0"])
s.add_development_dependency(%q<rspec>.freeze, ["~> 2.7"])
s.add_development_dependency(%q<bundler>.freeze, [">= 0"])
s.add_development_dependency(%q<jeweler>.freeze, ["~> 2.3"])
else
s.add_dependency(%q<git>.freeze, [">= 0"])
s.add_dependency(%q<launchy>.freeze, ["~> 2.5"])
s.add_dependency(%q<pry>.freeze, [">= 0"])
s.add_dependency(%q<rspec>.freeze, ["~> 2.7"])
s.add_dependency(%q<bundler>.freeze, [">= 0"])
s.add_dependency(%q<jeweler>.freeze, ["~> 2.3"])
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'icaprb/server/version'
Gem::Specification.new do |spec|
spec.name = "icaprb-server"
spec.version = ICAPrb::Server::VERSION
spec.authors = ["Fabian Franz"]
spec.email = ["fabian.franz@students.fh-hagenberg.at"]
spec.summary = %q{This project includes an ICAP server fully implemented in Ruby but it does not include services.}
spec.homepage = "TODO: Put your gem's website or public repo URL here."
# Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
# delete this section to allow pushing this gem to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
end
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_development_dependency "bundler", "~> 1.11"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
end
fix gemspec
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'icaprb/server/version'
Gem::Specification.new do |spec|
spec.name = "icaprb-server"
spec.version = ICAPrb::Server::VERSION
spec.authors = ["Fabian Franz"]
spec.email = ["fabian.franz@students.fh-hagenberg.at"]
spec.summary = %q{This project includes an ICAP server fully implemented in Ruby but it does not include services.}
spec.homepage = "https://github.com/fabianfrz/ICAPrb-Server"
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_development_dependency "bundler", "~> 1.11"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'idonethis_cli/version'
Gem::Specification.new do |spec|
spec.name = "idonethis-cli"
spec.version = IdonethisCli::VERSION
spec.authors = ["Shane Mingins"]
spec.email = ["shane@idonethis.com"]
spec.summary = %q{Write a short summary, because Rubygems requires one.}
spec.description = %q{Write a longer description or delete this line.}
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "bin"
spec.executables = ["idt"]
spec.require_paths = ["lib"]
spec.add_dependency 'thor'
spec.add_dependency 'highline'
spec.add_dependency 'oauth2'
spec.add_development_dependency "bundler", "~> 1.12"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
end
Name migration.
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'idonethis_cli/version'
Gem::Specification.new do |spec|
spec.name = "idonethis-official-cli"
spec.version = IdonethisCli::VERSION
spec.authors = ["Shane Mingins"]
spec.email = ["shane@idonethis.com"]
spec.summary = %q{Write a short summary, because Rubygems requires one.}
spec.description = %q{Write a longer description or delete this line.}
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "bin"
spec.executables = ["idt"]
spec.require_paths = ["lib"]
spec.add_dependency 'thor'
spec.add_dependency 'highline'
spec.add_dependency 'oauth2'
spec.add_development_dependency "bundler", "~> 1.12"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
end
|
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "enju_question/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "enju_question"
s.version = EnjuQuestion::VERSION
s.authors = ["Kosuke Tanabe"]
s.email = ["tanabe@mwr.mediacom.keio.ac.jp"]
s.homepage = "https://github.com/next-l/enju_question"
s.summary = "enju_queestion plugin"
s.description = "Question and answer management for Next-L Enju"
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["spec/**/*"] - Dir["spec/dummy/log/*"] - Dir["spec/dummy/solr/{data,pids}/*"]
s.add_dependency "rails", "~> 3.2"
s.add_dependency "enju_core", "~> 0.1.1.pre6"
s.add_dependency "simple_form"
s.add_dependency "acts-as-taggable-on", "~> 2.4"
s.add_dependency "rails_autolink"
s.add_development_dependency "sqlite3"
s.add_development_dependency "rspec-rails"
s.add_development_dependency "factory_girl_rails"
s.add_development_dependency "vcr", "~> 2.7"
s.add_development_dependency "enju_leaf", "~> 1.1.0.rc7"
s.add_development_dependency "enju_ndl", "~> 0.1.0.pre27"
s.add_development_dependency "sunspot_solr", "~> 2.1"
s.add_development_dependency "fakeweb"
s.add_development_dependency "sunspot-rails-tester"
end
updated acts-as-taggable-on
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "enju_question/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "enju_question"
s.version = EnjuQuestion::VERSION
s.authors = ["Kosuke Tanabe"]
s.email = ["tanabe@mwr.mediacom.keio.ac.jp"]
s.homepage = "https://github.com/next-l/enju_question"
s.summary = "enju_queestion plugin"
s.description = "Question and answer management for Next-L Enju"
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["spec/**/*"] - Dir["spec/dummy/log/*"] - Dir["spec/dummy/solr/{data,pids}/*"]
s.add_dependency "rails", "~> 3.2"
s.add_dependency "enju_core", "~> 0.1.1.pre6"
s.add_dependency "simple_form"
s.add_dependency "acts-as-taggable-on", "~> 3.0"
s.add_dependency "rails_autolink"
s.add_development_dependency "sqlite3"
s.add_development_dependency "rspec-rails"
s.add_development_dependency "factory_girl_rails"
s.add_development_dependency "vcr", "~> 2.7"
s.add_development_dependency "enju_leaf", "~> 1.1.0.rc7"
s.add_development_dependency "enju_ndl", "~> 0.1.0.pre29"
s.add_development_dependency "sunspot_solr", "~> 2.1"
s.add_development_dependency "fakeweb"
s.add_development_dependency "sunspot-rails-tester"
end
|
# -*- encoding: utf-8 -*-
require File.expand_path("../lib/fit_commit/version", __FILE__)
Gem::Specification.new do |gem|
gem.name = "fit-commit"
gem.version = FitCommit::VERSION
gem.license = "MIT"
gem.authors = ["Michael Foley"]
gem.email = ["foley3@gmail.com"]
gem.homepage = "https://github.com/m1foley/fit-commit"
gem.summary = "A Git hook to validate your commit messages"
gem.description = "A Git hook to validate your commit messages based on community standards."
gem.files = `git ls-files`.split("\n")
gem.executables = ["fit-commit"]
gem.test_files = `git ls-files -- test/*`.split("\n")
gem.require_paths = ["lib"]
gem.extra_rdoc_files = ["README.md"]
gem.rdoc_options = ["--main", "README.md"]
gem.post_install_message = <<-EOF
Install Fit Commit hooks in each git repo you want to scan using:
> fit-commit install
Read more: https://github.com/m1foley/fit-commit#readme
EOF
gem.add_dependency("swearjar", "~> 1.3")
gem.add_development_dependency("minitest", "~> 5.11")
gem.add_development_dependency("rake", "~> 12.3")
end
Update development dependency versions
Unimportant version bumps; no important changes.
# -*- encoding: utf-8 -*-
require File.expand_path("../lib/fit_commit/version", __FILE__)
Gem::Specification.new do |gem|
gem.name = "fit-commit"
gem.version = FitCommit::VERSION
gem.license = "MIT"
gem.authors = ["Michael Foley"]
gem.email = ["foley3@gmail.com"]
gem.homepage = "https://github.com/m1foley/fit-commit"
gem.summary = "A Git hook to validate your commit messages"
gem.description = "A Git hook to validate your commit messages based on community standards."
gem.files = `git ls-files`.split("\n")
gem.executables = ["fit-commit"]
gem.test_files = `git ls-files -- test/*`.split("\n")
gem.require_paths = ["lib"]
gem.extra_rdoc_files = ["README.md"]
gem.rdoc_options = ["--main", "README.md"]
gem.post_install_message = <<-EOF
Install Fit Commit hooks in each git repo you want to scan using:
> fit-commit install
Read more: https://github.com/m1foley/fit-commit#readme
EOF
gem.add_dependency("swearjar", "~> 1.4")
gem.add_development_dependency("minitest", "~> 5.14")
gem.add_development_dependency("rake", "~> 13.0")
end
|
set :application, "railscasts.com"
role :app, application
role :web, application
role :db, application, :primary => true
set :user, "deploy"
set :deploy_to, "/var/www/apps/#{application}"
set :deploy_via, :remote_cache
set :use_sudo, false
set :scm, "git"
set :repository, "git://github.com/ryanb/railscasts.git"
set :branch, "master"
namespace :deploy do
task :restart do
run "touch #{current_path}/tmp/restart.txt"
end
task :symlink_shared do
run "ln -nfs #{shared_path}/config/database.yml #{release_path}/config/database.yml"
run "ln -nfs #{shared_path}/assets #{release_path}/public/assets"
end
task :assets do
system "rsync -vr --exclude='.DS_Store' public/assets #{user}@#{application}:#{shared_path}/"
end
end
after 'deploy:update_code', 'deploy:symlink_shared'
adding desc docs for episode 133
set :application, "railscasts.com"
role :app, application
role :web, application
role :db, application, :primary => true
set :user, "deploy"
set :deploy_to, "/var/www/apps/#{application}"
set :deploy_via, :remote_cache
set :use_sudo, false
set :scm, "git"
set :repository, "git://github.com/ryanb/railscasts.git"
set :branch, "master"
namespace :deploy do
desc "Tell Passenger to restart the app."
task :restart do
run "touch #{current_path}/tmp/restart.txt"
end
desc "Symlink shared configs and folders on each release."
task :symlink_shared do
run "ln -nfs #{shared_path}/config/database.yml #{release_path}/config/database.yml"
run "ln -nfs #{shared_path}/assets #{release_path}/public/assets"
end
desc "Sync the public/assets directory."
task :assets do
system "rsync -vr --exclude='.DS_Store' public/assets #{user}@#{application}:#{shared_path}/"
end
end
after 'deploy:update_code', 'deploy:symlink_shared' |
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "inteltech_sms"
s.version = "1.1.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Ian Heggie"]
s.date = "2014-02-17"
s.description = "Ruby gem that provides an InteltechSms class to check credit and send SMS text messages to single or multiple recipients"
s.email = "ian@heggie.biz"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".coveralls.yml",
".document",
".travis.yml",
"Gemfile",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"inteltech_sms.gemspec",
"lib/dummy_inteltech_sms.rb",
"lib/inteltech_sms.rb",
"test/helper.rb",
"test/test_dummy_inteltech_sms.rb",
"test/test_inteltech_sms.rb"
]
s.homepage = "http://github.com/ianheggie/inteltech_sms"
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = "1.8.23"
s.summary = "Ruby Gem to send SMS via inteltech.com.au"
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<rdoc>, [">= 3.12"])
s.add_development_dependency(%q<bundler>, [">= 1.2.3"])
s.add_development_dependency(%q<jeweler>, [">= 1.8.4"])
s.add_development_dependency(%q<travis>, [">= 1.6.0"])
s.add_development_dependency(%q<travis-lint>, [">= 0"])
s.add_development_dependency(%q<shoulda-context>, [">= 0"])
s.add_development_dependency(%q<coveralls>, [">= 0"])
else
s.add_dependency(%q<rdoc>, [">= 3.12"])
s.add_dependency(%q<bundler>, [">= 1.2.3"])
s.add_dependency(%q<jeweler>, [">= 1.8.4"])
s.add_dependency(%q<travis>, [">= 1.6.0"])
s.add_dependency(%q<travis-lint>, [">= 0"])
s.add_dependency(%q<shoulda-context>, [">= 0"])
s.add_dependency(%q<coveralls>, [">= 0"])
end
else
s.add_dependency(%q<rdoc>, [">= 3.12"])
s.add_dependency(%q<bundler>, [">= 1.2.3"])
s.add_dependency(%q<jeweler>, [">= 1.8.4"])
s.add_dependency(%q<travis>, [">= 1.6.0"])
s.add_dependency(%q<travis-lint>, [">= 0"])
s.add_dependency(%q<shoulda-context>, [">= 0"])
s.add_dependency(%q<coveralls>, [">= 0"])
end
end
Regenerate gemspec for version 1.1.2
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "inteltech_sms"
s.version = "1.1.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Ian Heggie"]
s.date = "2014-05-17"
s.description = "Ruby gem that provides an InteltechSms class to check credit and send SMS text messages to single or multiple recipients"
s.email = "ian@heggie.biz"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".coveralls.yml",
".document",
".travis.yml",
"Gemfile",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"inteltech_sms.gemspec",
"lib/dummy_inteltech_sms.rb",
"lib/inteltech_sms.rb",
"test/helper.rb",
"test/test_dummy_inteltech_sms.rb",
"test/test_inteltech_sms.rb"
]
s.homepage = "http://github.com/ianheggie/inteltech_sms"
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = "1.8.23.2"
s.summary = "Ruby Gem to send SMS via inteltech.com.au"
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<rdoc>, [">= 3.12"])
s.add_development_dependency(%q<bundler>, [">= 1.2.3"])
s.add_development_dependency(%q<jeweler>, [">= 1.8.4"])
s.add_development_dependency(%q<travis>, [">= 1.6.0"])
s.add_development_dependency(%q<travis-lint>, [">= 0"])
s.add_development_dependency(%q<shoulda-context>, [">= 0"])
s.add_development_dependency(%q<coveralls>, [">= 0"])
s.add_development_dependency(%q<simplecov>, [">= 0"])
else
s.add_dependency(%q<rdoc>, [">= 3.12"])
s.add_dependency(%q<bundler>, [">= 1.2.3"])
s.add_dependency(%q<jeweler>, [">= 1.8.4"])
s.add_dependency(%q<travis>, [">= 1.6.0"])
s.add_dependency(%q<travis-lint>, [">= 0"])
s.add_dependency(%q<shoulda-context>, [">= 0"])
s.add_dependency(%q<coveralls>, [">= 0"])
s.add_dependency(%q<simplecov>, [">= 0"])
end
else
s.add_dependency(%q<rdoc>, [">= 3.12"])
s.add_dependency(%q<bundler>, [">= 1.2.3"])
s.add_dependency(%q<jeweler>, [">= 1.8.4"])
s.add_dependency(%q<travis>, [">= 1.6.0"])
s.add_dependency(%q<travis-lint>, [">= 0"])
s.add_dependency(%q<shoulda-context>, [">= 0"])
s.add_dependency(%q<coveralls>, [">= 0"])
s.add_dependency(%q<simplecov>, [">= 0"])
end
end
|
require 'open-uri'
class AppStore
def self.find_details_by_url(link)
uri = URI.parse(link)
if uri.host == "itunes.apple.com"
id = uri.path.split("/id").last
details = self.apple_store_data(id)
elsif uri.host == "play.google.com"
params = Rack::Utils.parse_nested_query uri.query
id = params["id"]
details = self.google_store_data(id)
else
details = {}
end
details
end
def self.google_store_data(id)
full_uri = "https://play.google.com/store/apps/details?id=#{id}"
begin
response = Nokogiri::HTML(open(full_uri).read)
date = Date.parse(response.xpath('//*[@itemprop="datePublished"]/text()').to_s.strip)
details = {
platform: "Android",
version: response.xpath('//*[@itemprop="softwareVersion"]/text()').to_s.strip,
average_rating: response.xpath('//*[@itemprop="aggregateRating"]//meta[@itemprop="ratingValue"]/@content').to_s.strip,
number_of_ratings: response.xpath('//*[@itemprop="aggregateRating"]//meta[@itemprop="ratingCount"]/@content').to_s.strip,
publish_day: date.day,
publish_month: date.month,
publish_year: date.year,
screenshot: response.xpath('//img[@itemprop="screenshot"]/@src').map(&:to_s).join("\n")
}
rescue Exception => e
Rails.logger.info e.inspect
return {}
end
details
end
def self.apple_store_data(id)
full_uri = "http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/wsLookup?mt=8&id=#{id}"
begin
response = JSON.parse(open(full_uri).read)
if response["resultCount"] == 1
date = Date.parse(response["results"][0]["releaseDate"])
return {
platform: "iOS",
version: response["results"][0]["version"],
average_rating: response["results"][0]["averageUserRating"],
number_of_ratings: response["results"][0]["userRatingCount"],
publish_day: date.day,
publish_month: date.month,
publish_year: date.year,
screenshot: response["results"][0]["screenshotUrls"].join("\n"),
language: response["results"][0]["language"] == "EN" ? "English" : "Spanish"
}
else
return {}
end
rescue Exception => e
Rails.logger.info e.inspect
return {}
end
end
end
adds support for ipad screenshots
require 'open-uri'
class AppStore
def self.find_details_by_url(link)
uri = URI.parse(link)
if uri.host == "itunes.apple.com"
id = uri.path.split("/id").last
details = self.apple_store_data(id)
elsif uri.host == "play.google.com"
params = Rack::Utils.parse_nested_query uri.query
id = params["id"]
details = self.google_store_data(id)
else
details = {}
end
details
end
def self.google_store_data(id)
full_uri = "https://play.google.com/store/apps/details?id=#{id}"
begin
response = Nokogiri::HTML(open(full_uri).read)
date = Date.parse(response.xpath('//*[@itemprop="datePublished"]/text()').to_s.strip)
details = {
platform: "Android",
version: response.xpath('//*[@itemprop="softwareVersion"]/text()').to_s.strip,
average_rating: response.xpath('//*[@itemprop="aggregateRating"]//meta[@itemprop="ratingValue"]/@content').to_s.strip,
number_of_ratings: response.xpath('//*[@itemprop="aggregateRating"]//meta[@itemprop="ratingCount"]/@content').to_s.strip,
publish_day: date.day,
publish_month: date.month,
publish_year: date.year,
screenshot: response.xpath('//img[@itemprop="screenshot"]/@src').map(&:to_s).join("\n")
}
rescue Exception => e
Rails.logger.info e.inspect
return {}
end
details
end
def self.apple_store_data(id)
full_uri = "http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/wsLookup?mt=8&id=#{id}"
begin
response = JSON.parse(open(full_uri).read)
if response["resultCount"] == 1
date = Date.parse(response["results"][0]["releaseDate"])
screenshots = response["results"][0]["screenshotUrls"] + response["results"][0]["ipadScreenshotUrls"]
return {
platform: "iOS",
version: response["results"][0]["version"],
average_rating: response["results"][0]["averageUserRating"],
number_of_ratings: response["results"][0]["userRatingCount"],
publish_day: date.day,
publish_month: date.month,
publish_year: date.year,
screenshot: screenshots.join("\n") ,
language: response["results"][0]["language"] == "EN" ? "English" : "Spanish"
}
else
return {}
end
rescue Exception => e
Rails.logger.info e.inspect
return {}
end
end
end |
require 'bike_number'
# Form object for entering and editing bike data
class BikeForm
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
# include BikeMfg::ActsAsManufacturable
# Bike Attributes
attr_reader :color, :value, :wheel_size, :seat_tube_height,
:top_tube_length, :bike_model_id, :number, :quality, :condition
# Bike object, model and brand attributes
attr_reader :bike
# BikeBrand and BikeModel attribues
attr_reader :bike_brand_name, :bike_model_name, :bike_brand_id
def form_method( action )
m = {:edit => :put, :new => :post}
m[action.to_sym]
end
def initialize(current_bike, params = {})
params ||= {}
@bike = current_bike || Bike.new
# Populate data first from the supplied object
parse_obj(bike)
# Then populate from the optional params
# Populating from params second
# allows supplied params to override persisted
# obj data
parse_params(params)
end
def parse_obj(obj)
bike_params_list.each do |p|
set_val(p, obj.send(p).to_s)
end
bm = obj.model
if bm
set_val(:bike_model_id, bm.id)
set_val(:bike_model_name, bm.name)
set_val(:bike_brand_name, bm.brand.name)
set_val(:bike_brand_id, bm.brand.id)
end
end
def parse_params(data)
data.each do |key, val|
set_val(key, val)
end
end
# Validations
validates_presence_of :number, :color
validates :seat_tube_height,:top_tube_length,:value, :numericality => true, :allow_nil => true
# validates_uniqueness_of :number, :allow_nil => true
#validates :number, :format => { :with => Bike.number_pattern, :message => "Must be 5 digits exactly"}
validates :number, :bike_number => true
# Forms are never themselves persisted
def persisted?
false # || (bike.persisted? if bike)
end
def save
if valid?
persist!
true
else
false
end
end
def self.bike_params_list
[:color, :value, :wheel_size, :seat_tube_height,
:top_tube_length, :bike_model_id,
:number, :quality, :condition]
end
def bike_params_list
self.class.bike_params_list
end
def self.form_params_list
bike_params_list + [:bike_brand_id, :bike_brand_name, :bike_model_name]
end
private
# bike brand and model cases
#
# Case model exists:
# then find create nothing
# then find model by id
#
# Case brand exists, but not the model
# then find brand by id
# then create model and assign to brand
#
# Case neither exist
# then create model and brand from given names
#
def bike_model_assignment!
if BikeModel.find_by_id(bike_model_id)
return bike_model_id
end
# find or create the brand
brand = BikeBrand.find_by_id(bike_brand_id)
brand ||= BikeBrand.new(bike_brand_params)
brand.save if brand && brand.valid?
# Create the bike model
new_model = brand.models.new(bike_model_params) if brand && brand.persisted?
new_model.save if new_model && new_model.valid?
return new_model.id if new_model && new_model.persisted?
end
def bike_brand_params
{:name=>bike_brand_name}
end
def bike_model_params
{:name=>bike_model_name}
end
def persist!
m_id = bike_model_assignment!
bike.update_attributes(
:number => number,
:color => color,
:value => value,
:wheel_size => wheel_size,
:seat_tube_height => seat_tube_height,
:top_tube_length => top_tube_length,
:bike_model_id => m_id
)
bike.save!
end
def set_val(attrib, val)
val = (val.blank?) ? nil : val.to_s
instance_variable_set("@#{attrib}", val)
end
end
assignin bike model using model factory
require 'bike_number'
# Form object for entering and editing bike data
class BikeForm
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
# include BikeMfg::ActsAsManufacturable
# Bike Attributes
attr_reader :color, :value, :wheel_size, :seat_tube_height,
:top_tube_length, :bike_model_id, :number, :quality, :condition
# Bike object, model and brand attributes
attr_reader :bike
# BikeBrand and BikeModel attribues
attr_reader :bike_brand_name, :bike_model_name, :bike_brand_id
def form_method( action )
m = {:edit => :put, :new => :post}
m[action.to_sym]
end
def initialize(current_bike, params = {})
params ||= {}
@bike = current_bike || Bike.new
# Populate data first from the supplied object
parse_obj(bike)
# Then populate from the optional params
# Populating from params second allows
# the supplied params to override
# persisted obj data
parse_params(form_params_list, params) unless params.empty?
end
# Validations
validates_presence_of :number, :color
validates :seat_tube_height,:top_tube_length,:value, :numericality => true, :allow_nil => true
# validates_uniqueness_of :number, :allow_nil => true
#validates :number, :format => { :with => Bike.number_pattern, :message => "Must be 5 digits exactly"}
validates :number, :bike_number => true
# Forms are never themselves persisted
def persisted?
false
end
def save
if valid?
persist!
true
else
false
end
end
def self.bike_params_list
[:color, :value, :wheel_size, :seat_tube_height,
:top_tube_length, :bike_model_id,
:number, :quality, :condition]
end
def bike_params_list
self.class.bike_params_list
end
def self.form_params_list
bike_params_list + [:bike_brand_id, :bike_brand_name, :bike_model_name]
end
def form_params_list
self.class.form_params_list
end
private
def parse_obj(obj)
bike_params_list.each do |p|
set_val(p, obj.send(p).to_s)
end
bm = obj.model
if bm
set_val(:bike_model_id, bm.id)
set_val(:bike_model_name, bm.name)
# Must check that a brand is assigned, since it
# may be unknown (nil)
unless bm.brand.nil?
set_val(:bike_brand_name, bm.brand.name)
set_val(:bike_brand_id, bm.brand.id)
end
end
end
def parse_params(params_list, params_data)
params_list.each do |key|
set_val(key, params_data[key])
end
end
# Get the bike model assignment
# based on the BikeModelFactory for
# the given bike brand and model cases
#
# Cache the assignment for consistency between calls
def bike_model_assignment
if @built_bike_model.nil?
factory = BikeModelFactory.new(model_factory_params)
@built_bike_model = factory.model unless factory.nil?
end
@built_bike_model
end
def model_factory_params
{
:model_id => bike_model_id,
:model_name => bike_model_name,
:brand_id => bike_brand_id,
:brand_name => bike_brand_name,
:brand_scope => BikeBrand,
:model_scope => BikeModel,
:param_prefix => :bike
}
end
def persist!
# update attributes
bike.number = number
bike.color = color
bike.value = value
bike.wheel_size = wheel_size
bike.seat_tube_height = seat_tube_height
bike.top_tube_length = top_tube_length
bike.bike_model = bike_model_assignment
bike.save!
end
def set_val(attrib, val)
val = (val.blank?) ? nil : val.to_s
instance_variable_set("@#{attrib}", val)
end
end
|
require 'active_record'
require_relative '../../helpers/bounding_box_helper'
class Carto::Map < ActiveRecord::Base
has_many :layers_maps
has_many :layers, class_name: 'Carto::Layer',
order: '"order"',
through: :layers_maps
has_many :base_layers, class_name: 'Carto::Layer',
order: '"order"',
through: :layers_maps,
source: :layer
has_many :data_layers, class_name: 'Carto::Layer',
conditions: { kind: 'carto' },
order: '"order"',
through: :layers_maps,
source: :layer
has_many :user_layers, class_name: 'Carto::Layer',
conditions: { kind: ['tiled', 'background', 'gmapsbase', 'wms'] },
order: '"order"',
through: :layers_maps,
source: :layer
has_many :carto_and_torque_layers, class_name: 'Carto::Layer',
conditions: { kind: ['carto', 'torque'] },
order: '"order"',
through: :layers_maps,
source: :layer
has_many :torque_layers, class_name: 'Carto::Layer',
conditions: { kind: 'torque' },
order: '"order"',
through: :layers_maps,
source: :layer
has_many :other_layers, class_name: 'Carto::Layer',
conditions: "kind not in ('carto', 'tiled', 'background', 'gmapsbase', 'wms')",
order: '"order"',
through: :layers_maps,
source: :layer
has_many :named_maps_layers, class_name: 'Carto::Layer',
conditions: { kind: ['carto', 'tiled', 'background', 'gmapsbase', 'wms'] },
order: '"order"',
through: :layers_maps,
source: :layer
has_many :user_tables, class_name: Carto::UserTable, inverse_of: :map
belongs_to :user
has_many :visualizations, class_name: Carto::Visualization, inverse_of: :map
DEFAULT_OPTIONS = {
zoom: 3,
bounding_box_sw: [BoundingBoxHelper::DEFAULT_BOUNDS[:minlat], BoundingBoxHelper::DEFAULT_BOUNDS[:minlon]],
bounding_box_ne: [BoundingBoxHelper::DEFAULT_BOUNDS[:maxlat], BoundingBoxHelper::DEFAULT_BOUNDS[:maxlon]],
provider: 'leaflet',
center: [30, 0]
}.freeze
def viz_updated_at
get_the_last_time_tiles_have_changed_to_render_it_in_vizjsons
end
def self.provider_for_baselayer_kind(kind)
kind == 'tiled' ? 'leaflet' : 'googlemaps'
end
# (lat,lon) points on all map data
def center_data
(center.nil? || center == '') ? DEFAULT_OPTIONS[:center] : center.gsub(/\[|\]|\s*/, '').split(',')
end
def view_bounds_data
if view_bounds_sw.nil? || view_bounds_sw == ''
bbox_sw = DEFAULT_OPTIONS[:bounding_box_sw]
else
bbox_sw = view_bounds_sw.gsub(/\[|\]|\s*/, '').split(',').map(&:to_f)
end
if view_bounds_ne.nil? || view_bounds_ne == ''
bbox_ne = DEFAULT_OPTIONS[:bounding_box_ne]
else
bbox_ne = view_bounds_ne.gsub(/\[|\]|\s*/, '').split(',').map(&:to_f)
end
{
# LowerCorner longitude, in decimal degrees
west: bbox_sw[1],
# LowerCorner latitude, in decimal degrees
south: bbox_sw[0],
# UpperCorner longitude, in decimal degrees
east: bbox_ne[1],
# UpperCorner latitude, in decimal degrees
north: bbox_ne[0]
}
end
def writable_by_user?(user)
!visualizations.select { |v| v.is_writable_by_user(user) }.empty?
end
def contains_layer?(layer)
return false unless layer
layers_maps.map(&:layer_id).include?(layer.id)
end
def notify_map_change
map = ::Map[id]
map.notify_map_change if map
end
private
def get_the_last_time_tiles_have_changed_to_render_it_in_vizjsons
table = user_tables.first
from_table = table.service.data_last_modified if table
[from_table, data_layers.map(&:updated_at)].flatten.compact.max
end
end
add new infalidations for notify map change
require 'active_record'
require_relative '../../helpers/bounding_box_helper'
class Carto::Map < ActiveRecord::Base
has_many :layers_maps
has_many :layers, class_name: 'Carto::Layer',
order: '"order"',
through: :layers_maps
has_many :base_layers, class_name: 'Carto::Layer',
order: '"order"',
through: :layers_maps,
source: :layer
has_many :data_layers, class_name: 'Carto::Layer',
conditions: { kind: 'carto' },
order: '"order"',
through: :layers_maps,
source: :layer
has_many :user_layers, class_name: 'Carto::Layer',
conditions: { kind: ['tiled', 'background', 'gmapsbase', 'wms'] },
order: '"order"',
through: :layers_maps,
source: :layer
has_many :carto_and_torque_layers, class_name: 'Carto::Layer',
conditions: { kind: ['carto', 'torque'] },
order: '"order"',
through: :layers_maps,
source: :layer
has_many :torque_layers, class_name: 'Carto::Layer',
conditions: { kind: 'torque' },
order: '"order"',
through: :layers_maps,
source: :layer
has_many :other_layers, class_name: 'Carto::Layer',
conditions: "kind not in ('carto', 'tiled', 'background', 'gmapsbase', 'wms')",
order: '"order"',
through: :layers_maps,
source: :layer
has_many :named_maps_layers, class_name: 'Carto::Layer',
conditions: { kind: ['carto', 'tiled', 'background', 'gmapsbase', 'wms'] },
order: '"order"',
through: :layers_maps,
source: :layer
has_many :user_tables, class_name: Carto::UserTable, inverse_of: :map
belongs_to :user
has_many :visualizations, class_name: Carto::Visualization, inverse_of: :map
DEFAULT_OPTIONS = {
zoom: 3,
bounding_box_sw: [BoundingBoxHelper::DEFAULT_BOUNDS[:minlat], BoundingBoxHelper::DEFAULT_BOUNDS[:minlon]],
bounding_box_ne: [BoundingBoxHelper::DEFAULT_BOUNDS[:maxlat], BoundingBoxHelper::DEFAULT_BOUNDS[:maxlon]],
provider: 'leaflet',
center: [30, 0]
}.freeze
def viz_updated_at
get_the_last_time_tiles_have_changed_to_render_it_in_vizjsons
end
def self.provider_for_baselayer_kind(kind)
kind == 'tiled' ? 'leaflet' : 'googlemaps'
end
# (lat,lon) points on all map data
def center_data
(center.nil? || center == '') ? DEFAULT_OPTIONS[:center] : center.gsub(/\[|\]|\s*/, '').split(',')
end
def view_bounds_data
if view_bounds_sw.nil? || view_bounds_sw == ''
bbox_sw = DEFAULT_OPTIONS[:bounding_box_sw]
else
bbox_sw = view_bounds_sw.gsub(/\[|\]|\s*/, '').split(',').map(&:to_f)
end
if view_bounds_ne.nil? || view_bounds_ne == ''
bbox_ne = DEFAULT_OPTIONS[:bounding_box_ne]
else
bbox_ne = view_bounds_ne.gsub(/\[|\]|\s*/, '').split(',').map(&:to_f)
end
{
# LowerCorner longitude, in decimal degrees
west: bbox_sw[1],
# LowerCorner latitude, in decimal degrees
south: bbox_sw[0],
# UpperCorner longitude, in decimal degrees
east: bbox_ne[1],
# UpperCorner latitude, in decimal degrees
north: bbox_ne[0]
}
end
def writable_by_user?(user)
!visualizations.select { |v| v.is_writable_by_user(user) }.empty?
end
def contains_layer?(layer)
return false unless layer
layers_maps.map(&:layer_id).include?(layer.id)
end
def notify_map_change
visualizations.each(&:save_named_map)
visualizations.each(&:invalidate_cache)
end
private
def get_the_last_time_tiles_have_changed_to_render_it_in_vizjsons
table = user_tables.first
from_table = table.service.data_last_modified if table
[from_table, data_layers.map(&:updated_at)].flatten.compact.max
end
end
|
class Changelog < ActiveRecord::Base
belongs_to :project
has_many :story_points
has_many :commits
class << self
def parse_pull_requests_and_commits
tags = []
Project.all.each do |project|
p = 1
tags_list = Rails.configuration.github_client.tags(project.github_path, :page => p)
while tags_list.present?
tags += tags_list
p += 1
tags_list = Rails.configuration.github_client.tags(project.github_path, :page => p)
end
tags_with_date = []
tags.each do |tag|
tags_with_date << [tag[:name], parse_date_for(project.github_path, tag[:commit][:sha])]
end
tags_with_date.sort_by! { |tag| tag.last }.each_with_index do |tag, index|
date_from = tag.last
date_to = tags[index + 1].present? ? tags_with_date[index + 1].last : nil
c = Changelog.find_or_create_by(:title => tag.first, :project_id => project.id) do |changelog|
c.github_created_at = date_from.to_datetime
end
# parse_and_save_commits project.github_path, date_from, date_to, changelog
end
tags = []
end
pull_requests = Project.pull_requests
StoryPoint.parse_pull_requests pull_requests
StoryPoint.sync_with_changelogs
end
def parse_and_save_commits(project, date_from, date_to, changelog)
commits = []
p = 1
if date_to.present?
commits_list = Rails.configuration.github_client.commits_between project, date_from, date_to, :page => p
else
commits_list = Rails.configuration.github_client.commits_before project, date_from, :page => p
end
while commits_list.present?
commits += commits_list
p += 1
commits_list = Rails.configuration.github_client.
commits_before(project, date_to, :page => p)
end
commits.each do |commit_params|
Commit.parse_and_save_with commit_params, project, changelog
end
end
def fetch_with(params)
case params[:date]
when 'month'
changelogs = Changelog.where('github_created_at >= ?', DateTime.now - 1.month)
when 'year'
changelogs = Changelog.where('github_created_at >= ?', DateTime.now - 1.year)
else
changelogs = Changelog.all
end
if params[:date_from].present? && params[:date_to].present?
changelogs = changelogs.
where('github_created_at >= ? and github_created_at <= ?',
DateTime.parse(params[:date_from]),
DateTime.parse(params[:date_to])
)
elsif params[:date_from].present?
changelogs.where('github_created_at >= ?', DateTime.parse(params[:date_from]))
elsif params[:date_to].present?
changelogs.where('github_created_at <= ?', DateTime.parse(params[:date_to]))
end
if params[:project].try(:[], 0).present?
changelogs = changelogs.where(:project_id => params[:project][0])
end
changelogs.includes(:story_points)
end
private
def parse_date_for(project, sha)
details = Rails.configuration.github_client.git_commit project, sha
details[:committer][:date]
end
end
end
Fix bug with naming
class Changelog < ActiveRecord::Base
belongs_to :project
has_many :story_points
has_many :commits
class << self
def parse_pull_requests_and_commits
tags = []
Project.all.each do |project|
p = 1
tags_list = Rails.configuration.github_client.tags(project.github_path, :page => p)
while tags_list.present?
tags += tags_list
p += 1
tags_list = Rails.configuration.github_client.tags(project.github_path, :page => p)
end
tags_with_date = []
tags.each do |tag|
tags_with_date << [tag[:name], parse_date_for(project.github_path, tag[:commit][:sha])]
end
tags_with_date.sort_by! { |tag| tag.last }.each_with_index do |tag, index|
date_from = tag.last
date_to = tags[index + 1].present? ? tags_with_date[index + 1].last : nil
c = Changelog.find_or_create_by(:title => tag.first, :project_id => project.id) do |changelog_object|
changelog_object.github_created_at = date_from.to_datetime
end
# parse_and_save_commits project.github_path, date_from, date_to, changelog
end
tags = []
end
pull_requests = Project.pull_requests
StoryPoint.parse_pull_requests pull_requests
StoryPoint.sync_with_changelogs
end
def parse_and_save_commits(project, date_from, date_to, changelog)
commits = []
p = 1
if date_to.present?
commits_list = Rails.configuration.github_client.commits_between project, date_from, date_to, :page => p
else
commits_list = Rails.configuration.github_client.commits_before project, date_from, :page => p
end
while commits_list.present?
commits += commits_list
p += 1
commits_list = Rails.configuration.github_client.
commits_before(project, date_to, :page => p)
end
commits.each do |commit_params|
Commit.parse_and_save_with commit_params, project, changelog
end
end
def fetch_with(params)
case params[:date]
when 'month'
changelogs = Changelog.where('github_created_at >= ?', DateTime.now - 1.month)
when 'year'
changelogs = Changelog.where('github_created_at >= ?', DateTime.now - 1.year)
else
changelogs = Changelog.all
end
if params[:date_from].present? && params[:date_to].present?
changelogs = changelogs.
where('github_created_at >= ? and github_created_at <= ?',
DateTime.parse(params[:date_from]),
DateTime.parse(params[:date_to])
)
elsif params[:date_from].present?
changelogs.where('github_created_at >= ?', DateTime.parse(params[:date_from]))
elsif params[:date_to].present?
changelogs.where('github_created_at <= ?', DateTime.parse(params[:date_to]))
end
if params[:project].try(:[], 0).present?
changelogs = changelogs.where(:project_id => params[:project][0])
end
changelogs.includes(:story_points)
end
private
def parse_date_for(project, sha)
details = Rails.configuration.github_client.git_commit project, sha
details[:committer][:date]
end
end
end
|
module Ci
class Runner < ActiveRecord::Base
extend Gitlab::Ci::Model
include Gitlab::SQL::Pattern
include RedisCacheable
include ChronicDurationAttribute
RUNNER_QUEUE_EXPIRY_TIME = 60.minutes
ONLINE_CONTACT_TIMEOUT = 1.hour
UPDATE_DB_RUNNER_INFO_EVERY = 40.minutes
AVAILABLE_SCOPES = %w[specific shared active paused online].freeze
FORM_EDITABLE = %i[description tag_list active run_untagged locked access_level maximum_timeout_human_readable].freeze
has_many :builds
has_many :runner_projects, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
has_many :projects, through: :runner_projects
has_many :runner_namespaces
has_many :groups, through: :runner_namespaces
has_one :last_build, ->() { order('id DESC') }, class_name: 'Ci::Build'
before_validation :set_default_values
scope :specific, -> { where(is_shared: false) }
scope :shared, -> { where(is_shared: true) }
scope :active, -> { where(active: true) }
scope :paused, -> { where(active: false) }
scope :online, -> { where('contacted_at > ?', contact_time_deadline) }
scope :ordered, -> { order(id: :desc) }
scope :belonging_to_project, -> (project_id) {
joins(:runner_projects).where(ci_runner_projects: { project_id: project_id })
}
scope :belonging_to_parent_group_of_project, -> (project_id) {
project_groups = ::Group.joins(:projects).where(projects: { id: project_id })
hierarchy_groups = Gitlab::GroupHierarchy.new(project_groups).base_and_ancestors
joins(:groups).where(namespaces: { id: hierarchy_groups })
}
scope :owned_or_shared, -> (project_id) do
union = Gitlab::SQL::Union.new(
[belonging_to_project(project_id), belonging_to_parent_group_of_project(project_id), shared],
remove_duplicates: false
)
from("(#{union.to_sql}) ci_runners")
end
scope :assignable_for, ->(project) do
# FIXME: That `to_sql` is needed to workaround a weird Rails bug.
# Without that, placeholders would miss one and couldn't match.
where(locked: false)
.where.not("ci_runners.id IN (#{project.runners.select(:id).to_sql})")
.project_type
end
validate :tag_constraints
validates :access_level, presence: true
validates :runner_type, presence: true
validate :no_projects, unless: :project_type?
validate :no_groups, unless: :group_type?
validate :any_project, if: :project_type?
validate :exactly_one_group, if: :group_type?
validate :is_shared_is_valid
acts_as_taggable
after_destroy :cleanup_runner_queue
enum access_level: {
not_protected: 0,
ref_protected: 1
}
enum runner_type: {
instance_type: 1,
group_type: 2,
project_type: 3
}
cached_attr_reader :version, :revision, :platform, :architecture, :ip_address, :contacted_at
chronic_duration_attr :maximum_timeout_human_readable, :maximum_timeout
validates :maximum_timeout, allow_nil: true,
numericality: { greater_than_or_equal_to: 600,
message: 'needs to be at least 10 minutes' }
# Searches for runners matching the given query.
#
# This method uses ILIKE on PostgreSQL and LIKE on MySQL.
#
# This method performs a *partial* match on tokens, thus a query for "a"
# will match any runner where the token contains the letter "a". As a result
# you should *not* use this method for non-admin purposes as otherwise users
# might be able to query a list of all runners.
#
# query - The search query as a String
#
# Returns an ActiveRecord::Relation.
def self.search(query)
fuzzy_search(query, [:token, :description])
end
def self.contact_time_deadline
ONLINE_CONTACT_TIMEOUT.ago
end
def set_default_values
self.token = SecureRandom.hex(15) if self.token.blank?
end
def assign_to(project, current_user = nil)
if shared?
self.is_shared = false if shared?
self.runner_type = :project_type
elsif group_type?
raise ArgumentError, 'Transitioning a group runner to a project runner is not supported'
end
self.projects << project
self.save
end
def display_name
return short_sha if description.blank?
description
end
def shared?
is_shared
end
def online?
contacted_at && contacted_at > self.class.contact_time_deadline
end
def status
if contacted_at.nil?
:not_connected
elsif active?
online? ? :online : :offline
else
:paused
end
end
def belongs_to_one_project?
runner_projects.count == 1
end
def specific?
!shared?
end
def assigned_to_group?
runner_namespaces.any?
end
def assigned_to_project?
runner_projects.any?
end
def can_pick?(build)
return false if self.ref_protected? && !build.protected?
assignable_for?(build.project_id) && accepting_tags?(build)
end
def only_for?(project)
projects == [project]
end
def short_sha
token[0...8] if token
end
def has_tags?
tag_list.any?
end
def predefined_variables
Gitlab::Ci::Variables::Collection.new
.append(key: 'CI_RUNNER_ID', value: id.to_s)
.append(key: 'CI_RUNNER_DESCRIPTION', value: description)
.append(key: 'CI_RUNNER_TAGS', value: tag_list.to_s)
end
def tick_runner_queue
SecureRandom.hex.tap do |new_update|
::Gitlab::Workhorse.set_key_and_notify(runner_queue_key, new_update,
expire: RUNNER_QUEUE_EXPIRY_TIME, overwrite: true)
end
end
def ensure_runner_queue_value
new_value = SecureRandom.hex
::Gitlab::Workhorse.set_key_and_notify(runner_queue_key, new_value,
expire: RUNNER_QUEUE_EXPIRY_TIME, overwrite: false)
end
def runner_queue_value_latest?(value)
ensure_runner_queue_value == value if value.present?
end
def update_cached_info(values)
values = values&.slice(:version, :revision, :platform, :architecture, :ip_address) || {}
values[:contacted_at] = Time.now
cache_attributes(values)
if persist_cached_data?
self.assign_attributes(values)
self.save if self.changed?
end
end
def pick_build!(build)
if can_pick?(build)
tick_runner_queue
end
end
private
def cleanup_runner_queue
Gitlab::Redis::Queues.with do |redis|
redis.del(runner_queue_key)
end
end
def runner_queue_key
"runner:build_queue:#{self.token}"
end
def persist_cached_data?
# Use a random threshold to prevent beating DB updates.
# It generates a distribution between [40m, 80m].
contacted_at_max_age = UPDATE_DB_RUNNER_INFO_EVERY + Random.rand(UPDATE_DB_RUNNER_INFO_EVERY)
real_contacted_at = read_attribute(:contacted_at)
real_contacted_at.nil? ||
(Time.now - real_contacted_at) >= contacted_at_max_age
end
def tag_constraints
unless has_tags? || run_untagged?
errors.add(:tags_list,
'can not be empty when runner is not allowed to pick untagged jobs')
end
end
def assignable_for?(project_id)
self.class.owned_or_shared(project_id).where(id: self.id).any?
end
def no_projects
if projects.any?
errors.add(:runner, 'cannot have projects assigned')
end
end
def no_groups
if groups.any?
errors.add(:runner, 'cannot have groups assigned')
end
end
def any_project
unless projects.any?
errors.add(:runner, 'needs to be assigned to at least one project')
end
end
def exactly_one_group
unless groups.one?
errors.add(:runner, 'needs to be assigned to exactly one group')
end
end
def is_shared_is_valid
unless is_shared? == instance_type?
errors.add(:is_shared, 'is not equal to instance_type?')
end
end
def accepting_tags?(build)
(run_untagged? || build.has_tags?) && (build.tag_list - tag_list).empty?
end
end
end
Fix static analysis
module Ci
class Runner < ActiveRecord::Base
extend Gitlab::Ci::Model
include Gitlab::SQL::Pattern
include RedisCacheable
include ChronicDurationAttribute
RUNNER_QUEUE_EXPIRY_TIME = 60.minutes
ONLINE_CONTACT_TIMEOUT = 1.hour
UPDATE_DB_RUNNER_INFO_EVERY = 40.minutes
AVAILABLE_SCOPES = %w[specific shared active paused online].freeze
FORM_EDITABLE = %i[description tag_list active run_untagged locked access_level maximum_timeout_human_readable].freeze
has_many :builds
has_many :runner_projects, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
has_many :projects, through: :runner_projects
has_many :runner_namespaces
has_many :groups, through: :runner_namespaces
has_one :last_build, ->() { order('id DESC') }, class_name: 'Ci::Build'
before_validation :set_default_values
scope :specific, -> { where(is_shared: false) }
scope :shared, -> { where(is_shared: true) }
scope :active, -> { where(active: true) }
scope :paused, -> { where(active: false) }
scope :online, -> { where('contacted_at > ?', contact_time_deadline) }
scope :ordered, -> { order(id: :desc) }
scope :belonging_to_project, -> (project_id) {
joins(:runner_projects).where(ci_runner_projects: { project_id: project_id })
}
scope :belonging_to_parent_group_of_project, -> (project_id) {
project_groups = ::Group.joins(:projects).where(projects: { id: project_id })
hierarchy_groups = Gitlab::GroupHierarchy.new(project_groups).base_and_ancestors
joins(:groups).where(namespaces: { id: hierarchy_groups })
}
scope :owned_or_shared, -> (project_id) do
union = Gitlab::SQL::Union.new(
[belonging_to_project(project_id), belonging_to_parent_group_of_project(project_id), shared],
remove_duplicates: false
)
from("(#{union.to_sql}) ci_runners")
end
scope :assignable_for, ->(project) do
# FIXME: That `to_sql` is needed to workaround a weird Rails bug.
# Without that, placeholders would miss one and couldn't match.
where(locked: false)
.where.not("ci_runners.id IN (#{project.runners.select(:id).to_sql})")
.project_type
end
validate :tag_constraints
validates :access_level, presence: true
validates :runner_type, presence: true
validate :no_projects, unless: :project_type?
validate :no_groups, unless: :group_type?
validate :any_project, if: :project_type?
validate :exactly_one_group, if: :group_type?
validate :validate_is_shared
acts_as_taggable
after_destroy :cleanup_runner_queue
enum access_level: {
not_protected: 0,
ref_protected: 1
}
enum runner_type: {
instance_type: 1,
group_type: 2,
project_type: 3
}
cached_attr_reader :version, :revision, :platform, :architecture, :ip_address, :contacted_at
chronic_duration_attr :maximum_timeout_human_readable, :maximum_timeout
validates :maximum_timeout, allow_nil: true,
numericality: { greater_than_or_equal_to: 600,
message: 'needs to be at least 10 minutes' }
# Searches for runners matching the given query.
#
# This method uses ILIKE on PostgreSQL and LIKE on MySQL.
#
# This method performs a *partial* match on tokens, thus a query for "a"
# will match any runner where the token contains the letter "a". As a result
# you should *not* use this method for non-admin purposes as otherwise users
# might be able to query a list of all runners.
#
# query - The search query as a String
#
# Returns an ActiveRecord::Relation.
def self.search(query)
fuzzy_search(query, [:token, :description])
end
def self.contact_time_deadline
ONLINE_CONTACT_TIMEOUT.ago
end
def set_default_values
self.token = SecureRandom.hex(15) if self.token.blank?
end
def assign_to(project, current_user = nil)
if shared?
self.is_shared = false if shared?
self.runner_type = :project_type
elsif group_type?
raise ArgumentError, 'Transitioning a group runner to a project runner is not supported'
end
self.projects << project
self.save
end
def display_name
return short_sha if description.blank?
description
end
def shared?
is_shared
end
def online?
contacted_at && contacted_at > self.class.contact_time_deadline
end
def status
if contacted_at.nil?
:not_connected
elsif active?
online? ? :online : :offline
else
:paused
end
end
def belongs_to_one_project?
runner_projects.count == 1
end
def specific?
!shared?
end
def assigned_to_group?
runner_namespaces.any?
end
def assigned_to_project?
runner_projects.any?
end
def can_pick?(build)
return false if self.ref_protected? && !build.protected?
assignable_for?(build.project_id) && accepting_tags?(build)
end
def only_for?(project)
projects == [project]
end
def short_sha
token[0...8] if token
end
def has_tags?
tag_list.any?
end
def predefined_variables
Gitlab::Ci::Variables::Collection.new
.append(key: 'CI_RUNNER_ID', value: id.to_s)
.append(key: 'CI_RUNNER_DESCRIPTION', value: description)
.append(key: 'CI_RUNNER_TAGS', value: tag_list.to_s)
end
def tick_runner_queue
SecureRandom.hex.tap do |new_update|
::Gitlab::Workhorse.set_key_and_notify(runner_queue_key, new_update,
expire: RUNNER_QUEUE_EXPIRY_TIME, overwrite: true)
end
end
def ensure_runner_queue_value
new_value = SecureRandom.hex
::Gitlab::Workhorse.set_key_and_notify(runner_queue_key, new_value,
expire: RUNNER_QUEUE_EXPIRY_TIME, overwrite: false)
end
def runner_queue_value_latest?(value)
ensure_runner_queue_value == value if value.present?
end
def update_cached_info(values)
values = values&.slice(:version, :revision, :platform, :architecture, :ip_address) || {}
values[:contacted_at] = Time.now
cache_attributes(values)
if persist_cached_data?
self.assign_attributes(values)
self.save if self.changed?
end
end
def pick_build!(build)
if can_pick?(build)
tick_runner_queue
end
end
private
def cleanup_runner_queue
Gitlab::Redis::Queues.with do |redis|
redis.del(runner_queue_key)
end
end
def runner_queue_key
"runner:build_queue:#{self.token}"
end
def persist_cached_data?
# Use a random threshold to prevent beating DB updates.
# It generates a distribution between [40m, 80m].
contacted_at_max_age = UPDATE_DB_RUNNER_INFO_EVERY + Random.rand(UPDATE_DB_RUNNER_INFO_EVERY)
real_contacted_at = read_attribute(:contacted_at)
real_contacted_at.nil? ||
(Time.now - real_contacted_at) >= contacted_at_max_age
end
def tag_constraints
unless has_tags? || run_untagged?
errors.add(:tags_list,
'can not be empty when runner is not allowed to pick untagged jobs')
end
end
def assignable_for?(project_id)
self.class.owned_or_shared(project_id).where(id: self.id).any?
end
def no_projects
if projects.any?
errors.add(:runner, 'cannot have projects assigned')
end
end
def no_groups
if groups.any?
errors.add(:runner, 'cannot have groups assigned')
end
end
def any_project
unless projects.any?
errors.add(:runner, 'needs to be assigned to at least one project')
end
end
def exactly_one_group
unless groups.one?
errors.add(:runner, 'needs to be assigned to exactly one group')
end
end
def validate_is_shared
unless is_shared? == instance_type?
errors.add(:is_shared, 'is not equal to instance_type?')
end
end
def accepting_tags?(build)
(run_untagged? || build.has_tags?) && (build.tag_list - tag_list).empty?
end
end
end
|
class Community < ActiveRecord::Base
# TODO: protect attributes from mass-assignment
# counter-cache for number of websites
has_many :rankings do
def with_websites
map{|ranking| { :rank => ranking.rank, :created_at => ranking.created_at,
:website => ranking.website, :share => ranking.share, :status => ranking.status,
:count0 => ranking.count0, :count1 => ranking.count1, :ranking_id => ranking.id }}.sort_by {
|website_and_ranking| [website_and_ranking[:rank]] }
end
end
has_many :websites, :through => :rankings
has_many :fundings
has_many :feedbacks
validates_presence_of :name, :short_name
validates_presence_of :category, :message => "(Type) can't be blank"
validates_length_of :name, :maximum => 50
validates_length_of :short_name, :maximum => 20, :message => ": please shorten to 20 characters or less"
validates_length_of :category, :maximum => 20
validates_length_of :country, :maximum => 30
validates_length_of :prov_state, :maximum => 30
validates_length_of :city, :maximum => 30
named_scope :recently_created, :order => 'communities.created_at DESC'
named_scope :recently_updated, :order => 'communities.updated_at DESC'
# Required by sphinx
define_index do
indexes name, short_name, category, country, prov_state, city, scope
set_property :delta => true
end
cattr_reader :per_page
@@per_page = 30
def to_param
short_name.blank? ? id : "#{id}-#{short_name.parameterize}"
end
def location
"#{city} #{prov_state} #{country}"
end
def tally_oldcodeparts
@votes = Vote.find(:all, :conditions => ["community_id = ? and (place = ? or place IS NULL)", self.id, ""],
:order => "website_id, ip_address, created_at DESC", :group => "website_id, ip_address")
# So this finds last record in each group:
@votes.each do |vote|
temp = Vote.find(:last, :conditions => ["community_id = ? and website_id = ? and ip_address = ?",
self.id, vote.website_id, vote.ip_address], :order => "created_at")
vote.created_at = temp.created_at
vote.support = temp.support
vote.ballot_type = temp.ballot_type
end
end
def tally(tally_cutoff, rankings)
# Should skip this if community has no websites/rankings or no votes, else probably get error.
# This algorithm doesn't handle tie votes "fairly": it gives all the tied share to the first website.
# So should probably be enhanced some time to make it fairer. But this problem is not significant when there are many
# votes and some are over 10 days old.
# How to select the latest vote from each IP address for each website?:
# This doesn't get all data fields, so no good I guess:
# @votes = Vote.maximum(:updated_at,
# :conditions => ["community_id = ?", self.id],
# :group => "ip_address, website_id")
# Found example at http://stackoverflow.com/questions/1129792/rails-active-record-find-in-conjunction-with-order-and-group
# but unsure how to code with just one query, so used naive way with too many queries:
# This almost works, but returns the first record of each group (by ID, regardless of how sorted)
# while we want the latest record:
@votes = Vote.find(:all, :conditions => ["community_id = ? and created_at < ? and (place = ? or place IS NULL)",
self.id, tally_cutoff, ""],
:order => "website_id, ip_address, created_at DESC", :group => "website_id, ip_address")
# So this finds last record in each group:
@votes.each do |vote|
temp = Vote.find(:last, :conditions => ["community_id = ? and created_at < ? and website_id = ? and ip_address = ?",
self.id, tally_cutoff, vote.website_id, vote.ip_address], :order => "created_at")
vote.created_at = temp.created_at
vote.support = temp.support
vote.ballot_type = temp.ballot_type
end
unless self.tallied_at == rankings[0].tallied_at
puts "Warning: Rankings last tallied at " + rankings[0].tallied_at.to_s + " not same as when community last tallied!"
end
# ranking.status = limbo means website hasn't entered contest but
# we want to show it at bottom of ballot, at least temporarily.
if rankings.any?
puts Time.now.to_s + " Found " + rankings.size.to_s + " rankings."
else
puts Time.now.to_s + " Warning: Found no rankings!"
end
if @votes.any?
puts "Found " + @votes.size.to_s + " votes."
else
puts "Found no votes."
end
# Make sure shares are nonnegative whole numbers, not all zero:
rankings.each do |ranking|
ranking.share = ranking.share.round
if ranking.share < 0.0
ranking.share = 0.0
end
ranking.save
end
if rankings.sum(&:share) <= 0.0
rankings.each do |ranking|
ranking.share = 1.0
ranking.save
end
end
# Calculate count0 (# votes for share or more) and count1 (# votes for share+1 or more) for each ranking:
rankings.each do |ranking|
ranking.count0 = countVotes(tally_cutoff, @votes, ranking, 0.0)
ranking.count1 = countVotes(tally_cutoff, @votes, ranking, 1.0)
ranking.save
end
# Need to adjust shares until they sum to 100.0 and max_count1 <= min_count0(for websites with positive shares).
# @max_count1 is the ranking record for the website that most deserves to have its share increased.
# @min_count0 is the ranking record for the website that most deserves to have its share decreased.
@max_count1 = rankings.max {|a,b| a.count1 <=> b.count1 }
# Can only reduce a share if it's positive, so:
rankings_pos = rankings.find_all {|r| r.share > 0.0 }
@min_count0 = rankings_pos.min {|a,b| a.count0 <=> b.count0 }
# but if all shares = 0.0, @min_count0 is nil which gives error; hence prevented above.
# If shares sum to more than 100 (which shouldn't happen, but just in case), decrease 1 at a time:
while rankings.sum(&:share) > 100.0
@min_count0.share -= 1.0
@min_count0.count1 = @min_count0.count0
@min_count0.count0 = countVotes(tally_cutoff, @votes, @min_count0, 0.0)
@min_count0.save
rankings = Ranking.find(:all, :conditions => ["community_id = ? and created_at < ? and dropped_at > ?",
self.id, tally_cutoff, tally_cutoff], :order => "website_id")
@max_count1 = rankings.max {|a,b| a.count1 <=> b.count1 }
rankings_pos = rankings.find_all {|r| r.share > 0.0 }
@min_count0 = rankings_pos.min {|a,b| a.count0 <=> b.count0 }
end
# If shares sum to less than 100 (e.g. when first website[s] added), increase 1 at a time:
while rankings.sum(&:share) < 100.0
@max_count1.share += 1.0
@max_count1.count0 = @max_count1.count1
@max_count1.count1 = countVotes(tally_cutoff, @votes, @max_count1, 1.0)
@max_count1.save
rankings = Ranking.find(:all, :conditions => ["community_id = ? and created_at < ? and dropped_at > ?",
self.id, tally_cutoff, tally_cutoff], :order => "website_id")
@max_count1 = rankings.max {|a,b| a.count1 <=> b.count1 }
rankings_pos = rankings.find_all {|r| r.share > 0.0 }
@min_count0 = rankings_pos.min {|a,b| a.count0 <=> b.count0 }
end
# Main loop: Adjust shares until max_count1 <= min_count0 i.e. find a cutoff number of votes (actually a range of cutoffs)
# where shares sum to 100.0 using that same cutoff to determine each website's share.
# This is like a stock market order matching system. Each count1 is a bid; each count0 is an offer.
# If the highest bid is higher than the lowest offer, then a trade of 1% happens.
# It's a competitive market for public goods:
while @min_count0.count0 < @max_count1.count1
# Move one percent share from @min_count0 to @max_count1
@min_count0.share -= 1.0
@min_count0.count1 = @min_count0.count0
@min_count0.count0 = countVotes(tally_cutoff, @votes, @min_count0, 0.0)
@min_count0.save
@max_count1.share += 1.0
@max_count1.count0 = @max_count1.count1
@max_count1.count1 = countVotes(tally_cutoff, @votes, @max_count1, 1.0)
@max_count1.save
rankings = Ranking.find(:all, :conditions => ["community_id = ? and created_at < ? and dropped_at > ?",
self.id, tally_cutoff, tally_cutoff], :order => "website_id")
rankings_pos = rankings.find_all {|r| r.share > 0.0 }
@min_count0 = rankings_pos.min {|a,b| a.count0 <=> b.count0 }
@max_count1 = rankings.max {|a,b| a.count1 <=> b.count1 }
end
# Share calculations are now completed, so store rank of each website in this community:
rankings = Ranking.find(:all, :conditions => ["community_id = ? and created_at < ? and dropped_at > ?",
self.id, tally_cutoff, tally_cutoff],
:order => "share DESC, count1 DESC, created_at DESC")
rank_sequence = 0
rankings.each do |ranking|
rank_sequence += 1
ranking.rank = rank_sequence
ranking.tallied_at = tally_cutoff
ranking.save
end
end
# Subroutine to count the number of (time-decayed) votes for shares >= cutoff = ranking.share + increment
def countVotes(tally_cutoff, votes, ranking, increment)
days_full_value = 10
days_valid = 60
ranking_formula_denominator = 50
cutoff = ranking.share + increment
count = 0.00000001 * (100.0 - ranking.share) # To break ties caused by having no votes. This will equalize shares.
votes.each do |vote|
if vote.website_id == ranking.website_id && vote.support
# Time decay of vote:
days_old = (tally_cutoff.to_date - vote.created_at.to_date).to_i
if days_old < days_full_value
decayed_weight = 1.0
elsif days_old < days_valid
decayed_weight = (days_valid - days_old) / ranking_formula_denominator.to_f
else
decayed_weight = 0.01 / days_old # To break ties caused by having very few votes.
end
# if decayed_weight > 0.0 # This conditional not needed now that condition always true because of tie-breaker line above.
if vote.ballot_type == 2
# ballot_type 2 is Interpolated Consensus with 5% increments:
if vote.support < 0.1
# This is to catch the special case of vote.support = 0.0 -- no interpolation.
if cutoff < 0.1
support_fraction = 1.0
# In case it's useful to see how many voted for 0.0
else
support_fraction = 0.0
end
elsif vote.support - 2.5 > cutoff
support_fraction = 1.0
elsif vote.support + 2.5 < cutoff
support_fraction = 0.0
else
support_fraction = 0.2 * (vote.support + 2.5 - cutoff)
end
elsif vote.ballot_type == 101 # Changed from == 1 to in effect comment this out.
# ballot_type 1 is simple percent vote for vote.support:
if vote.support >= cutoff
support_fraction = 1.0
else
support_fraction = 0.0
end
elsif vote.ballot_type == 100 # Changed from == 0 to in effect comment this out.
# Ballot_type 0 means voted for "Increase Share" from vote.support = share when voted,
# interpreted as uniform distribution of vote from vote.support to 100.0:
if vote.support >= cutoff
support_fraction = 1.0
elsif vote.support >= 100.0 or cutoff > 100.0
support_fraction = 0.0
else
support_fraction = (100.0 - cutoff)/(100.0 - vote.support)
end
else
# No provision for other ballot types at this point:
support_fraction = 0.0
end
count += decayed_weight * support_fraction
# end
end
end
return count
end
# Calculate periodic (non-daily) past_rankings for this community and date:
def calc_periodic_rankings(tally_cutoff_date)
PastRanking.delete_all(["community_id = ? and period != ? and start <= ? and end >= ?",
self.id, "day", tally_cutoff_date, tally_cutoff_date])
for period in ["month", "year"]
if period == "month"
beginning_of_period = tally_cutoff_date.beginning_of_month
end_of_period = tally_cutoff_date.end_of_month
else
beginning_of_period = tally_cutoff_date.beginning_of_year
end_of_period = tally_cutoff_date.end_of_year
end
first_ranked_date = PastRanking.minimum(:start,
:conditions => ["community_id = ? and period = ? and start >= ? and start <= ?",
self.id, "day", beginning_of_period, end_of_period])
last_ranked_date = PastRanking.maximum(:start,
:conditions => ["community_id = ? and period = ? and start >= ? and start <= ?",
self.id, "day", beginning_of_period, end_of_period])
funds = Funding.sum(:amount, :conditions => ["community_id = ? and date >= ? and date <= ?",
self.id, first_ranked_date, last_ranked_date])
n_days = PastRanking.count(:start, :distinct => true, :conditions =>
["community_id = ? and period = ? and start >= ? and start <= ?",
self.id, "day", first_ranked_date, last_ranked_date])
if n_days != 1 + (last_ranked_date - first_ranked_date)
puts "Warning: n_days = " + n_days.to_s + " but we seem to have " +
(1 + (last_ranked_date - first_ranked_date) - n_days).to_s + " missing days in this " + period + "."
end
# Find the ranking_ids that have any past_rankings on the days we are considering:
if funds > 0
past_rankings = PastRanking.find(:all, :conditions =>
["community_id = ? and period = ? and start >= ? and start <= ? and funds > 0",
self.id, "day", first_ranked_date, last_ranked_date],
:order => "ranking_id, start", :group => "ranking_id")
else
past_rankings = PastRanking.find(:all, :conditions =>
["community_id = ? and period = ? and start >= ? and start <= ?",
self.id, "day", first_ranked_date, last_ranked_date],
:order => "ranking_id, start", :group => "ranking_id")
end
past_rankings.each do |past_ranking|
if funds > 0
award = PastRanking.sum(:award, :conditions =>
["community_id = ? and ranking_id = ? and period = ? and start >= ? and start <= ?",
self.id, past_ranking.ranking_id, "day", first_ranked_date, last_ranked_date])
share = award * 100 / funds
else
award = 0
share = PastRanking.sum(:share, :conditions =>
["community_id = ? and ranking_id = ? and period = ? and start >= ? and start <= ?",
self.id, past_ranking.ranking_id, "day", first_ranked_date, last_ranked_date])/n_days
end
PastRanking.create!({:ranking_id => past_ranking.ranking_id, :community_id => self.id,
:website_id => past_ranking.website_id, :rank => 0, # rank will be set later
:tallied_at => self.tallied_at, :share => share, :funds => funds, :award => award,
:period => period, :start => first_ranked_date, :latest => last_ranked_date, :end => end_of_period})
end
end
# Sort and save monthly and yearly ranks:
rankpr(tally_cutoff_date)
end
# Update periodic (non-daily) past_rankings ranks for this community; also check totals:
def rankpr(date_to_process)
monthly_rankings = PastRanking.find(:all, :conditions => ["community_id = ? and period = ? and start >= ? and start <= ?",
self.id, "month", date_to_process.beginning_of_month, date_to_process.end_of_month],
:order => "share DESC, count1 DESC")
if monthly_rankings.any?
checkpr(monthly_rankings)
end
yearly_rankings = PastRanking.find(:all, :conditions => ["community_id = ? and period = ? and start >= ? and start <= ?",
self.id, "year", date_to_process.beginning_of_year, date_to_process.end_of_year],
:order => "share DESC, count1 DESC")
if yearly_rankings.any?
checkpr(yearly_rankings)
end
end
def checkpr(period_rankings)
rank_sequence = 0
first_funds = period_rankings[0].funds
total_deviations = 0.0
total_awards = 0.0
total_shares = 0.0
period_rankings.each do |pr|
rank_sequence += 1
pr.rank = rank_sequence
pr.save
total_deviations += (pr.funds - first_funds).abs
total_awards += pr.award
total_shares += pr.share
end
if total_deviations > 0.09 # Should be 0.0 but concerned about roundoff.
puts "Community number " + period_rankings[0].community_id.to_s + " " + period_rankings[0].period +
"ly fundings deviate by" + total_deviations.to_s
end
if (total_awards - first_funds).abs > 0.09 # Should be 0.0 but concerned about roundoff.
puts "Community number " + period_rankings[0].community_id.to_s + " " + period_rankings[0].period +
"ly awards total $" + total_awards.to_s + " but first_funds = " + first_funds.to_s
end
if (total_shares - 100.0).abs > 0.09 # Should be 0.0 but concerned about roundoff.
puts "Community number " + period_rankings[0].community_id.to_s + " " + period_rankings[0].period +
"ly shares total " + total_shares.to_s + " but should = 100.0 -- rescaling all to fix this."
# This fix is OK for when a community first has blogs added to it; also if a day is missed.
if total_shares > 0.0
period_rankings.each do |pr|
pr.share *= 100.0/total_shares
pr.save
end
end
end
end
class << self
def filter(params={})
# TODO: Separate the sphinx search
if params[:q]
# Unfortunately, sphinx's search doesn't want to play nice with will_paginate
return search(params[:q], :page => params[:page], :per_page => @@per_page)
end
scope = self
if sorted = params[:sorted]
sorted = sorted.downcase.to_sym
scope = scope.send(sorted) if self.scopes.keys.include?(sorted)
else
scope = scope.scoped(:order => 'n_websites DESC, lower(country), lower(category), lower(name)')
end
scope
end
# TODO: A community should be marked by admin as featured
# Should be a named_scope eventually
def featured
ids = [82, 96, 94, 51, 52, 81, 5, 205, 3, 151, 116, 109, 223]
find(:all, :conditions => ["id in (?)", ids]).sort{|a, b| ids.index(a.id) <=> ids.index(b.id)}
end
end
end
Added sorting in search results. Resolves case #44.
class Community < ActiveRecord::Base
# TODO: protect attributes from mass-assignment
# counter-cache for number of websites
has_many :rankings do
def with_websites
map{|ranking| { :rank => ranking.rank, :created_at => ranking.created_at,
:website => ranking.website, :share => ranking.share, :status => ranking.status,
:count0 => ranking.count0, :count1 => ranking.count1, :ranking_id => ranking.id }}.sort_by {
|website_and_ranking| [website_and_ranking[:rank]] }
end
end
has_many :websites, :through => :rankings
has_many :fundings
has_many :feedbacks
validates_presence_of :name, :short_name
validates_presence_of :category, :message => "(Type) can't be blank"
validates_length_of :name, :maximum => 50
validates_length_of :short_name, :maximum => 20, :message => ": please shorten to 20 characters or less"
validates_length_of :category, :maximum => 20
validates_length_of :country, :maximum => 30
validates_length_of :prov_state, :maximum => 30
validates_length_of :city, :maximum => 30
named_scope :recently_created, :order => 'communities.created_at DESC'
named_scope :recently_updated, :order => 'communities.updated_at DESC'
# Required by sphinx
define_index do
indexes name, short_name, category, country, prov_state, city, scope, :sortable => true
has n_websites, :sortable => true
set_property :delta => true
end
cattr_reader :per_page
@@per_page = 30
def to_param
short_name.blank? ? id : "#{id}-#{short_name.parameterize}"
end
def location
"#{city} #{prov_state} #{country}"
end
def tally_oldcodeparts
@votes = Vote.find(:all, :conditions => ["community_id = ? and (place = ? or place IS NULL)", self.id, ""],
:order => "website_id, ip_address, created_at DESC", :group => "website_id, ip_address")
# So this finds last record in each group:
@votes.each do |vote|
temp = Vote.find(:last, :conditions => ["community_id = ? and website_id = ? and ip_address = ?",
self.id, vote.website_id, vote.ip_address], :order => "created_at")
vote.created_at = temp.created_at
vote.support = temp.support
vote.ballot_type = temp.ballot_type
end
end
def tally(tally_cutoff, rankings)
# Should skip this if community has no websites/rankings or no votes, else probably get error.
# This algorithm doesn't handle tie votes "fairly": it gives all the tied share to the first website.
# So should probably be enhanced some time to make it fairer. But this problem is not significant when there are many
# votes and some are over 10 days old.
# How to select the latest vote from each IP address for each website?:
# This doesn't get all data fields, so no good I guess:
# @votes = Vote.maximum(:updated_at,
# :conditions => ["community_id = ?", self.id],
# :group => "ip_address, website_id")
# Found example at http://stackoverflow.com/questions/1129792/rails-active-record-find-in-conjunction-with-order-and-group
# but unsure how to code with just one query, so used naive way with too many queries:
# This almost works, but returns the first record of each group (by ID, regardless of how sorted)
# while we want the latest record:
@votes = Vote.find(:all, :conditions => ["community_id = ? and created_at < ? and (place = ? or place IS NULL)",
self.id, tally_cutoff, ""],
:order => "website_id, ip_address, created_at DESC", :group => "website_id, ip_address")
# So this finds last record in each group:
@votes.each do |vote|
temp = Vote.find(:last, :conditions => ["community_id = ? and created_at < ? and website_id = ? and ip_address = ?",
self.id, tally_cutoff, vote.website_id, vote.ip_address], :order => "created_at")
vote.created_at = temp.created_at
vote.support = temp.support
vote.ballot_type = temp.ballot_type
end
unless self.tallied_at == rankings[0].tallied_at
puts "Warning: Rankings last tallied at " + rankings[0].tallied_at.to_s + " not same as when community last tallied!"
end
# ranking.status = limbo means website hasn't entered contest but
# we want to show it at bottom of ballot, at least temporarily.
if rankings.any?
puts Time.now.to_s + " Found " + rankings.size.to_s + " rankings."
else
puts Time.now.to_s + " Warning: Found no rankings!"
end
if @votes.any?
puts "Found " + @votes.size.to_s + " votes."
else
puts "Found no votes."
end
# Make sure shares are nonnegative whole numbers, not all zero:
rankings.each do |ranking|
ranking.share = ranking.share.round
if ranking.share < 0.0
ranking.share = 0.0
end
ranking.save
end
if rankings.sum(&:share) <= 0.0
rankings.each do |ranking|
ranking.share = 1.0
ranking.save
end
end
# Calculate count0 (# votes for share or more) and count1 (# votes for share+1 or more) for each ranking:
rankings.each do |ranking|
ranking.count0 = countVotes(tally_cutoff, @votes, ranking, 0.0)
ranking.count1 = countVotes(tally_cutoff, @votes, ranking, 1.0)
ranking.save
end
# Need to adjust shares until they sum to 100.0 and max_count1 <= min_count0(for websites with positive shares).
# @max_count1 is the ranking record for the website that most deserves to have its share increased.
# @min_count0 is the ranking record for the website that most deserves to have its share decreased.
@max_count1 = rankings.max {|a,b| a.count1 <=> b.count1 }
# Can only reduce a share if it's positive, so:
rankings_pos = rankings.find_all {|r| r.share > 0.0 }
@min_count0 = rankings_pos.min {|a,b| a.count0 <=> b.count0 }
# but if all shares = 0.0, @min_count0 is nil which gives error; hence prevented above.
# If shares sum to more than 100 (which shouldn't happen, but just in case), decrease 1 at a time:
while rankings.sum(&:share) > 100.0
@min_count0.share -= 1.0
@min_count0.count1 = @min_count0.count0
@min_count0.count0 = countVotes(tally_cutoff, @votes, @min_count0, 0.0)
@min_count0.save
rankings = Ranking.find(:all, :conditions => ["community_id = ? and created_at < ? and dropped_at > ?",
self.id, tally_cutoff, tally_cutoff], :order => "website_id")
@max_count1 = rankings.max {|a,b| a.count1 <=> b.count1 }
rankings_pos = rankings.find_all {|r| r.share > 0.0 }
@min_count0 = rankings_pos.min {|a,b| a.count0 <=> b.count0 }
end
# If shares sum to less than 100 (e.g. when first website[s] added), increase 1 at a time:
while rankings.sum(&:share) < 100.0
@max_count1.share += 1.0
@max_count1.count0 = @max_count1.count1
@max_count1.count1 = countVotes(tally_cutoff, @votes, @max_count1, 1.0)
@max_count1.save
rankings = Ranking.find(:all, :conditions => ["community_id = ? and created_at < ? and dropped_at > ?",
self.id, tally_cutoff, tally_cutoff], :order => "website_id")
@max_count1 = rankings.max {|a,b| a.count1 <=> b.count1 }
rankings_pos = rankings.find_all {|r| r.share > 0.0 }
@min_count0 = rankings_pos.min {|a,b| a.count0 <=> b.count0 }
end
# Main loop: Adjust shares until max_count1 <= min_count0 i.e. find a cutoff number of votes (actually a range of cutoffs)
# where shares sum to 100.0 using that same cutoff to determine each website's share.
# This is like a stock market order matching system. Each count1 is a bid; each count0 is an offer.
# If the highest bid is higher than the lowest offer, then a trade of 1% happens.
# It's a competitive market for public goods:
while @min_count0.count0 < @max_count1.count1
# Move one percent share from @min_count0 to @max_count1
@min_count0.share -= 1.0
@min_count0.count1 = @min_count0.count0
@min_count0.count0 = countVotes(tally_cutoff, @votes, @min_count0, 0.0)
@min_count0.save
@max_count1.share += 1.0
@max_count1.count0 = @max_count1.count1
@max_count1.count1 = countVotes(tally_cutoff, @votes, @max_count1, 1.0)
@max_count1.save
rankings = Ranking.find(:all, :conditions => ["community_id = ? and created_at < ? and dropped_at > ?",
self.id, tally_cutoff, tally_cutoff], :order => "website_id")
rankings_pos = rankings.find_all {|r| r.share > 0.0 }
@min_count0 = rankings_pos.min {|a,b| a.count0 <=> b.count0 }
@max_count1 = rankings.max {|a,b| a.count1 <=> b.count1 }
end
# Share calculations are now completed, so store rank of each website in this community:
rankings = Ranking.find(:all, :conditions => ["community_id = ? and created_at < ? and dropped_at > ?",
self.id, tally_cutoff, tally_cutoff],
:order => "share DESC, count1 DESC, created_at DESC")
rank_sequence = 0
rankings.each do |ranking|
rank_sequence += 1
ranking.rank = rank_sequence
ranking.tallied_at = tally_cutoff
ranking.save
end
end
# Subroutine to count the number of (time-decayed) votes for shares >= cutoff = ranking.share + increment
def countVotes(tally_cutoff, votes, ranking, increment)
days_full_value = 10
days_valid = 60
ranking_formula_denominator = 50
cutoff = ranking.share + increment
count = 0.00000001 * (100.0 - ranking.share) # To break ties caused by having no votes. This will equalize shares.
votes.each do |vote|
if vote.website_id == ranking.website_id && vote.support
# Time decay of vote:
days_old = (tally_cutoff.to_date - vote.created_at.to_date).to_i
if days_old < days_full_value
decayed_weight = 1.0
elsif days_old < days_valid
decayed_weight = (days_valid - days_old) / ranking_formula_denominator.to_f
else
decayed_weight = 0.01 / days_old # To break ties caused by having very few votes.
end
# if decayed_weight > 0.0 # This conditional not needed now that condition always true because of tie-breaker line above.
if vote.ballot_type == 2
# ballot_type 2 is Interpolated Consensus with 5% increments:
if vote.support < 0.1
# This is to catch the special case of vote.support = 0.0 -- no interpolation.
if cutoff < 0.1
support_fraction = 1.0
# In case it's useful to see how many voted for 0.0
else
support_fraction = 0.0
end
elsif vote.support - 2.5 > cutoff
support_fraction = 1.0
elsif vote.support + 2.5 < cutoff
support_fraction = 0.0
else
support_fraction = 0.2 * (vote.support + 2.5 - cutoff)
end
elsif vote.ballot_type == 101 # Changed from == 1 to in effect comment this out.
# ballot_type 1 is simple percent vote for vote.support:
if vote.support >= cutoff
support_fraction = 1.0
else
support_fraction = 0.0
end
elsif vote.ballot_type == 100 # Changed from == 0 to in effect comment this out.
# Ballot_type 0 means voted for "Increase Share" from vote.support = share when voted,
# interpreted as uniform distribution of vote from vote.support to 100.0:
if vote.support >= cutoff
support_fraction = 1.0
elsif vote.support >= 100.0 or cutoff > 100.0
support_fraction = 0.0
else
support_fraction = (100.0 - cutoff)/(100.0 - vote.support)
end
else
# No provision for other ballot types at this point:
support_fraction = 0.0
end
count += decayed_weight * support_fraction
# end
end
end
return count
end
# Calculate periodic (non-daily) past_rankings for this community and date:
def calc_periodic_rankings(tally_cutoff_date)
PastRanking.delete_all(["community_id = ? and period != ? and start <= ? and end >= ?",
self.id, "day", tally_cutoff_date, tally_cutoff_date])
for period in ["month", "year"]
if period == "month"
beginning_of_period = tally_cutoff_date.beginning_of_month
end_of_period = tally_cutoff_date.end_of_month
else
beginning_of_period = tally_cutoff_date.beginning_of_year
end_of_period = tally_cutoff_date.end_of_year
end
first_ranked_date = PastRanking.minimum(:start,
:conditions => ["community_id = ? and period = ? and start >= ? and start <= ?",
self.id, "day", beginning_of_period, end_of_period])
last_ranked_date = PastRanking.maximum(:start,
:conditions => ["community_id = ? and period = ? and start >= ? and start <= ?",
self.id, "day", beginning_of_period, end_of_period])
funds = Funding.sum(:amount, :conditions => ["community_id = ? and date >= ? and date <= ?",
self.id, first_ranked_date, last_ranked_date])
n_days = PastRanking.count(:start, :distinct => true, :conditions =>
["community_id = ? and period = ? and start >= ? and start <= ?",
self.id, "day", first_ranked_date, last_ranked_date])
if n_days != 1 + (last_ranked_date - first_ranked_date)
puts "Warning: n_days = " + n_days.to_s + " but we seem to have " +
(1 + (last_ranked_date - first_ranked_date) - n_days).to_s + " missing days in this " + period + "."
end
# Find the ranking_ids that have any past_rankings on the days we are considering:
if funds > 0
past_rankings = PastRanking.find(:all, :conditions =>
["community_id = ? and period = ? and start >= ? and start <= ? and funds > 0",
self.id, "day", first_ranked_date, last_ranked_date],
:order => "ranking_id, start", :group => "ranking_id")
else
past_rankings = PastRanking.find(:all, :conditions =>
["community_id = ? and period = ? and start >= ? and start <= ?",
self.id, "day", first_ranked_date, last_ranked_date],
:order => "ranking_id, start", :group => "ranking_id")
end
past_rankings.each do |past_ranking|
if funds > 0
award = PastRanking.sum(:award, :conditions =>
["community_id = ? and ranking_id = ? and period = ? and start >= ? and start <= ?",
self.id, past_ranking.ranking_id, "day", first_ranked_date, last_ranked_date])
share = award * 100 / funds
else
award = 0
share = PastRanking.sum(:share, :conditions =>
["community_id = ? and ranking_id = ? and period = ? and start >= ? and start <= ?",
self.id, past_ranking.ranking_id, "day", first_ranked_date, last_ranked_date])/n_days
end
PastRanking.create!({:ranking_id => past_ranking.ranking_id, :community_id => self.id,
:website_id => past_ranking.website_id, :rank => 0, # rank will be set later
:tallied_at => self.tallied_at, :share => share, :funds => funds, :award => award,
:period => period, :start => first_ranked_date, :latest => last_ranked_date, :end => end_of_period})
end
end
# Sort and save monthly and yearly ranks:
rankpr(tally_cutoff_date)
end
# Update periodic (non-daily) past_rankings ranks for this community; also check totals:
def rankpr(date_to_process)
monthly_rankings = PastRanking.find(:all, :conditions => ["community_id = ? and period = ? and start >= ? and start <= ?",
self.id, "month", date_to_process.beginning_of_month, date_to_process.end_of_month],
:order => "share DESC, count1 DESC")
if monthly_rankings.any?
checkpr(monthly_rankings)
end
yearly_rankings = PastRanking.find(:all, :conditions => ["community_id = ? and period = ? and start >= ? and start <= ?",
self.id, "year", date_to_process.beginning_of_year, date_to_process.end_of_year],
:order => "share DESC, count1 DESC")
if yearly_rankings.any?
checkpr(yearly_rankings)
end
end
def checkpr(period_rankings)
rank_sequence = 0
first_funds = period_rankings[0].funds
total_deviations = 0.0
total_awards = 0.0
total_shares = 0.0
period_rankings.each do |pr|
rank_sequence += 1
pr.rank = rank_sequence
pr.save
total_deviations += (pr.funds - first_funds).abs
total_awards += pr.award
total_shares += pr.share
end
if total_deviations > 0.09 # Should be 0.0 but concerned about roundoff.
puts "Community number " + period_rankings[0].community_id.to_s + " " + period_rankings[0].period +
"ly fundings deviate by" + total_deviations.to_s
end
if (total_awards - first_funds).abs > 0.09 # Should be 0.0 but concerned about roundoff.
puts "Community number " + period_rankings[0].community_id.to_s + " " + period_rankings[0].period +
"ly awards total $" + total_awards.to_s + " but first_funds = " + first_funds.to_s
end
if (total_shares - 100.0).abs > 0.09 # Should be 0.0 but concerned about roundoff.
puts "Community number " + period_rankings[0].community_id.to_s + " " + period_rankings[0].period +
"ly shares total " + total_shares.to_s + " but should = 100.0 -- rescaling all to fix this."
# This fix is OK for when a community first has blogs added to it; also if a day is missed.
if total_shares > 0.0
period_rankings.each do |pr|
pr.share *= 100.0/total_shares
pr.save
end
end
end
end
class << self
def filter(params={})
# TODO: Separate the sphinx search
if params[:q]
# Unfortunately, sphinx's search doesn't want to play nice with will_paginate
return search(params[:q], :page => params[:page], :per_page => @@per_page,
:order => 'n_websites DESC, country ASC, category ASC, name ASC')
end
scope = self
if sorted = params[:sorted]
sorted = sorted.downcase.to_sym
scope = scope.send(sorted) if self.scopes.keys.include?(sorted)
else
scope = scope.scoped(:order => 'n_websites DESC, lower(country), lower(category), lower(name)')
end
scope
end
# TODO: A community should be marked by admin as featured
# Should be a named_scope eventually
def featured
ids = [82, 96, 94, 51, 52, 81, 5, 205, 3, 151, 116, 109, 223]
find(:all, :conditions => ["id in (?)", ids]).sort{|a, b| ids.index(a.id) <=> ids.index(b.id)}
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.