Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix ogf method that returns the root path of the gem
require 'tempfile' require File.expand_path '../file.rb', __FILE__ require File.expand_path '../elastic_search.rb', __FILE__ require File.expand_path '../cron.rb', __FILE__ require File.expand_path '../kibana.rb', __FILE__ module InternetBoxLogger module Tasks def ibl_gem_path spec = Gem::Specification.find_by_name('internet_box_logger') File.expand_path "../#{spec.name}", spec.spec_dir end end end
require 'tempfile' require File.expand_path '../file.rb', __FILE__ require File.expand_path '../elastic_search.rb', __FILE__ require File.expand_path '../cron.rb', __FILE__ require File.expand_path '../kibana.rb', __FILE__ module InternetBoxLogger module Tasks def ibl_gem_path spec = Gem::Specification.find_by_name('internet_box_logger') spec.gem_dir end end end
Remove all previous gem versions before reinstalling
## This file is loaded by irb -r ## So, setup any necessary configuration variables / executables here ## Remove previous gem installation `rm -rf pkg/` ## Install local source code as gem `rake install` require 'Cb' Cb.configuration.dev_key = "WDHH6P96RQD9FSDCZ0G7" ## more configuration options to follow...
## This file is loaded by irb -r ## So, setup any necessary configuration variables / executables here ## Remove all previous gem installations `gem uninstall -Ia cb-api` `rm -rf pkg/` ## Install local source code as gem `rake install` require 'Cb' Cb.configuration.dev_key = "WDHH6P96RQD9FSDCZ0G7" ## more configuration options to follow...
Add comment to help understand the meaning of aaet
module TimelineFu module ActsAsEventTarget def self.included(klass) klass.send(:extend, ClassMethods) end module ClassMethods def acts_as_event_target has_many :timeline_events, :as => :target end end end end
module TimelineFu module ActsAsEventTarget def self.included(klass) klass.send(:extend, ClassMethods) end module ClassMethods # Who's this timeline for? User? Person? # Go and put acts_as_event_target in the model's class definition. def acts_as_event_target has_many :timeline_events, :as => :target end end end end
Disable apt-lists bucket for windows hosts
module VagrantPlugins module Cachier class Bucket class AptLists < Bucket def self.capability :apt_lists_dir end def install if guest.capability?(:apt_lists_dir) guest_path = guest.capability(:apt_lists_dir) return if @env[:cache_dirs].include?(guest_path) symlink(guest_path) comm.execute("mkdir -p /tmp/vagrant-cache/#{@name}/partial") else @env[:ui].info I18n.t('vagrant_cachier.skipping_bucket', bucket: 'apt-lists') end end end end end end
module VagrantPlugins module Cachier class Bucket class AptLists < Bucket def self.capability :apt_lists_dir end def install # Apt lists bucket can't be used on windows hosts # https://github.com/fgrehm/vagrant-cachier/issues/106 return if Vagrant::Util::Platform.windows? if guest.capability?(:apt_lists_dir) guest_path = guest.capability(:apt_lists_dir) return if @env[:cache_dirs].include?(guest_path) symlink(guest_path) comm.execute("mkdir -p /tmp/vagrant-cache/#{@name}/partial") else @env[:ui].info I18n.t('vagrant_cachier.skipping_bucket', bucket: 'apt-lists') end end end end end end
Update name to not conflict with already existing gem
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "robot/version" Gem::Specification.new do |s| s.name = "robot" s.version = Robot::VERSION::STRING s.platform = Gem::Platform::RUBY s.authors = ["Dray Lacy", "Grady Griffin", "Brian Fisher"] s.email = "opensource@izea.com" s.homepage = "https://github.com/IZEA/robot" s.summary = %q{Use Robot to run scheduled jobs} 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"] end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "robot/version" Gem::Specification.new do |s| s.name = "scheduled-robot" s.version = Robot::VERSION::STRING s.platform = Gem::Platform::RUBY s.authors = ["Dray Lacy", "Grady Griffin", "Brian Fisher"] s.email = "opensource@izea.com" s.homepage = "https://github.com/IZEA/robot" s.summary = %q{Use Robot to run scheduled jobs} 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"] end
Add the basic idea and a few config options
require "lita" module Lita module Handlers class MeetupRsvps < Handler end Lita.register_handler(MeetupRsvps) end end
require "lita" module Lita module Handlers class MeetupRsvps < Handler end # How often we should poll for new events/meetups from your groups. config :events_poll_interval, type: Integer, default: 3600 # Configure the Meetup you want to poll and the channel you want it to # output it in. config :events, type: Hash, required: true # * Poll for new events # * Compare the events received with the ones stored in redis # * Send triggers for the events which weren't in redis # * In the trigger do # ** Send trigger for rsvps # ** Send trigger for event_comments # ** Save the current event in redis # # http://www.meetup.com/meetup_api/docs/2/events/ # https://api.meetup.com/2/events?group_urlname=STHLM-Lounge-Hackers&page=20&key=7714627f7e7d61275a161303b3e3332 # # http://www.meetup.com/meetup_api/docs/stream/2/rsvps/#http # http://stream.meetup.com/2/rsvps?event_id=XXX&since_mtime=restart_from # # http://www.meetup.com/meetup_api/docs/stream/2/event_comments/#http # http://stream.meetup.com/2/event_comments?event_id=XXX&since_mtime=restart_from # # every 60 robot.trigger :check_alive, :room: room, :meetup-url: "sthlm-lounge-hackers" # check_alive # redis-lock || return # Net::HTTP payload[:meedup-url] do # robot.send_message payload[:room] MEOW # end # end Lita.register_handler(MeetupRsvps) end end
Allow agents to set vip attribute.
class CreateVip < ActiveRecord::Migration def up add_column :users, :vip, :boolean, :default => false ObjectManager::Attribute.add( :object => 'User', :name => 'vip', :display => 'VIP', :data_type => 'boolean', :data_option => { :null => true, :default => false, :item_class => 'formGroup--halfSize', :options => { :false => 'no', :true => 'yes', }, :translate => true, }, :editable => false, :active => true, :screens => { :edit => { :Admin => { :null => true, }, }, :view => { '-all-' => { :shown => false, }, }, }, :pending_migration => false, :position => 1490, :created_by_id => 1, :updated_by_id => 1, ) end def down end end
class CreateVip < ActiveRecord::Migration def up add_column :users, :vip, :boolean, :default => false ObjectManager::Attribute.add( :object => 'User', :name => 'vip', :display => 'VIP', :data_type => 'boolean', :data_option => { :null => true, :default => false, :item_class => 'formGroup--halfSize', :options => { :false => 'no', :true => 'yes', }, :translate => true, }, :editable => false, :active => true, :screens => { :edit => { :Admin => { :null => true, }, :Agent => { :null => true, }, }, :view => { '-all-' => { :shown => false, }, }, }, :pending_migration => false, :position => 1490, :created_by_id => 1, :updated_by_id => 1, ) end def down end end
Update package creation to use Ruby zip library instead of OS zip utility.
unversioned = `git ls-files -o src`.strip if !unversioned.empty? puts "Error: Unversioned files in tree, exiting.\n#{unversioned}" exit 1 end version = `jq -r .version src/manifest.json`.strip if version.empty? puts 'Error: Package version not found in manifest.json, exiting.' exit 1 end out = "marinara-#{version}.zip" `(cd src && zip -r - .) > #{out}` puts "Package created: #{out}."
require 'json' require 'zip/zip' unversioned = `git ls-files -o src`.strip if !unversioned.empty? puts "Error: Unversioned files in tree, exiting.\n#{unversioned}" exit 1 end version = JSON.load(File.read('src/manifest.json'))['version'] out = "marinara-#{version}.zip" Zip::ZipFile::open(out, 'w') do |zip| Dir['src/**/*'].each do |path| zip.add(path.sub(/^src\//, ''), path) end end puts "Package created: #{out}."
Add rake as development dependency
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) require 'net_http_ssl_fix/version' Gem::Specification.new do |s| s.name = 'net_http_ssl_fix' s.version = NetHttpSslFix::VERSION s.summary = 'Community-updated Net::HTTP certificate authority file hack. Very useful for authoring HTTP clients that must run on Ruby + Windows.' s.description = 'Get rid of this lovely error for good, especially on Windows: `SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed`' s.authors = ['Chris Peters'] s.email = 'chris@minimalorange.com' s.license = 'MIT' s.homepage = 'https://github.com/liveeditor/net_http_ssl_fix' s.files = `git ls-files`.split("\n") s.require_paths = ['lib'] s.add_development_dependency 'rspec', '~> 3.4.0' end
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) require 'net_http_ssl_fix/version' Gem::Specification.new do |s| s.name = 'net_http_ssl_fix' s.version = NetHttpSslFix::VERSION s.summary = 'Community-updated Net::HTTP certificate authority file hack. Very useful for authoring HTTP clients that must run on Ruby + Windows.' s.description = 'Get rid of this lovely error for good, especially on Windows: `SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed`' s.authors = ['Chris Peters'] s.email = 'chris@minimalorange.com' s.license = 'MIT' s.homepage = 'https://github.com/liveeditor/net_http_ssl_fix' s.files = `git ls-files`.split("\n") s.require_paths = ['lib'] s.add_development_dependency 'rake', '~> 11.1.2' s.add_development_dependency 'rspec', '~> 3.4.0' end
Update gemspec with minimum ruby/rails versions
$:.unshift File.expand_path("../lib", __FILE__) require "sprockets/rails/version" Gem::Specification.new do |s| s.name = "sprockets-rails" s.version = Sprockets::Rails::VERSION s.homepage = "https://github.com/rails/sprockets-rails" s.summary = "Sprockets Rails integration" s.license = "MIT" s.files = Dir["README.md", "lib/**/*.rb", "MIT-LICENSE"] s.required_ruby_version = '>= 1.9.3' s.add_dependency "sprockets", ">= 3.0.0" s.add_dependency "actionpack", ">= 4.0" s.add_dependency "activesupport", ">= 4.0" s.add_development_dependency "railties", ">= 4.0" s.add_development_dependency "rake" s.add_development_dependency "sass" s.add_development_dependency "uglifier" s.author = "Joshua Peek" s.email = "josh@joshpeek.com" end
$:.unshift File.expand_path("../lib", __FILE__) require "sprockets/rails/version" Gem::Specification.new do |s| s.name = "sprockets-rails" s.version = Sprockets::Rails::VERSION s.homepage = "https://github.com/rails/sprockets-rails" s.summary = "Sprockets Rails integration" s.license = "MIT" s.files = Dir["README.md", "lib/**/*.rb", "MIT-LICENSE"] s.required_ruby_version = '>= 2.5' s.add_dependency "sprockets", ">= 3.0.0" s.add_dependency "actionpack", ">= 5.2" s.add_dependency "activesupport", ">= 5.2" s.add_development_dependency "railties", ">= 5.2" s.add_development_dependency "rake" s.add_development_dependency "sass" s.add_development_dependency "uglifier" s.author = "Joshua Peek" s.email = "josh@joshpeek.com" end
Bring base controller from spree
require 'cancan' require_dependency 'spree/core/controller_helpers/strong_parameters' class Spree::BaseController < ApplicationController include Spree::Core::ControllerHelpers::Auth include Spree::Core::ControllerHelpers::RespondWith include Spree::Core::ControllerHelpers::SSL include Spree::Core::ControllerHelpers::Common include Spree::Core::ControllerHelpers::Search include Spree::Core::ControllerHelpers::StrongParameters include Spree::Core::ControllerHelpers::Search respond_to :html end require 'spree/i18n/initializer'
Add .pre for next release
# This file is maintained by a herd of rabid monkeys with Rakes. module EY class CloudClient VERSION = '1.0.6' end end # Please be aware that the monkeys like tho throw poo sometimes.
# This file is maintained by a herd of rabid monkeys with Rakes. module EY class CloudClient VERSION = '1.0.7.pre' end end # Please be aware that the monkeys like tho throw poo sometimes.
Copy mongohq example conf on heroku
require 'fileutils' namespace :errbit do desc "Copys of example config files" task :copy_configs do configs = { 'config.example.yml' => 'config.yml', 'deploy.example.rb' => 'deploy.rb', 'mongoid.example.yml' => 'mongoid.yml' } puts "Copying example config files..." configs.each do |old, new| if File.exists?("config/#{new}") puts "-- Skipping config/#{new}: already exists" else puts "-- Copying config/#{old} to config/#{new}" FileUtils.cp "config/#{old}", "config/#{new}" end end end desc "Copy's over example files and seeds the database" task :bootstrap do Rake::Task['errbit:copy_configs'].execute puts "\n" Rake::Task['db:seed'].invoke puts "\n" Rake::Task['db:mongoid:create_indexes'].invoke end end
require 'fileutils' namespace :errbit do desc "Copys of example config files" task :copy_configs do configs = { 'config.example.yml' => 'config.yml', 'deploy.example.rb' => 'deploy.rb', (ENV['HEROKU'] ? 'mongoid.mongohq.yml' : 'mongoid.example.yml') => 'mongoid.yml' } puts "Copying example config files..." configs.each do |old, new| if File.exists?("config/#{new}") puts "-- Skipping config/#{new}: already exists" else puts "-- Copying config/#{old} to config/#{new}" FileUtils.cp "config/#{old}", "config/#{new}" end end end desc "Copy's over example files and seeds the database" task :bootstrap do Rake::Task['errbit:copy_configs'].execute puts "\n" Rake::Task['db:seed'].invoke puts "\n" Rake::Task['db:mongoid:create_indexes'].invoke end end
Upgrade gems to latest versions.
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "gogogibbon_tools/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "gogogibbon_tools" s.version = GogogibbonTools::VERSION s.authors = ["GoGoCarl"] s.email = ["carl.scott@solertium.com"] s.homepage = "https://github.com/GoGoCarl/gogogibbon_tools" s.summary = "Engine exposing quick utilities for Mailchimp run through GoGoGibbon." s.description = "Engine exposing quick utilities for Mailchimp run through GoGoGibbon." s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"] s.test_files = Dir["test/**/*"] s.add_dependency "slim" s.add_dependency "rails", "~> 3.2.13.rc1" s.add_dependency "gogogibbon", "~> 1.1.1" s.add_dependency "bootstrap-sass", '3.1.1.0' s.add_dependency "sass-rails", '> 3.2', '< 5' # s.add_dependency "jquery-rails" end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "gogogibbon_tools/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "gogogibbon_tools" s.version = GogogibbonTools::VERSION s.authors = ["GoGoCarl"] s.email = ["carl.scott@solertium.com"] s.homepage = "https://github.com/GoGoCarl/gogogibbon_tools" s.summary = "Engine exposing quick utilities for Mailchimp run through GoGoGibbon." s.description = "Engine exposing quick utilities for Mailchimp run through GoGoGibbon." s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"] s.test_files = Dir["test/**/*"] s.add_dependency "slim" s.add_dependency "rails", "~>4.2" s.add_dependency "gogogibbon", "~> 1.1.1" s.add_dependency "bootstrap-sass" s.add_dependency "sass-rails" s.add_dependency "protected_attributes" # s.add_dependency "jquery-rails" end
Gather should generate valid XML.
Gather = Bandwidth::Xml::Verbs::Gather describe Gather do describe '#to_xml' do it 'should generate valid xml' do expect(Helper.to_xml(Gather.new(:request_url => "http://localhost"))).to eql("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response><Gather requestUrl=\"http://localhost\"/></Response>") expect(Helper.to_xml(Gather.new(:request_url => "http://localhost", :max_digits => 2))).to eql("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response><Gather requestUrl=\"http://localhost\" maxDigits=\"2\"/></Response>") end end end
Gather = Bandwidth::Xml::Verbs::Gather describe Gather do describe '#to_xml' do it 'should generate valid xml' do expect(Helper.to_xml(Gather.new(:request_url => "http://localhost"))).to eql("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response><Gather requestUrl=\"http://localhost\"></Gather></Response>") expect(Helper.to_xml(Gather.new(:request_url => "http://localhost", :max_digits => 2))).to eql("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response><Gather requestUrl=\"http://localhost\" maxDigits=\"2\"></Gather></Response>") end end end
Fix NamePartyExtractor when regex doesn't match
class NamePartyExtractor def initialize(text) @text = text end def extract people = [] parties = [] pairs = @text.gsub("\n", '').gsub(' und', ', ').split(',').map(&:strip) pairs.each do |line| m = line.match(/(.+)\s\((.+)\)/) people << m[1].strip.gsub(/\p{Z}+/, ' ') parties << m[2].strip.gsub(/\p{Z}+/, ' ') end { people: people, parties: parties.uniq } end end
class NamePartyExtractor def initialize(text) @text = text end def extract people = [] parties = [] pairs = @text.gsub("\n", '').gsub(' und', ', ').split(',').map(&:strip) pairs.each do |line| m = line.match(/(.+)\s\((.+)\)/) next if m.nil? people << m[1].strip.gsub(/\p{Z}+/, ' ') parties << m[2].strip.gsub(/\p{Z}+/, ' ') end { people: people, parties: parties.uniq } end end
Use `git ls-files` to create the file list for the gem
Gem::Specification.new do |s| s.name = 'jbuilder' s.version = '1.0.2' s.author = 'David Heinemeier Hansson' s.email = 'david@37signals.com' s.summary = 'Create JSON structures via a Builder-style DSL' s.license = 'MIT' s.add_dependency 'activesupport', '>= 3.0.0' s.add_development_dependency 'rake', '~> 10.0.3' s.files = Dir["#{File.dirname(__FILE__)}/**/*"] end
Gem::Specification.new do |s| s.name = 'jbuilder' s.version = '1.0.2' s.author = 'David Heinemeier Hansson' s.email = 'david@37signals.com' s.summary = 'Create JSON structures via a Builder-style DSL' s.license = 'MIT' s.add_dependency 'activesupport', '>= 3.0.0' s.add_development_dependency 'rake', '~> 10.0.3' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- test/*`.split("\n") end
Change to prevent duplicate colors.
# coding: utf-8 module Pastel # Collects a list of decorators for styling a string # # @api private class DecoratorChain include Enumerable include Equatable def initialize(decorators = []) @decorators = decorators end # Add decorator # # @api public def add(decorator) self.class.new(decorators + [decorator]) end # Iterate over list of decorators # # @api public def each(&block) decorators.each(&block) end # Create an empty decorator chain # # @return [DecoratorChain] # # @api public def self.empty new([]) end protected attr_reader :decorators end # DecoratorChain end # Patel
# coding: utf-8 module Pastel # Collects a list of decorators for styling a string # # @api private class DecoratorChain include Enumerable include Equatable def initialize(decorators = []) @decorators = decorators end # Add decorator # # @api public def add(decorator) if decorators.include?(decorator) self.class.new(decorators) else self.class.new(decorators + [decorator]) end end # Iterate over list of decorators # # @api public def each(&block) decorators.each(&block) end # Create an empty decorator chain # # @return [DecoratorChain] # # @api public def self.empty new([]) end protected attr_reader :decorators end # DecoratorChain end # Patel
Save browser logs to log/browser.log in tests.
# Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/ RSpec.configure do |config| config.after(:each, type: :system) do next if page.driver.browser.browser != :chrome errors = page.driver.browser.manage.logs.get(:browser).select { |m| m.level == 'SEVERE' && m.to_s =~ %r{EvalError|InternalError|RangeError|ReferenceError|SyntaxError|TypeError|URIError} } if errors.present? Rails.logger.error "JS ERRORS: #{errors.to_json}" errors.each do |error| puts "#{error.message}\n\n" end end expect(errors.length).to eq(0) end end
# Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/ RSpec.configure do |config| config.after(:each, type: :system) do next if page.driver.browser.browser != :chrome logs = page.driver.browser.manage.logs.get(:browser) errors = logs.select { |m| m.level == 'SEVERE' && m.to_s =~ %r{EvalError|InternalError|RangeError|ReferenceError|SyntaxError|TypeError|URIError} } if errors.present? Rails.logger.error "JS ERRORS: #{errors.to_json}" errors.each do |error| puts "#{error.message}\n\n" end File.write(Rails.root.join('log/browser.log'), logs.map { |l| "#{l.level}|#{l.message}" }.join("\n")) end expect(errors.length).to eq(0) end end
Tweak language of number-of-blocks matcher.
When /^build an index on the reference sequence$/ do @idx = Bio::MAF::KyotoIndex.build(@parser, '%') end Given /^a Kyoto Cabinet index file "(.*?)"$/ do |name| @idx = Bio::MAF::KyotoIndex.open($test_data + name) end Then /^the index has at least (\d+) entries$/ do |size_spec| @idx.db.count.should be >= size_spec.to_i end When /^search for blocks between positions (\d+) and (\d+) of (\S+)$/ do |i_start, i_end, chr| int = Bio::GenomicInterval.zero_based(chr, i_start.to_i, i_end.to_i) @blocks = @idx.find([int], @parser) end Then /^(\d+) blocks are obtained$/ do |num| @blocks.size.should == num.to_i end
When /^build an index on the reference sequence$/ do @idx = Bio::MAF::KyotoIndex.build(@parser, '%') end Given /^a Kyoto Cabinet index file "(.*?)"$/ do |name| @idx = Bio::MAF::KyotoIndex.open($test_data + name) end Then /^the index has at least (\d+) entries$/ do |size_spec| @idx.db.count.should be >= size_spec.to_i end When /^search for blocks between positions (\d+) and (\d+) of (\S+)$/ do |i_start, i_end, chr| int = Bio::GenomicInterval.zero_based(chr, i_start.to_i, i_end.to_i) @blocks = @idx.find([int], @parser) end Then /^(\d+) blocks? (?:is|are) obtained$/ do |num| @blocks.size.should == num.to_i end
Add new acceptance test for class
require 'spec_helper_acceptance' describe 'swap_file class', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do context 'swap_file' do context 'ensure => present' do it 'should work with no errors' do pp = <<-EOS class { 'swap_file': files => { 'swapfile' => { ensure => 'present', }, 'use fallocate' => { swapfile => '/tmp/swapfile.fallocate', cmd => 'fallocate', }, 'remove swap file' => { ensure => 'absent', swapfile => '/tmp/swapfile.old', }, }, } EOS # Run it twice and test for idempotency apply_manifest(pp, :catch_failures => true) apply_manifest(pp, :catch_changes => true) end it 'should contain the default swapfile' do shell('/sbin/swapon -s | grep /mnt/swap.1', :acceptable_exit_codes => [0]) end it 'should contain the default fstab setting' do shell('cat /etc/fstab | grep /mnt/swap.1', :acceptable_exit_codes => [0]) shell('cat /etc/fstab | grep defaults', :acceptable_exit_codes => [0]) end it 'should contain the default swapfile' do shell('/sbin/swapon -s | grep /tmp/swapfile.fallocate', :acceptable_exit_codes => [0]) end it 'should contain the default fstab setting' do shell('cat /etc/fstab | grep /tmp/swapfile.fallocate', :acceptable_exit_codes => [0]) end end end end
Fix typo in Unicorn config
worker_processes Integer(ENV[WEB_CONCURRENCY] || 3) timeout 15 preload_app true before_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn master intercepting TERM and sending myself QUIT instead' Process.kill 'QUIT', Process.pid end defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect! end after_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to send QUIT' end defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection end
worker_processes Integer(ENV["WEB_CONCURRENCY"] || 3) timeout 15 preload_app true before_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn master intercepting TERM and sending myself QUIT instead' Process.kill 'QUIT', Process.pid end defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect! end after_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to send QUIT' end defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection end
Use double instead of mock
describe CloudNoteMailer do describe '.syncdown_note_failed' do let(:provider) { 'PROVIDER01' } let(:guid) { 'USER01' } let(:username) { 'USER01' } let(:error) { mock('error', :class => 'ERRORCLASS', :message => 'ERRORMESSAGE', :backtrace => ['ERROR', 'BACKTRACE']) } let(:mail) { CloudNoteMailer.syncdown_note_failed(provider, guid, username, error) } it 'renders the subject' do mail.subject.should == I18n.t('notes.sync.failed.email.subject', :provider => provider.titlecase, :guid => guid, :username => username) end it 'renders the receiver email' do mail.to.should == [Settings.monitoring.email] end it 'renders the sender email' do mail.from.should == [Settings.admin.email] end it 'assigns @name' do mail.body.encoded.should match(Settings.monitoring.name) end it 'assigns @user' do mail.body.encoded.should match(username) end it 'assigns @error class' do mail.body.encoded.should match('ERRORCLASS') end it 'assigns @error message' do # Is this needed? pending "mail.body.encoded.should match('ERRORMESSAGE')" end end end
# encoding: utf-8 describe CloudNoteMailer do describe '.syncdown_note_failed' do let(:provider) { 'PROVIDER01' } let(:guid) { 'USER01' } let(:username) { 'USER01' } let(:error) { double('error', class: 'ERRORCLASS', message: 'ERRORMESSAGE', backtrace: %w(ERROR BACKTRACE)) } let(:mail) { CloudNoteMailer.syncdown_note_failed(provider, guid, username, error) } it 'renders the subject' do mail.subject.should == I18n.t('notes.sync.failed.email.subject', provider: provider.titlecase, guid: guid, username: username) end it 'renders the receiver email' do mail.to.should == [Settings.monitoring.email] end it 'renders the sender email' do mail.from.should == [Settings.admin.email] end it 'assigns @name' do mail.body.encoded.should match(Settings.monitoring.name) end it 'assigns @user' do mail.body.encoded.should match(username) end it 'assigns @error class' do mail.body.encoded.should match('ERRORCLASS') end it 'assigns @error message' do # Is this needed? pending "mail.body.encoded.should match('ERRORMESSAGE')" end end end
Add skipped integration tests for unintrospectable signals
require 'gir_ffi_test_helper' GirFFI.setup :Gst Gst.init [] # Tests behavior of objects in the generated Gio namespace. describe 'the generated Gst module' do describe 'Gst::FakeSink' do let(:instance) { Gst::ElementFactory.make('fakesink', 'sink') } it 'allows the handoff signal to be connected and emitted' do skip a = nil instance.signal_connect('handoff') { a = 10 } instance.signal_emit('handoff') a.must_equal 10 end end end
Convert to startURL instead of retURL and dry it up a bit.
class MainController < NSWindowController extend IB outlet :webview, WebView outlet :w, NSWindow attr_accessor :end_point, :window_title def generate_login_url end_point case end_point when "prod" @end_point = "https://login.salesforce.com?retURL=/one/one.app" @window_title = "Production Org" when "sandbox" @end_point = "https://test.salesforce.com?retURL=/one/one.app" @window_title = "Sandbox Org" when "pre" @end_point = "https://gs0.salesforce.com?retURL=/one/one.app" @window_title = "Pre-Release Org" else @end_point = "https://login.salesforce.com?retURL=/one/one.app" @window_title = "Production Org" end end def init end_point generate_login_url end_point initWithWindowNibName('MainWindow') end def windowDidLoad load(self) w.title = "Motion1 - #{@window_title}" end def load(sender) request = NSURLRequest.requestWithURL(NSURL.URLWithString(@end_point)) webview.mainFrame.loadRequest(request) end end
class MainController < NSWindowController extend IB outlet :webview, WebView outlet :w, NSWindow attr_accessor :end_point, :window_title def generate_login_url end_point case end_point when "prod" @end_point = "https://login.salesforce.com" @window_title = "Production Org" when "sandbox" @end_point = "https://test.salesforce.com" @window_title = "Sandbox Org" when "pre" @end_point = "https://gs0.salesforce.com" @window_title = "Pre-Release Org" else @end_point = "https://login.salesforce.com" @window_title = "Production Org" end # Per PR-1, i've changed this from retURL to startURL to support SSO @end_point += "?startURL=/one/one.app" end def init end_point generate_login_url end_point initWithWindowNibName('MainWindow') end def windowDidLoad load(self) w.title = "Motion1 - #{@window_title}" end def load(sender) request = NSURLRequest.requestWithURL(NSURL.URLWithString(@end_point)) webview.mainFrame.loadRequest(request) end end
Update syntax of expect in User spec
require 'spec_helper' describe User do describe "associations" do it { should have_many(:subscriptions) } it { should have_many(:comics).through(:subscriptions) } end describe "validations" do it { should validate_presence_of(:username) } end describe "subscriptions" do let(:user) { Factory(:user) } let(:comic) { Factory(:comic) } it "has no subscribed comics" do user.subscriptions.should be_empty end it "can subscribe to a comic" do expect { user.subscribe!(comic) }.to change { user.subscriptions.count }.by(1) end it "cannot subscribe to the same comic twice" do user.subscribe!(comic) expect { user.subscribe!(comic) }.to_not change { user.subscriptions.count } end end end
require 'spec_helper' describe User do describe "associations" do it { should have_many(:subscriptions) } it { should have_many(:comics).through(:subscriptions) } end describe "validations" do it { should validate_presence_of(:username) } end describe "subscriptions" do let(:user) { Factory(:user) } let(:comic) { Factory(:comic) } it "has no subscribed comics" do user.subscriptions.should be_empty end it "can subscribe to a comic" do expect { user.subscribe!(comic) }.to change(user.subscriptions, :count).by(1) end it "cannot subscribe to the same comic twice" do user.subscribe!(comic) expect { user.subscribe!(comic) }.to_not change(user.subscriptions, :count) end end end
Switch to Alice & Bob
User.create!(username: "michael", password: "foobar") User.create!(username: "lee", password: "asdfasdf") User.create!(username: "nick", password: "fdsafdsa")
User.create!(username: "alice", password: "wonderland") User.create!(username: "bob", password: "asdfasdf")
Upgrade complete, test coverage needs increase
FactoryBot.define do factory :image do attachment { StringIO.new(File.open("./spec/fixture.jpg").read) } meta {({x: 1, y: 2, z: 3})} device end end
FactoryBot.define do factory :image do meta { ({ x: 1, y: 2, z: 3 }) } device end end
Remove Migrate button for SCVMM VMs
class ManageIQ::Providers::Redhat::InfraManager::Vm < ManageIQ::Providers::InfraManager::Vm include_concern 'Operations' include_concern 'RemoteConsole' def provider_object(connection = nil) connection ||= self.ext_management_system.connect connection.get_resource_by_ems_ref(self.ems_ref) end def scan_via_ems? true end def parent_cluster rp = self.parent_resource_pool rp && rp.detect_ancestor(:of_type => "EmsCluster").first end alias owning_cluster parent_cluster alias ems_cluster parent_cluster # # UI Button Validation Methods # def has_required_host? true end def cloneable? true end def self.calculate_power_state(raw_power_state) case raw_power_state when 'up' then 'on' when 'down' then 'off' else super end end end
class ManageIQ::Providers::Redhat::InfraManager::Vm < ManageIQ::Providers::InfraManager::Vm include_concern 'Operations' include_concern 'RemoteConsole' def provider_object(connection = nil) connection ||= self.ext_management_system.connect connection.get_resource_by_ems_ref(self.ems_ref) end def scan_via_ems? true end def parent_cluster rp = self.parent_resource_pool rp && rp.detect_ancestor(:of_type => "EmsCluster").first end alias owning_cluster parent_cluster alias ems_cluster parent_cluster # # UI Button Validation Methods # def has_required_host? true end def cloneable? true end def self.calculate_power_state(raw_power_state) case raw_power_state when 'up' then 'on' when 'down' then 'off' else super end end def validate_migrate validate_unsupported("Migrate") end end
Fix style: tab-size (This time it will work)
class Gigasecond def self.from time time + 10**9 end end module BookKeeping VERSION = 6 end
class Gigasecond def self.from time time + 10**9 end end module BookKeeping VERSION = 6 end
Remove unnecessary if test, @commands is set to an empty array by default
module Sprinkle module Installers class Rake < Installer def initialize(parent, commands = [], &block) super parent, &block @commands = commands end protected def install_sequence if @commands "rake #{@commands.join(' ')}" end end end end end
module Sprinkle module Installers class Rake < Installer def initialize(parent, commands = [], &block) super parent, &block @commands = commands end protected def install_sequence "rake #{@commands.join(' ')}" end end end end
Fix notifiable based mailer check
module ActsAsNotifiable module Couriers module Email def self.inject(notifiable) notifiable.notification_after_create << :email end class Courier < ActsAsNotifiable::Courier def deliver mailer.delay.notification @notification end def mailer if @notification.type == 'Notification' notifiable_mailer else notification_mailer end end def notifiable_mailer "#{notifiable.class}NotificationMailer".safe_constantize end def notification_mailer "#{@notification.class}Mailer".safe_constantize end end end end end
module ActsAsNotifiable module Couriers module Email def self.inject(notifiable) notifiable.notification_after_create << :email end class Courier < ActsAsNotifiable::Courier def deliver mailer.delay.notification @notification end def mailer if @notification.instance_of? Notification notifiable_mailer else notification_mailer end end def notifiable_mailer "#{@notifiable.class}NotificationMailer".safe_constantize end def notification_mailer "#{@notification.class}Mailer".safe_constantize end end end end end
Allow BlockscoreError to initialize when json_body passed in is empty
module BlockScore class BlockscoreError < StandardError attr_reader :message attr_reader :error_type attr_reader :http_status attr_reader :json_body def initialize(message=nil, json_body=nil, http_status="400", error_type="invalid_request_error") super(message) message_desc = "#{json_body["error"]["param"]} #{json_body["error"]["code"]}" @error_type = error_type @http_status = http_status @json_body = json_body @message = "#{message} (#{message_desc})" end def to_s "Status: #{@http_status}. Type: #{@error_type}, Message: #{@message}" end end end
module BlockScore class BlockscoreError < StandardError attr_reader :message attr_reader :error_type attr_reader :http_status attr_reader :json_body def initialize(message=nil, json_body={}, http_status="400", error_type="invalid_request_error") super(message) json_body["error"] ||= {} message_desc = "#{json_body["error"]["param"]} #{json_body["error"]["code"]}" @error_type = error_type @http_status = http_status @json_body = json_body @message = "#{message} (#{message_desc})" end def to_s "Status: #{@http_status}. Type: #{@error_type}, Message: #{@message}" end end end
Put ab_variant into cache key for start page.
class HomeController < ApplicationController caches_action :index, :expires_in => 1.hour, :unless => lambda { user_signed_in? || admin_signed_in? } def index render end end
class HomeController < ApplicationController caches_action :index, :expires_in => 1.hour, :unless => lambda { user_signed_in? || admin_signed_in? }, :cache_path => Proc.new {|c| c.params.delete_if { |k,v| %w{lat lon zoom q layers a}.include?(k) }.merge(:ab_splash_screen => ab_test("splash_screen").to_s) } def index render end end
Set owner on repo creation
class User < ApplicationRecord has_many :repos def remote client = Octokit::Client.new access_token: token client if client.user rescue Octokit::Unauthorized end def self.from_token token User.find_by(token: token) || begin remote = Octokit::Client.new access_token: token user = User.create token: token, username: remote.user.login remote.repositories.each do |repo| if repo.permissions.admin Repo.create user_id: user.id, name: repo.name end end rescue Octokit::Unauthorized end end end
class User < ApplicationRecord has_many :repos def remote client = Octokit::Client.new access_token: token client if client.user rescue Octokit::Unauthorized end def self.from_token token User.find_by(token: token) || begin remote = Octokit::Client.new access_token: token user = User.create token: token, username: remote.user.login remote.repositories.each do |repo| if repo.permissions.admin Repo.create name: repo.name, user_id: user.id, owner: repo.owner.login end end user rescue Octokit::Unauthorized end end end
Add CocoaDeveloper Quicklook Plugin v1.3.0
class Ipaql < Cask url 'http://ipaql.com/site/assets/files/1006/ipaql_1-3-0.zip' homepage 'http://ipaql.com/' version '1.3.0' sha1 'a870da34839b42945cf2334c7a27c2574d41ffcd' qlplugin 'IPAQuickLook-1.3.0/IPAQuickLook.qlgenerator' end
Fix gemspec to not include gem files
Gem::Specification.new do |s| s.name = 'bible-passage' s.summary = 'A simple library for parsing and rendering bible passages' s.version = '0.0.1' s.authors = ["Si Wilkins"] s.email = 'si.wilkins@gmail.com' s.homepage = 'https://github.com/siwilkins/bible-passage' readmes = Dir['*'].reject{ |x| x = ~ /(^|[^.a-z])[a-z]+/ || x == "TODO" || x = ~ /\.gem$/ } s.files = Dir['lib/**/*', 'spec/**/*'] + readmes s.has_rdoc = false s.test_files = Dir["test/**/*_test.rb"] s.license = "MIT" s.description = <<-END bible-passage provides a facility for parsing a string to check its validity as a Bible reference, and then render it in a consistent manner. END s.add_development_dependency 'rspec', '~> 3.0' s.add_development_dependency 'guard', '~> 2.6' s.add_development_dependency 'guard-rspec', '~> 4.2' s.add_development_dependency 'fuubar', '~> 1.3' end
Gem::Specification.new do |s| s.name = 'bible-passage' s.summary = 'A simple library for parsing and rendering bible passages' s.version = '0.0.1' s.authors = ["Si Wilkins"] s.email = 'si.wilkins@gmail.com' s.homepage = 'https://github.com/siwilkins/bible-passage' readmes = Dir['*'].reject{ |x| x = ~ /(^|[^.a-z])[a-z]+/ || x == "TODO" || x =~ /\.gem$/ } s.files = Dir['lib/**/*', 'spec/**/*'] + readmes s.has_rdoc = false s.test_files = Dir["test/**/*_test.rb"] s.license = "MIT" s.description = <<-END bible-passage provides a facility for parsing a string to check its validity as a Bible reference, and then render it in a consistent manner. END s.add_development_dependency 'rspec', '~> 3.0' s.add_development_dependency 'guard', '~> 2.6' s.add_development_dependency 'guard-rspec', '~> 4.2' s.add_development_dependency 'fuubar', '~> 1.3' end
Revert "Add missing API fields"
module Nomis class Offender class Details include MemoryModel attribute :given_name, :string attribute :surname, :string attribute :title, :string attribute :nationalities, :string attribute :date_of_birth, :date attribute :aliases attribute :gender attribute :religion attribute :ethnicity attribute :convicted, :boolean attribute :imprisonment_status attribute :cro_number, :string attribute :pnc_number, :string attribute :iep_level attribute :api_call_successful, :boolean, default: true def valid? api_call_successful end end end end
module Nomis class Offender class Details include MemoryModel attribute :given_name, :string attribute :surname, :string attribute :title, :string attribute :date_of_birth, :date attribute :aliases attribute :gender attribute :convicted, :boolean attribute :imprisonment_status attribute :iep_level attribute :api_call_successful, :boolean, default: true def valid? api_call_successful end end end end
Change nested describe blocks into context blocks
require 'spec_helper' describe 'Veritas::Logic::Predicate::Enumerable.compare_method' do subject { object.compare_method(enumerable) } let(:object) { Logic::Predicate::Enumerable } describe 'the enumerable is a Range' do let(:enumerable) { 1..2 } it { should == :cover? } end describe 'the enumerable is an Array' do let(:enumerable) { [ 1, 2 ] } it { should == :include? } end end
require 'spec_helper' describe 'Veritas::Logic::Predicate::Enumerable.compare_method' do subject { object.compare_method(enumerable) } let(:object) { Logic::Predicate::Enumerable } context 'the enumerable is a Range' do let(:enumerable) { 1..2 } it { should == :cover? } end context 'the enumerable is an Array' do let(:enumerable) { [ 1, 2 ] } it { should == :include? } end end
Fix a permalink redirector 500
class Users::PbsController < ApplicationController before_action :set_user, only: [:show] before_action :set_game, only: [:show] before_action :set_category, only: [:show] def show if @user.patron?(tier: 3) if params[:trailing_path].nil? redirect_to run_path(@user.pb_for(@category)) else redirect_to "#{run_path(@user.pb_for(@category))}/#{params[:trailing_path]}" end else redirect_to user_path(@user), alert: 'Redirectors are not enabled for this account.' end end private def set_user @user = User.find_by(name: params[:user]) || not_found end def set_game @game = Game.joins(:srdc).find_by(speedrun_dot_com_games: {shortname: params[:game]}) || Game.find_by(id: params[:game]) not_found if @game.nil? end def set_category @category = @game.categories.where(shortname: params[:category]).or( @game.categories.where(id: params[:category]) ).first not_found if @category.nil? end end
class Users::PbsController < ApplicationController before_action :set_user, only: [:show] before_action :set_game, only: [:show] before_action :set_category, only: [:show] def show if @user.patron?(tier: 3) if params[:trailing_path].nil? redirect_to run_path(@user.pb_for(Run::REAL, @category)) else redirect_to "#{run_path(@user.pb_for(@category))}/#{params[:trailing_path]}" end else redirect_to user_path(@user), alert: 'Redirectors are not enabled for this account.' end end private def set_user @user = User.find_by(name: params[:user]) || not_found end def set_game @game = Game.joins(:srdc).find_by(speedrun_dot_com_games: {shortname: params[:game]}) || Game.find_by(id: params[:game]) not_found if @game.nil? end def set_category @category = @game.categories.where(shortname: params[:category]).or( @game.categories.where(id: params[:category]) ).first not_found if @category.nil? end end
Make sure we properly zip binary files on Windows.
require 'zip/zip' require 'tempfile' require 'find' module Selenium module WebDriver module Zipper EXTENSIONS = %w[.zip .xpi] def self.unzip(path) destination = Dir.mktmpdir("unzip") FileReaper << destination Zip::ZipFile.open(path) do |zip| zip.each do |entry| to = File.join(destination, entry.name) dirname = File.dirname(to) FileUtils.mkdir_p dirname unless File.exist? dirname zip.extract(entry, to) end end destination end def self.zip(path) tmp_zip = Tempfile.new("webdriver-zip") begin zos = Zip::ZipOutputStream.new(tmp_zip.path) ::Find.find(path) do |file| next if File.directory?(file) entry = file.sub("#{path}/", '') zos.put_next_entry(entry) zos << File.read(file) end zos.close tmp_zip.rewind [tmp_zip.read].pack("m") ensure tmp_zip.close end end end # Zipper end # WebDriver end # Selenium
require 'zip/zip' require 'tempfile' require 'find' module Selenium module WebDriver module Zipper EXTENSIONS = %w[.zip .xpi] def self.unzip(path) destination = Dir.mktmpdir("unzip") FileReaper << destination Zip::ZipFile.open(path) do |zip| zip.each do |entry| to = File.join(destination, entry.name) dirname = File.dirname(to) FileUtils.mkdir_p dirname unless File.exist? dirname zip.extract(entry, to) end end destination end def self.zip(path) tmp_zip = Tempfile.new("webdriver-zip") begin zos = Zip::ZipOutputStream.new(tmp_zip.path) ::Find.find(path) do |file| next if File.directory?(file) entry = file.sub("#{path}/", '') zos.put_next_entry(entry) zos << File.read(file, "rb") end zos.close tmp_zip.rewind [tmp_zip.read].pack("m") ensure tmp_zip.close end end end # Zipper end # WebDriver end # Selenium
Remove repeated elements from two files
#!/usr/bin/env ruby-local-exec # Author: Matti # Version: 0.1 # Usage: ./remove_duplicates_from_two_files.rb path/to/first/file path/to/second/file first_file_path = ARGV[0] second_file_path = ARGV[1] first_file = File.open(first_file_path) second_file = File.open(second_file_path) elements_from_first_file = [] first_file.each_line { |line| elements_from_first_file << line } first_file.close elements_from_second_file = [] second_file.each_line { |line| elements_from_second_file << line } second_file.close common_elements = (elements_from_first_file & elements_from_second_file) if common_elements.empty? puts 'No common elements found. Nothing to do, yay!' exit end unique_elements_from_first_file = elements_from_first_file - common_elements unique_elements_from_second_file = elements_from_second_file - common_elements first_file = File.open(first_file_path, 'w') second_file = File.open(second_file_path, 'w') unique_elements_from_first_file.each { |elem| first_file.write(elem) } first_file.close unique_elements_from_second_file.each { |elem| second_file.write(elem) } second_file.close puts "Removed #{common_elements.size} common element(s):" puts common_elements.map(&:chomp).join(', ') exit
Improve system spec for live pages
require 'rails_helper' RSpec.describe 'Live', type: :system do describe 'list' do before do create_list(:live, 2) create(:live, :unpublished, name: 'draft live') end it 'enables users to see the published lives' do visit lives_path expect(page).to have_title('ライブ') Live.published.each do |live| expect(page).to have_content(live.name) end Live.unpublished.each do |draft_live| expect(page).not_to have_content(draft_live.name) end end end describe 'detail' do let(:live) { create(:live, :with_songs, album_url: 'https://example.com/album') } it 'enables non-logged-in users to see individual live pages' do visit live_path(live) expect(page).to have_title(live.title) expect(page).to have_content(live.name) expect(page).to have_content(I18n.l(live.date)) expect(page).to have_content(live.place) expect(page).not_to have_link(href: live.album_url) expect(page).not_to have_css('#admin-tools') live.songs.each do |song| expect(page).to have_content(song.name) end end it 'enables logged-in users to see individual live pages with an album link' do log_in_as create(:user) visit live_path(live) expect(page).to have_title(live.title) expect(page).to have_link(href: live.album_url) expect(page).not_to have_css('#admin-tools') end end end
require 'rails_helper' RSpec.describe 'Live:', type: :system do specify 'A user can see the live index page and a live detail page, and after logged-in, they can see album', js: true do # Given live = create(:live, :with_songs, album_url: 'https://example.com/album') user = create(:user) # When visit lives_path # Then expect(page).to have_title 'ライブ' # When find('td', text: live.name).click # Then expect(page).to have_title live.title expect(page).not_to have_link 'アルバム' # When log_in_as user visit live_path(live) # Then expect(page).to have_title live.title expect(page).to have_link 'アルバム' end end
Remove Monkey Patch for help
module SlackRubyBot module Commands class HelpCommand < Base help do title 'help' desc 'Shows help information.' end command 'help' do |client, data, match| command = match[:expression] text = if command.present? CommandsHelper.instance.command_full_desc(command) else general_text end client.say(channel: data.channel, text: text, gif: 'help') end class << self private def general_text bot_desc = CommandsHelper.instance.bot_desc_and_commands other_commands_descs = CommandsHelper.instance.other_commands_descs <<TEXT #{bot_desc.join("\n")} TEXT end end end end end
# module SlackRubyBot # module Commands # class HelpCommand < Base # help do # title 'help' # desc 'Shows help information.' # end # # command 'help' do |client, data, match| # command = match[:expression] # # text = if command.present? # CommandsHelper.instance.command_full_desc(command) # else # general_text # end # # client.say(channel: data.channel, text: text, gif: 'help') # end # # class << self # private # # def general_text # bot_desc = CommandsHelper.instance.bot_desc_and_commands # other_commands_descs = CommandsHelper.instance.other_commands_descs # <<TEXT # #{bot_desc.join("\n")} # TEXT # end # end # end # end # end
Add runtime dependency to ruby2_keywords
$:.unshift File.expand_path("../lib", __FILE__) require "mustermann/version" Gem::Specification.new do |s| s.name = "mustermann" s.version = Mustermann::VERSION s.authors = ["Konstantin Haase", "Zachary Scott"] s.email = "sinatrarb@googlegroups.com" s.homepage = "https://github.com/sinatra/mustermann" s.summary = %q{Your personal string matching expert.} s.description = %q{A library implementing patterns that behave like regular expressions.} s.license = 'MIT' s.required_ruby_version = '>= 2.2.0' 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) } end
$:.unshift File.expand_path("../lib", __FILE__) require "mustermann/version" Gem::Specification.new do |s| s.name = "mustermann" s.version = Mustermann::VERSION s.authors = ["Konstantin Haase", "Zachary Scott"] s.email = "sinatrarb@googlegroups.com" s.homepage = "https://github.com/sinatra/mustermann" s.summary = %q{Your personal string matching expert.} s.description = %q{A library implementing patterns that behave like regular expressions.} s.license = 'MIT' s.required_ruby_version = '>= 2.2.0' 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.add_runtime_dependency('ruby2_keywords', '~> 0.0.1') end
Define RSpec as our default test framework.
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module Rubygamedev class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module Rubygamedev class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de config.generators do |g| g.test_framework :rspec, fixture: false end end end
Add rollbar deploy notice ID:512
lock '3.4.0' set :repo_url, 'git@github.com:westernmilling/gman-services.git' set :branch, 'master' set :user, 'deploy' set :deploy_to, '/var/www' set :linked_files, %w{ config/application.yml config/database.yml lib/RelJDBC.jar } set :linked_dirs, %w{og tmp/pids tmp/cache tmp/sockets vendor/bundle public/system} set :keep_releases, 5 set :normalize_asset_timestamps, %w{public/images public/javascripts public/stylesheets} set :rvm_type, :user set :rvm_ruby_version, 'jruby-9.0.5.0' namespace :deploy do desc 'Restart application' task :restart do on roles(:app), in: :sequence, wait: 5 do end end after :publishing, :restart after :publishing, 'deploy:assets:precompile' end
lock '3.4.0' set :repo_url, 'git@github.com:westernmilling/gman-services.git' set :branch, 'master' set :user, 'deploy' set :deploy_to, '/var/www' set :linked_files, %w{ config/application.yml config/database.yml lib/RelJDBC.jar } set :linked_dirs, %w{og tmp/pids tmp/cache tmp/sockets vendor/bundle public/system} set :keep_releases, 5 set :normalize_asset_timestamps, %w{public/images public/javascripts public/stylesheets} set :rvm_type, :user set :rvm_ruby_version, 'jruby-9.0.5.0' set :rollbar_token, proc { Figaro.env.ROLLBAR_POST_SERVER_ITEM_ACCESS_TOKEN } set :rollbar_env, proc { fetch :stage } set :rollbar_role, proc { :app } namespace :deploy do after :starting, 'figaro:load' desc 'Restart application' task :restart do on roles(:app), in: :sequence, wait: 5 do end end after :publishing, :restart after :publishing, 'deploy:assets:precompile' end
Undo small change, moving from string to symbol (but it's indifferent access).
module API module V1 class APIController < JSONAPI::ResourceController include ActionController::HttpAuthentication::Token::ControllerMethods include ActionController::MimeResponds def context { current_user: current_user } end private def restrict_access unless restrict_access_by_params || restrict_access_by_header render json: { message: 'Invalid API token.' }, status: 401 return end @current_user = @api_key.user if @api_key end def restrict_access_by_header return true if @api_key authenticate_with_http_token { |token| @api_key = APIKey.find_by(token: token) } end def restrict_access_by_params return true if @api_key @api_key = APIKey.find_by(token: params['api_key']) end end end end
module API module V1 class APIController < JSONAPI::ResourceController include ActionController::HttpAuthentication::Token::ControllerMethods include ActionController::MimeResponds def context { current_user: current_user } end private def restrict_access unless restrict_access_by_params || restrict_access_by_header render json: { message: 'Invalid API token.' }, status: 401 return end @current_user = @api_key.user if @api_key end def restrict_access_by_header return true if @api_key authenticate_with_http_token { |token| @api_key = APIKey.find_by(token: token) } end def restrict_access_by_params return true if @api_key @api_key = APIKey.find_by(token: params[:api_key]) end end end end
Add game admin page test
# frozen_string_literal: true require 'rails_helper' RSpec.feature 'Admin::Games', level: :feature do let(:admin) { create(:admin_user) } let(:game) { create(:game) } before { sign_in admin } describe '#index' do before do @games = create_list(:game, 5) end it 'can see all game' do visit admin_games_path @games.each { |game| expect(page).to have_content(game.name) } end end describe '#new' do it 'can add new game' do visit new_admin_game_path fill_in 'game_name', with: 'Example' fill_in 'game_description', with: 'Example Description' fill_in 'game_team', with: 'Team' attach_file( 'game_thumbnail', Rails.root.join('spec', 'support', 'brands', 'logos', 'TGDF.png') ) click_button '新增Game' expect(page).to have_content('Example') end end describe '#edit' do it 'can edit game' do visit edit_admin_game_path(game) fill_in 'game_name', with: 'New Game Name' click_button '更新Game' expect(page).to have_content('New Game Name') end end describe '#destroy' do before { @game = create(:game) } it 'can destroy game' do visit admin_games_path within first('td', text: @game.name).first(:xpath, './/..') do click_on 'Destroy' end expect(page).not_to have_content(@game.name) end end end
Update test PrintLineJob with the default value for io.
class PrintLineJob extend QueueingRabbit::Job class << self attr_accessor :io end queue :print_line_job, :durable => true def self.perform(arguments = {}) self.io.puts arguments[:line] end end
class PrintLineJob extend QueueingRabbit::Job class << self attr_writer :io end queue :print_line_job, :durable => true def self.perform(arguments = {}) self.io.puts arguments[:line] end def self.io @io ||= STDOUT end end
Use constant for '.' and '..' dirs
require "walk/version" module Walk def self.walk(root, topdown=true, followlinks=false) Enumerator.new do |enum| inner_walk(enum, root, topdown=true, followlinks=false) end end def self.inner_walk(enum, root, topdown=true, followlinks=false) dirs = [] files = [] path_to_explore = [] Dir.entries(root).each do |entry| next if entry=='.' or entry=='..' fullpath = File.join(root, entry) if File.file?(fullpath) files << entry elsif File.directory?(fullpath) dirs << entry if (followlinks or not File.symlink?(fullpath)) and File.readable?(fullpath) path_to_explore << fullpath end end end enum << [root, dirs, files] if topdown path_to_explore.each do |fullpath| inner_walk(enum, fullpath, topdown, followlinks) end enum << [root, dirs, files] unless topdown end private_class_method :inner_walk end
require "walk/version" module Walk CURRENT_DIR = '.' PARENT_DIR = '..' def self.walk(root, topdown=true, followlinks=false) Enumerator.new do |enum| inner_walk(enum, root, topdown=true, followlinks=false) end end def self.inner_walk(enum, root, topdown=true, followlinks=false) dirs = [] files = [] path_to_explore = [] Dir.entries(root).each do |entry| next if entry==CURRENT_DIR or entry==PARENT_DIR fullpath = File.join(root, entry) if File.file?(fullpath) files << entry elsif File.directory?(fullpath) dirs << entry if (followlinks or not File.symlink?(fullpath)) and File.readable?(fullpath) path_to_explore << fullpath end end end enum << [root, dirs, files] if topdown path_to_explore.each do |fullpath| inner_walk(enum, fullpath, topdown, followlinks) end enum << [root, dirs, files] unless topdown end private_class_method :inner_walk end
Update Jython HEAD to 2.5.2rc3
require 'formula' class Jython <Formula url "http://downloads.sourceforge.net/project/jython/jython/2.5.1/jython_installer-2.5.1.jar", :using => :nounzip md5 '2ee978eff4306b23753b3fe9d7af5b37' homepage 'http://www.jython.org' head "http://downloads.sourceforge.net/project/jython/jython-dev/2.5.2b2/jython_installer-2.5.2b2.jar", :using => :nounzip def install system "java", "-jar", Pathname.new(@url).basename, "-s", "-d", libexec bin.mkpath ln_s libexec+'bin/jython', bin end end
require 'formula' class Jython <Formula url "http://downloads.sourceforge.net/project/jython/jython/2.5.1/jython_installer-2.5.1.jar", :using => :nounzip homepage 'http://www.jython.org' head "http://downloads.sourceforge.net/project/jython/jython-dev/2.5.2rc3/jython_installer-2.5.2rc3.jar", :using => :nounzip if ARGV.build_head? sha1 '547c424a119661ed1901079ff8f4e45af7d57b56' else md5 '2ee978eff4306b23753b3fe9d7af5b37' end def install system "java", "-jar", Pathname.new(@url).basename, "-s", "-d", libexec bin.mkpath ln_s libexec+'bin/jython', bin end end
Add rake as a dev dep
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "health_inspector/version" Gem::Specification.new do |s| s.name = "health_inspector" s.version = HealthInspector::VERSION s.authors = ["Ben Marini"] s.email = ["bmarini@gmail.com"] s.homepage = "https://github.com/bmarini/health_inspector" s.summary = %q{A tool to inspect your chef repo as is compares to what is on your chef server} s.description = %q{A tool to inspect your chef repo as is compares to what is on your chef server} s.rubyforge_project = "health_inspector" 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_development_dependency "rspec" s.add_runtime_dependency "thor" s.add_runtime_dependency "chef", "~> 10.14" s.add_runtime_dependency "yajl-ruby" end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "health_inspector/version" Gem::Specification.new do |s| s.name = "health_inspector" s.version = HealthInspector::VERSION s.authors = ["Ben Marini"] s.email = ["bmarini@gmail.com"] s.homepage = "https://github.com/bmarini/health_inspector" s.summary = %q{A tool to inspect your chef repo as is compares to what is on your chef server} s.description = %q{A tool to inspect your chef repo as is compares to what is on your chef server} s.rubyforge_project = "health_inspector" 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_development_dependency "rake" s.add_development_dependency "rspec" s.add_runtime_dependency "thor" s.add_runtime_dependency "chef", "~> 10.14" s.add_runtime_dependency "yajl-ruby" end
Add comments on find and images methods on Person.
module TMDb class Person < Base extend Searchable # Person attributes ATTRIBUTES = :id, :adult, :also_known_as, :biography, :birthday, :deathday, :homepage, :name, :place_of_birth, :profile_path, :popularity attr_reader *ATTRIBUTES def self.find(id, options = {}) res = get("/person/#{id}", query: options) res.success? ? Person.new(res) : bad_response(res) end def self.images(id, options = {}) res = get("/person/#{id}/images", query: options) res.success? ? res : bad_response(res) end end end
module TMDb class Person < Base extend Searchable # Person attributes ATTRIBUTES = :id, :adult, :also_known_as, :biography, :birthday, :deathday, :homepage, :name, :place_of_birth, :profile_path, :popularity attr_reader *ATTRIBUTES # Public: Get the basic person information for a specific person ID. # # id - The ID of the person. # options - The hash options used to filter the search (default: {}): # More information about the options, check the api documentation # # Examples # # TMDb::Person.find(138) def self.find(id, options = {}) res = get("/person/#{id}", query: options) res.success? ? Person.new(res) : bad_response(res) end # Public: Get the images for a specific person ID. # # id - The person's ID # # Examples # # TMDb::Person.images(138) def self.images(id) res = get("/person/#{id}/images") res.success? ? res : bad_response(res) end end end
Set 60min at expire of settion
module API::Auth def session env[Rack::Session::Abstract::ENV_SESSION_KEY] end def authenticated? !current_user.nil? end def authenticate!(account) session[:account_id] = account.id session[:expires_at] = Time.zone.now + 1.minutes end def current_user unless available? session.destroy return nil end Account.find_by(id: session[:account_id]) end def available? return if session[:expires_at].nil? session[:expires_at] > Time.zone.now end end
module API::Auth def session env[Rack::Session::Abstract::ENV_SESSION_KEY] end def authenticated? !current_user.nil? end def authenticate!(account) session[:account_id] = account.id session[:expires_at] = Time.zone.now + 60.minutes end def current_user unless available? session.destroy return nil end Account.find_by(id: session[:account_id]) end def available? return if session[:expires_at].nil? session[:expires_at] > Time.zone.now end end
Add connection (for the service) and client attributes.
require 'chronologic/client' require 'chronologic/connection' require 'chronologic/server' require 'chronologic/version'
require 'chronologic/client' require 'chronologic/connection' require 'chronologic/server' require 'chronologic/version' require "active_support/core_ext/module" module Chronologic VERSION = "0.1.0" mattr_accessor :connection mattr_accessor :client end
Remove SlimLogicLessConverter in favor of @config
require 'slim' module Jekyll class SlimConverter < Converter safe true priority :low def matches(ext) ext =~ /slim/i end def output_ext(ext) '.html' end def convert(content) Slim::Template.new { content }.render end end class SlimLogicLessConverter < SlimConverter def convert(content) Slime::Template.new(:logic_less => true) { content }.render end end end
require 'slim' module Jekyll class SlimConverter < Converter safe true priority :low def matches(ext) ext =~ /slim/i end def output_ext(ext) '.html' end def convert(content) Slim::Template.new(@config) { content }.render end end end
Include the error class in the client
require 'pixi_client/version' require 'pixi_client/configuration' require 'pixi_client/response_parser' require 'pixi_client/response' require 'pixi_client/requests' module PixiClient class << self def configuration @configuration ||= Configuration.new end def configure yield(configuration) end end end
require 'pixi_client/version' require 'pixi_client/error' require 'pixi_client/configuration' require 'pixi_client/response_parser' require 'pixi_client/response' require 'pixi_client/requests' module PixiClient class << self def configuration @configuration ||= Configuration.new end def configure yield(configuration) end end end
Exclude some junk from output directory
require 'haml' require 'sass' require 'coderay' class Button attr_reader :file_name, :html, :func_name, :camel_name def initialize(func_name) @func_name = func_name @camel_name = func_name.gsub(/(.)([A-Z])/,'\1_\2').downcase @file_name = "js/#{@camel_name}.js" @html = CodeRay.encode_file @file_name, :div end end before 'index.html.haml' do @buttons = %w{Buttoner HidingButtoner}.map do |func_name| Button.new func_name end end
require 'haml' require 'sass' require 'coderay' class Button attr_reader :file_name, :html, :func_name, :camel_name def initialize(func_name) @func_name = func_name @camel_name = func_name.gsub(/(.)([A-Z])/,'\1_\2').downcase @file_name = "js/#{@camel_name}.js" @html = CodeRay.encode_file @file_name, :div end end ignore *%w{.gitignore LICENSE Gemfile Gemfile.lock Rakefile} ignore(/\.swp$/, %r{/\.git/}, %r{/\.sass-cache/}) before 'index.html.haml' do @buttons = %w{Buttoner HidingButtoner}.map do |func_name| Button.new func_name end end
Update to use new URLs.
require 'httparty' require 'hashie' module Bouvier class Client include HTTParty format :xml base_uri "http://www.eot.state.ma.us" # Bouvier::Client.branches def self.branches response = get('/developers/downloads/qmaticXML.aspx') Hashie::Mash.new(response['branches']).branch end # Bouvier::Client.branch("Danvers") def self.branch(town_name) self.branches.detect{|b| b.town == town_name } end end end
require 'httparty' require 'hashie' module Bouvier class Client include HTTParty format :xml base_uri "http://www.massdot.state.ma.us" # Bouvier::Client.branches def self.branches response = get('/feeds/qmaticxml/qmaticXML.aspx') Hashie::Mash.new(response['branches']).branch end # Bouvier::Client.branch("Danvers") def self.branch(town_name) self.branches.detect{|b| b.town == town_name } end end end
Revert to naive implementation as existing implementation does not work.
require "tachyon/version" class Tachyon def self.insert(klass, data) raise ArgumentError, "data must be a hash or array" unless data.is_a?(Array) || data.is_a?(Hash) raise ArgumentError, "klass must inherit from ActiveRecord::Base" unless klass < ActiveRecord::Base if data.is_a?(Array) self.insert_records(klass, data) elsif data.is_a?(Hash) self.insert_record(klass, data) end end def self.insert_record(klass, data) if klass.has_attribute?(:created_at) && klass.has_attribute?(:updated_at) defaults = { created_at: Time.now, updated_at: Time.now }.with_indifferent_access data = defaults.merge(data.with_indifferent_access) end table = klass.arel_table mapped_data = data.map do |key, value| [table[key], value] end insert = Arel::InsertManager.new insert.into(table) insert.insert(mapped_data) begin begin klass.connection.execute(insert.to_sql) rescue ArgumentError # If we can't generate the insert using Arel (likely because # of an issue with a serialized attribute) then fall back # to safe but slow behaviour. klass.new(data).save(validate: false) end rescue ActiveRecord::RecordNotUnique end end def self.insert_records(klass, data) klass.connection.transaction do data.each do |record| self.insert_record(klass, record) end end end end
require "tachyon/version" class Tachyon def self.insert(klass, data) raise ArgumentError, "data must be a hash or array" unless data.is_a?(Array) || data.is_a?(Hash) raise ArgumentError, "klass must inherit from ActiveRecord::Base" unless klass < ActiveRecord::Base if data.is_a?(Array) self.insert_records(klass, data) elsif data.is_a?(Hash) self.insert_record(klass, data) end end def self.insert_record(klass, data) begin klass.new(data).save(validate: false) rescue ActiveRecord::RecordNotUnique end end def self.insert_records(klass, data) klass.connection.transaction do data.each do |record| self.insert_record(klass, record) end end end end
Update compo URL finder use.
require 'compo' module Bra module Model # A view into the model # # This allows parts of bra that use the model to access it without being # coupled to the actual definition of the model. class View extend Forwardable # Initialises the model view # # @param root [Root] The model root. def initialize(root) @root = root end # Allow access to the model's updates channel def_delegator :@root, :register_for_updates def_delegator :@root, :deregister_from_updates # Logs an error message in the bra log # # @api public # @example Log an error. # view.log(:error, 'The system is down!') # # @param severity [Symbol] The severity level of the log message. This # must be one of :debug, :info, :warn, :error or :fatal. # @param message [String] The log message itself. # # @return [void] def log(severity, message) find('log') { |log| log.driver_post(severity, message) } end protected # Finds a model object given its URL # # @api private # # @return [ModelObject] The found model object. def find(url, &block) Compo::UrlFinder.find(@root, url, &block) end end end end
require 'compo' module Bra module Model # A view into the model # # This allows parts of bra that use the model to access it without being # coupled to the actual definition of the model. class View extend Forwardable # Initialises the model view # # @param root [Root] The model root. def initialize(root) @root = root end # Allow access to the model's updates channel def_delegator :@root, :register_for_updates def_delegator :@root, :deregister_from_updates # Logs an error message in the bra log # # @api public # @example Log an error. # view.log(:error, 'The system is down!') # # @param severity [Symbol] The severity level of the log message. This # must be one of :debug, :info, :warn, :error or :fatal. # @param message [String] The log message itself. # # @return [void] def log(severity, message) find('log') { |log| log.driver_post(severity, message) } end protected # Finds a model object given its URL # # @api private # # @return [ModelObject] The found model object. def find(url, &block) Compo::Finders::Url.find(@root, url, &block) end end end end
Remove Tai Chi Chuan from interests
class Application < ActiveRecord::Base belongs_to :user accepts_nested_attributes_for :user validates :user, presence: true # TODO: validate that the interests are all from INTEREST_OPTIONS # (inclusion may not work since it expects to compare arrays)' validates :interests, presence: { message: "must be chosen" } validates :phone, presence: true validates :address, presence: true validates :emergency_contact_name, presence: true validates :emergency_contact_phone, presence: true validates :wahnam_courses, presence: true validates :martial_arts_experience, presence: true validates :health_issues, presence: true validates :bio, presence: true validates :why_shaolin, presence: true validates :ten_shaolin_laws, acceptance: { accept: true } INTEREST_OPTIONS = [ 'Shaolin Cosmos Chi Kung', 'Shaolin Kung Fu', 'Tai Chi Chuan' ] def interests_to_a return [] if interests.blank? interests.split(',').map {|x| x.downcase.strip } end def interested_in? interest interests_to_a.include? interest.downcase.strip # # needed b/c #interested_in? is used to determine whether or not an interest # # is selected in the new application form (which can be before the user has # # set the interests) # return false if self.interests.blank? # self.interests.split(',').map { |x| # x.downcase.strip # }.include? interest.downcase.strip end end
class Application < ActiveRecord::Base belongs_to :user accepts_nested_attributes_for :user validates :user, presence: true # TODO: validate that the interests are all from INTEREST_OPTIONS # (inclusion may not work since it expects to compare arrays)' validates :interests, presence: { message: "must be chosen" } validates :phone, presence: true validates :address, presence: true validates :emergency_contact_name, presence: true validates :emergency_contact_phone, presence: true validates :wahnam_courses, presence: true validates :martial_arts_experience, presence: true validates :health_issues, presence: true validates :bio, presence: true validates :why_shaolin, presence: true validates :ten_shaolin_laws, acceptance: { accept: true } INTEREST_OPTIONS = [ 'Shaolin Cosmos Chi Kung', 'Shaolin Kung Fu' ] def interests_to_a return [] if interests.blank? interests.split(',').map {|x| x.downcase.strip } end def interested_in? interest interests_to_a.include? interest.downcase.strip # # needed b/c #interested_in? is used to determine whether or not an interest # # is selected in the new application form (which can be before the user has # # set the interests) # return false if self.interests.blank? # self.interests.split(',').map { |x| # x.downcase.strip # }.include? interest.downcase.strip end end
Add tests for `multi` command without block given.
require 'spec_helper' module FakeRedis describe "TransactionsMethods" do before(:each) do @client = Redis.new end it "should mark the start of a transaction block" do transaction = @client.multi do @client.set("key1", "1") @client.set("key2", "2") @client.mget("key1", "key2") end transaction.should be == ["OK", "OK", ["1", "2"]] end end end
require 'spec_helper' module FakeRedis describe "TransactionsMethods" do before(:each) do @client = Redis.new end it "should mark the start of a transaction block" do transaction = @client.multi do @client.set("key1", "1") @client.set("key2", "2") @client.mget("key1", "key2") end transaction.should be == ["OK", "OK", ["1", "2"]] end it "should execute all command after multi" do @client.multi @client.set("key1", "1") @client.set("key2", "2") @client.mget("key1", "key2") @client.exec.should be == ["OK", "OK", ["1", "2"]] end end end
Add missing require for 'shellwords'
module V1 class WebhooksController < BaseController # No authorization necessary for webhook skip_before_action :doorkeeper_authorize! # POST /v1/webhooks/github def github # We are always answering with a 202 render json: {}, status: :accepted # Skip any further actions unless it is a push return unless request.headers['X-GitHub-Event'] == 'push' && repo_path.present? # Reset local changes to Puppet repository and pull changes repo = Git.open repo_path repo.reset_hard 'HEAD' repo.pull # Execute post update script, e.g. # "cd /etc/puppet/environments/production; librarian-puppet install" return unless post_update_script.present? Bundler.with_clean_env do system "bash -c #{Shellwords.escape post_update_script}" end end private def repo_path ENV['puppet_repository_path'] end def post_update_script ENV['puppet_repository_post_update'] end end end
require 'shellwords' module V1 class WebhooksController < BaseController # No authorization necessary for webhook skip_before_action :doorkeeper_authorize! # POST /v1/webhooks/github def github # We are always answering with a 202 render json: {}, status: :accepted # Skip any further actions unless it is a push return unless request.headers['X-GitHub-Event'] == 'push' && repo_path.present? # Reset local changes to Puppet repository and pull changes repo = Git.open repo_path repo.reset_hard 'HEAD' repo.pull # Execute post update script, e.g. # "cd /etc/puppet/environments/production; librarian-puppet install" return unless post_update_script.present? Bundler.with_clean_env do system "bash -c #{Shellwords.escape post_update_script}" end end private def repo_path ENV['puppet_repository_path'] end def post_update_script ENV['puppet_repository_post_update'] end end end
Use a regex to detect bash.
$:.unshift File.dirname(__FILE__) and require 'pry' unless defined? Pry::Plugins Pry.const_set :Plugins, Class.new end unless RbConfig::CONFIG['host_os'] =~ /mswin/ Pry::Commands.block_command /\.(.*)/, '.shell commands' do |cmd| if defined?(Pry::Plugins::VTerm) && Pry::Plugins::VTerm.aliases.include?(cmd) cmd = Pry::Plugins::VTerm.aliases[cmd] end Pry.config.system.call Pry.output, cmd end class Pry::Plugins::VTerm class << self def version '0.0.5' end def aliases return @@aliases || {} end end end case ENV['SHELL'] when '/bin/bash' then require 'pry/aliases/bash' end end
$:.unshift File.dirname(__FILE__) and require 'pry' unless defined? Pry::Plugins Pry.const_set :Plugins, Class.new end unless RbConfig::CONFIG['host_os'] =~ /mswin/ Pry::Commands.block_command /\.(.*)/, '.shell commands' do |cmd| if defined?(Pry::Plugins::VTerm) && Pry::Plugins::VTerm.aliases.include?(cmd) cmd = Pry::Plugins::VTerm.aliases[cmd] end Pry.config.system.call Pry.output, cmd end class Pry::Plugins::VTerm class << self def version '0.0.5' end def aliases return @@aliases || {} end end end case ENV['SHELL'] when %r!/bash\Z! then require 'pry/aliases/bash' end end
Replace preflight stanza with target rename
cask :v1 => 'nodeclipse' do version '0.11-preview' sha256 '01f630446313cb981ce2ee9b934977cfdbf318e09761dee244a3256f9a559003' url 'https://downloads.sourceforge.net/sourceforge/nodeclipse/Enide-Studio-2014-011-20140228-macosx-cocoa-x86_64.zip' homepage 'http://www.nodeclipse.org/' license :oss preflight do system '/bin/mv', '--', staged_path.join('eclipse/Eclipse.app'), staged_path.join('eclipse/Nodeclipse.app') end app 'eclipse/Nodeclipse.app' end
cask :v1 => 'nodeclipse' do version '0.11-preview' sha256 '01f630446313cb981ce2ee9b934977cfdbf318e09761dee244a3256f9a559003' url "http://downloads.sourceforge.net/project/nodeclipse/Enide-Studio-2014/#{version}/Enide-Studio-2014-011-20140228-macosx-cocoa-x86_64.zip" name 'Nodeclipse' homepage 'http://www.nodeclipse.org/' license :oss # Renamed for clarity: app name is inconsistent with its branding. # Also renamed to avoid conflict with other eclipse Casks. # Original discussion: https://github.com/caskroom/homebrew-cask/pull/8183 app 'eclipse/Eclipse.app', :target => 'Nodeclipse.app' end
Use public github url format.
# # Copyright 2012-2014 Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # name "opscode-pushy-server" default_version "1.1.0" source git: "git://opscode/opscode-pushy-server" dependency "erlang" dependency "rebar" dependency "curl" dependency "automake" dependency "autoconf" dependency "libuuid" dependency "libtool" dependency "bundler" relative_path "opscode-pushy-server" build do env = with_standard_compiler_flags(with_embedded_path) make "distclean", env: env make "rel", env: env sync "#{project_dir}/rel/opscode-pushy-server/", "#{install_dir}/embedded/service/opscode-pushy-server/" delete "#{install_dir}/embedded/service/opscode-pushy-server/log" end
# # Copyright 2012-2014 Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # name "opscode-pushy-server" default_version "1.1.0" source git: "git://github.com/opscode/opscode-pushy-server" dependency "erlang" dependency "rebar" dependency "curl" dependency "automake" dependency "autoconf" dependency "libuuid" dependency "libtool" dependency "bundler" relative_path "opscode-pushy-server" build do env = with_standard_compiler_flags(with_embedded_path) make "distclean", env: env make "rel", env: env sync "#{project_dir}/rel/opscode-pushy-server/", "#{install_dir}/embedded/service/opscode-pushy-server/" delete "#{install_dir}/embedded/service/opscode-pushy-server/log" end
Use TW apt repo for package installation
name "go" description "Installs/Configures Go servers and agents" version "0.0.4" supports "ubuntu" "12.04" recipe "go::server", "Installs and configures a Go server" recipe "go::agent", "Installs and configures a Go agent" depends "apt", "1.9.2" depends "java", "1.10.0"
name "go" description "Installs/Configures Go servers and agents" version "0.0.5" supports "ubuntu" "12.04" recipe "go::server", "Installs and configures a Go server" recipe "go::agent", "Installs and configures a Go agent" depends "apt", "1.9.2" depends "java", "1.10.0"
Add features test for form create a new user
require 'rails_helper' feature 'User managment' do scenario "add new user" do expect{ visit new_user_path fill_in 'user_user_name', with: attributes_for(:user)[:user_name] fill_in 'user_email', with: attributes_for(:user)[:email] fill_in 'user_password', with: attributes_for(:user)[:password] click_button 'create_user' }.to change(User, :count).by(1) end end
Package version is increased from 2.2.4.2 to 2.2.4.3
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'evt-schema' s.summary = "Primitives for schema and data structure" s.version = '2.2.4.2' s.description = ' ' s.authors = ['The Eventide Project'] s.email = 'opensource@eventide-project.org' s.homepage = 'https://github.com/eventide-project/schema' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.3.3' s.add_runtime_dependency 'evt-attribute' s.add_runtime_dependency 'evt-set_attributes' s.add_runtime_dependency 'evt-initializer' s.add_runtime_dependency 'evt-validate' s.add_runtime_dependency 'evt-virtual' s.add_development_dependency 'test_bench' end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'evt-schema' s.summary = "Primitives for schema and data structure" s.version = '2.2.4.3' s.description = ' ' s.authors = ['The Eventide Project'] s.email = 'opensource@eventide-project.org' s.homepage = 'https://github.com/eventide-project/schema' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.3.3' s.add_runtime_dependency 'evt-attribute' s.add_runtime_dependency 'evt-set_attributes' s.add_runtime_dependency 'evt-initializer' s.add_runtime_dependency 'evt-validate' s.add_runtime_dependency 'evt-virtual' s.add_development_dependency 'test_bench' end
Update tests for active flags
require 'spec_helper' describe MembersController do describe "GET 'index'" do it "returns http success" do get 'index' response.should be_success end end describe "GET 'show'" do it "returns http success" do @member = FactoryGirl.create :member get 'show', :id => @member.membership_number response.should be_success end end end
require 'spec_helper' describe MembersController do describe "GET 'index'" do it "returns http success" do get 'index' response.should be_success end end describe "GET 'show'" do it "returns http success if member is active" do member = FactoryGirl.create :member, :cached_active => true get 'show', :id => member.membership_number response.should be_success end it "returns 404 if member is not active" do member = FactoryGirl.create :member, :cached_active => false expect { get 'show', :id => member.membership_number }.to raise_error(ActiveRecord::RecordNotFound) end end end
Handle 404 rails way (static).
# Courseware application controller class ApplicationController < ActionController::Base # CSRF protection protect_from_forgery # Abilities checking check_authorization # Setup locale before_filter :set_gettext_locale # Ask users to authenticate before_filter :require_login # Handle errors rescue_from CanCan::AccessDenied, :with => :unauthorized rescue_from ActiveRecord::RecordNotFound, :with => :not_found private # Sorcery method overwritten to customize error message def not_authenticated redirect_to(login_url, :alert => _('Please authenticate first.')) end # Unauthorized error handler def unauthorized redirect_to(root_url, :alert => _('Access to this page is not allowed.')) end # Not found handler def not_found render(:status => 404) end end
# Courseware application controller class ApplicationController < ActionController::Base # CSRF protection protect_from_forgery # Abilities checking check_authorization # Setup locale before_filter :set_gettext_locale # Ask users to authenticate before_filter :require_login # Handle errors rescue_from CanCan::AccessDenied, :with => :unauthorized rescue_from ActiveRecord::RecordNotFound, :with => :not_found private # Sorcery method overwritten to customize error message def not_authenticated redirect_to(login_url, :alert => _('Please authenticate first.')) end # Unauthorized error handler def unauthorized redirect_to(root_url, :alert => _('Access to this page is not allowed.')) end # Not found handler def not_found redirect_to('/404') end end
Create instance variables within the categories controller
class CategoriesController < ApplicationController def index end def new end end
class CategoriesController < ApplicationController def index @categories = Category.all end def new @category = Category.new end end
Update FreeSMUG Chromium to v40.0.2214.115
cask :v1 => 'freesmug-chromium' do version '40.0.2214.94' sha256 '404d93a048f86d500320c7d2a11b58bf8391aca190278036688c095fd8d183b2' # sourceforge.net is the official download host per the vendor homepage url "http://downloads.sourceforge.net/sourceforge/osxportableapps/Chromium_OSX_#{version}.dmg" appcast 'http://sourceforge.net/projects/osxportableapps/rss?path=/Chromium' homepage 'http://www.freesmug.org/chromium' license :gpl app 'Chromium.app' end
cask :v1 => 'freesmug-chromium' do version '40.0.2214.115' sha256 '00b40f4b903b2ea985e2d1dfd4f822fb23b6954b145c1ebe4cb8bde0d2a60260' # sourceforge.net is the official download host per the vendor homepage url "http://downloads.sourceforge.net/sourceforge/osxportableapps/Chromium_OSX_#{version}.dmg" appcast 'http://sourceforge.net/projects/osxportableapps/rss?path=/Chromium' homepage 'http://www.freesmug.org/chromium' license :gpl app 'Chromium.app' end
Refactor User specs for readability
require 'spec_helper' describe User do let(:user) { FactoryGirl.create(:user) } it 'has a valid factory' do user.should be_valid end it 'is invalid without email, or invalid email' do FactoryGirl.build(:user, email: nil).should_not be_valid FactoryGirl.build(:user, email: 'nil@').should_not be_valid end it 'is invalid without password' do FactoryGirl.build(:user, password: nil).should_not be_valid end it 'accept a blank password if the user exists' do user.password = '' user.should be_valid user.save.should be_true end it 'is invalid if the email exists' do new_user = FactoryGirl.build(:user, email: user.email) new_user.should_not be_valid new_user.should have(1).error_on(:email) end it "can't delete the last admin" do expect { user.destroy }.to raise_error 'Must be at least one admin' end end
require 'spec_helper' describe User do describe '#valid?' do subject { FactoryGirl.build(:user, params) } context 'default factory' do let(:params) { nil } it { should be_valid } end context 'without email' do let(:params) { {email: nil} } it { should_not be_valid } end context 'with invalid email' do let(:params) { {email: 'nil@'} } it { should_not be_valid } end context 'without password' do let(:params) { {password: nil} } it { should_not be_valid } end context 'is invalid if the email exists' do let(:params) { {password: nil} } let!(:existing_user) { FactoryGirl.create(:user, email: subject.email) } it { should_not be_valid } it { should have(1).error_on(:email) } end end describe '#save' do subject { FactoryGirl.create(:user) } context 'accept a blank password if the user exists' do before { subject.password = '' } it { should be_valid } it { expect(subject.save).to be_true } end end describe '#destroy' do subject { FactoryGirl.create(:user) } context "can't delete the last admin" do it { expect { subject.destroy }.to raise_error 'Must be at least one admin' } end end end
Write tests for validating Prime behavior
require_relative '../lib/prime.rb' describe Prime do it 'checks if a number is prime' it 'generates any number of primes' end
require_relative '../lib/prime.rb' describe Prime do it 'checks if a number is prime' do expect(Prime.valid?(10)).to eq(false) expect(Prime.valid?(49)).to eq(false) expect(Prime.valid?(101)).to eq(true) expect(Prime.valid?(29)).to eq(true) end it 'generates any number of primes' do expect(Prime.first(10)).to eq([2, 3, 5, 7, 11, 13, 17, 19, 23, 29]) expect(Prime.first(5)).to eq([2, 3, 5, 7, 11]) expect(Prime.first(20)).to eq([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]) end it 'generates 10 primes by default' do expect(Prime.first).to eq([2, 3, 5, 7, 11, 13, 17, 19, 23, 29]) end end
Store schema in an ivar
require 'logger' require 'rom/repository' require 'rom/sql/commands' module ROM module SQL class Repository < ROM::Repository attr_reader :logger def self.database_file?(scheme) scheme.to_s.include?('sqlite') end def initialize(uri, options = {}) @connection = ::Sequel.connect(uri.to_s, options) end def disconnect connection.disconnect end def [](name) connection[name] end def use_logger(logger) @logger = logger connection.loggers << logger end def schema connection.tables end def dataset(table) connection[table] end def dataset?(name) schema.include?(name) end def extend_relation_class(klass) klass.send(:include, RelationInclusion) end def extend_relation_instance(relation) model = relation.model model.set_dataset(relation.dataset) model.dataset.naked! end def command_namespace SQL::Commands end end end end
require 'logger' require 'rom/repository' require 'rom/sql/commands' module ROM module SQL class Repository < ROM::Repository attr_reader :logger, :schema def self.database_file?(scheme) scheme.to_s.include?('sqlite') end def initialize(uri, options = {}) @connection = ::Sequel.connect(uri.to_s, options) @schema = connection.tables end def disconnect connection.disconnect end def [](name) connection[name] end def use_logger(logger) @logger = logger connection.loggers << logger end def dataset(table) connection[table] end def dataset?(name) schema.include?(name) end def extend_relation_class(klass) klass.send(:include, RelationInclusion) end def extend_relation_instance(relation) model = relation.model model.set_dataset(relation.dataset) model.dataset.naked! end def command_namespace SQL::Commands end end end end
Update copy for MHRA email alerts
class EmailSignupPagesFinder def self.find(organisation) case organisation.slug when "medicines-and-healthcare-products-regulatory-agency" mhra_email_signup_pages end end def self.mhra_email_signup_pages [ OpenStruct.new( text: "Safety alerts", url: "/drug-device-alerts/email-signup", description: "Drug alerts and medical device alerts published by the MHRA.", ), OpenStruct.new( text: "Drug safety updates", url: "/drug-safety-update/email-signup", description: "The drug safety update is a monthly newsletter for healthcare professionals, bringing you information and clinical advice on the safe use of medicines.", ), OpenStruct.new( text: "News and publications from the MHRA", url: "/government/email-signup/new?email_signup%5Bfeed%5D=https%3A%2F%2Fwww.gov.uk%2Fgovernment%2Forganisations%2Fmedicines-and-healthcare-products-regulatory-agency.atom", description: "Information published by the MHRA about policies, announcements, publications, statistics and consultations.", ), ] end end
class EmailSignupPagesFinder def self.find(organisation) case organisation.slug when "medicines-and-healthcare-products-regulatory-agency" mhra_email_signup_pages end end def self.mhra_email_signup_pages [ OpenStruct.new( text: "Drug alerts and medical device alerts", description: "Subscribe to <a href='/drug-device-alerts/email-signup'>MHRA's alerts and recalls for drugs and medical devices</a>.".html_safe, ), OpenStruct.new( text: "Drug Safety Update", description: "Subscribe to the <a href='/drug-safety-update/email-signup'>Drug Safety Update</a>, the monthly newsletter for healthcare professionals, with clinical advice on the safe use of medicines.".html_safe, ), OpenStruct.new( text: "News and publications from the MHRA", description: "Subscribe to <a href='/government/email-signup/new?email_signup%5Bfeed%5D=https%3A%2F%2Fwww.gov.uk%2Fgovernment%2Forganisations%2Fmedicines-and-healthcare-products-regulatory-agency.atom'>MHRA's new publications, statistics, consultations and announcements</a>.".html_safe, ), ] end end
Fix redirect when Rails' `raise_on_open_redirect` is true
# frozen_string_literal: true module Spree module Admin class PostageLabelsController < Spree::Admin::BaseController def show @shipment = Spree::Shipment.find_by(number: params[:shipment_id]) authorize! @shipment, :show unless @shipment.easypost_postage_label_url flash[:error] = t('.no_postage_label', shipment_number: @shipment.number) redirect_back(fallback_location: edit_admin_order_path(@shipment.order)) return end redirect_to @shipment.easypost_postage_label_url end end end end
# frozen_string_literal: true module Spree module Admin class PostageLabelsController < Spree::Admin::BaseController def show @shipment = Spree::Shipment.find_by(number: params[:shipment_id]) authorize! @shipment, :show unless @shipment.easypost_postage_label_url flash[:error] = t('.no_postage_label', shipment_number: @shipment.number) redirect_back(fallback_location: edit_admin_order_path(@shipment.order)) return end redirect_to @shipment.easypost_postage_label_url, allow_other_host: true end end end end
Add title to allowed parameters
class Admin::PostsController < ApplicationController layout 'admin/layout' def create @post = Post.create(post_params[:post]) redirect_to admin_posts_path end def update @post = Post.find_by_slug(post_params[:id]) @post.update_attributes(post_params[:post]) redirect_to admin_posts_path end def index @posts = Post.all @post = Post.new end def show @post = Post.find(params[:id]) end def edit @post = Post.find(params[:id]) end def destroy @post = Post.find(params[:id]) @post.destroy redirect_to admin_posts_path end private def post_params params.permit(:id, post: [:author, :published, :published_at, :content]) end end
class Admin::PostsController < ApplicationController layout 'admin/layout' def create @post = Post.create(post_params[:post]) redirect_to admin_posts_path end def update @post = Post.find_by_slug(post_params[:id]) @post.update_attributes(post_params[:post]) redirect_to admin_posts_path end def index @posts = Post.all @post = Post.new end def show @post = Post.find(params[:id]) end def edit @post = Post.find(params[:id]) end def destroy @post = Post.find(params[:id]) @post.destroy redirect_to admin_posts_path end private def post_params params.permit(:id, post: [:title, :author, :published, :published_at, :content]) end end
Make the code a bit more readable
module Carto module BillingCycle def last_billing_cycle day = period_end_date.day rescue 29.days.ago.day # << operator substract 1 month from the date object date = (day > Date.today.day ? Date.today << 1 : Date.today) begin Date.parse("#{date.year}-#{date.month}-#{day}") rescue ArgumentError day = day - 1 retry end end end end
module Carto module BillingCycle def last_billing_cycle day = period_end_date.day rescue 29.days.ago.day date = (day > Date.today.day ? (Date.today - 1.month) : Date.today) begin Date.parse("#{date.year}-#{date.month}-#{day}") rescue ArgumentError day = day - 1 retry end end end end
Use map instead of each in extract_sources()
module ActionDispatch class ExceptionWrapper def extract_sources res = []; exception.backtrace.each do |trace| file, line, _ = trace.split(":") line_number = line.to_i res << { code: source_fragment(file, line_number), file: file, line_number: line_number } end res end end end
module ActionDispatch class ExceptionWrapper def extract_sources exception.backtrace.map do |trace| file, line, _ = trace.split(":") line_number = line.to_i { code: source_fragment(file, line_number), file: file, line_number: line_number } end end end end
Add some logging when catching these errors
# encoding: utf-8 require 'state_machine' module Punchblock class CommandNode < RayoNode def initialize(*args) super @response = FutureResource.new end state_machine :state, :initial => :new do event :request do transition :new => :requested end event :execute do transition :requested => :executing end event :complete do transition :executing => :complete end end def response(timeout = nil) @response.resource timeout end def response=(other) return if @response.set_yet? @response.resource = other execute! rescue FutureResource::ResourceAlreadySetException end end # CommandNode end # Punchblock
# encoding: utf-8 require 'state_machine' module Punchblock class CommandNode < RayoNode def initialize(*args) super @response = FutureResource.new end state_machine :state, :initial => :new do event :request do transition :new => :requested end event :execute do transition :requested => :executing end event :complete do transition :executing => :complete end end def response(timeout = nil) @response.resource timeout end def response=(other) return if @response.set_yet? @response.resource = other execute! rescue FutureResource::ResourceAlreadySetException pb_logger.warn "Rescuing a FutureResource::ResourceAlreadySetException!" pb_logger.warn "Here is some information about me: #{self.inspect}" end end # CommandNode end # Punchblock
Update the version of geoserver
# # 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. # default['geoserver']['user'] = nil default['geoserver']['group'] = nil #Hmmm ... 2.2.4 does not seem to work in glassfish? version = '2.1.4' #version = '2.3.1' default['geoserver']['version'] = version default['geoserver']['package_url'] = "http://downloads.sourceforge.net/geoserver/geoserver-#{version}-war.zip" default['geoserver']['base_dir'] = '/srv/geoserver' default['geoserver']['data_dir'] = '/srv/geoserver/data' default['geoserver']['git']['config_repository'] = nil default['geoserver']['git']['reference'] = 'master' default['geoserver']['glassfish']['domain'] = nil default['geoserver']['glassfish']['root'] = '/geoserver' default['geoserver']['users'] = Mash.new default['geoserver']['tomcat']['instance'] = nil default['geoserver']['tomcat']['root'] = '/geoserver'
# # 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. # default['geoserver']['user'] = nil default['geoserver']['group'] = nil version = '2.3.1' default['geoserver']['version'] = version default['geoserver']['package_url'] = "http://downloads.sourceforge.net/geoserver/geoserver-#{version}-war.zip" default['geoserver']['base_dir'] = '/srv/geoserver' default['geoserver']['data_dir'] = '/srv/geoserver/data' default['geoserver']['git']['config_repository'] = nil default['geoserver']['git']['reference'] = 'master' default['geoserver']['glassfish']['domain'] = nil default['geoserver']['glassfish']['root'] = '/geoserver' default['geoserver']['users'] = Mash.new default['geoserver']['tomcat']['instance'] = nil default['geoserver']['tomcat']['root'] = '/geoserver'
Fix idle hous average trello (oeprator precedence bug)w
ProviderRepo.find!(:trello).register_metric :idle_hours_average do |metric| metric.description = "Average time each card has been idle measured in hours" metric.title = "Card Average Age" metric.block = proc do |adapter, options| now_utc = Time.current.utc list_ids = Array(options[:list_ids]) cards = adapter.cards(list_ids) sum = cards.map do |card| now_utc - card.last_activity_date / 1.hour end.sum value = sum.zero? ? sum : sum / cards.count Datapoint.new value: value.to_i end metric.configuration = proc do |client, params| list_ids = Array(params["list_ids"]) [ [:list_ids, select_tag("goal[params][list_ids]", options_for_select(client.list_options, selected: list_ids), multiple: true, class: "form-control")] ] end end
ProviderRepo.find!(:trello).register_metric :idle_hours_average do |metric| metric.description = "Average time each card has been idle measured in hours" metric.title = "Card average age" metric.block = proc do |adapter, options| now_utc = Time.current.utc list_ids = Array(options[:list_ids]) cards = adapter.cards(list_ids) sum = cards.map do |card| (now_utc - card.last_activity_date) / 1.hour end.sum value = sum.zero? ? sum : sum / cards.count Datapoint.new value: value.to_i end metric.configuration = proc do |client, params| list_ids = Array(params["list_ids"]) [ [:list_ids, select_tag("goal[params][list_ids]", options_for_select(client.list_options, selected: list_ids), multiple: true, class: "form-control")] ] end end
Add expected East 2017 date
# -*- encoding: utf-8 -*- module Cinch module Plugins # Versioning info class PaxTimer PAXES = [ { type: 'aus', name: 'PAX Australia', date: Time.parse('2016-11-04 08:00:00 +11:00'), estimated: false }, { type: 'prime', name: 'PAX West', date: Time.parse('2016-09-02 08:00:00 -08:00'), estimated: false }, { type: 'west', name: 'PAX West', date: Time.parse('2016-09-02 08:00:00 -08:00'), estimated: false }, { type: 'south', name: 'PAX South', date: Time.parse('2017-01-29 08:00:00 -06:00'), estimated: true }, { type: 'east', name: 'PAX East', date: Time.parse('2016-04-22 08:00:00 -05:00'), estimated: false } ] end end end
# -*- encoding: utf-8 -*- module Cinch module Plugins # Versioning info class PaxTimer PAXES = [ { type: 'aus', name: 'PAX Australia', date: Time.parse('2016-11-04 08:00:00 +11:00'), estimated: false }, { type: 'prime', name: 'PAX West', date: Time.parse('2016-09-02 08:00:00 -08:00'), estimated: false }, { type: 'west', name: 'PAX West', date: Time.parse('2016-09-02 08:00:00 -08:00'), estimated: false }, { type: 'south', name: 'PAX South', date: Time.parse('2017-01-29 08:00:00 -06:00'), estimated: true }, { type: 'east', name: 'PAX East', date: Time.parse('2017-03-10 08:00:00 -05:00'), estimated: true } ] end end end
Fix typo in untested code
class ArticleCategoriesController < ApplicationController def show @article_category = ArticleCategory.find(params[:id]) @article_category.articles.delete_if { |article| !article.display? } top_level_article_category_id = @article_category.parent_id top_level_article_category_id = params[:id] if top_level_article_category_id == 0 @article_categories = ArticleCategorywhere(:parent_id => top_level_article_category_id).order(:position) @article_categories.each { |article_category| article_category.articles.delete_if { |article| !article.display? }} end end
class ArticleCategoriesController < ApplicationController def show @article_category = ArticleCategory.find(params[:id]) @article_category.articles.delete_if { |article| !article.display? } top_level_article_category_id = @article_category.parent_id top_level_article_category_id = params[:id] if top_level_article_category_id == 0 @article_categories = ArticleCategory.where(:parent_id => top_level_article_category_id).order(:position) @article_categories.each { |article_category| article_category.articles.delete_if { |article| !article.display? }} end end
Add a scaler for the new Cedar stack.
require 'heroku' module Delayed module Workless module Scaler class HerokuCedar < Base require "heroku" def up client.ps_scale(ENV['APP_NAME'], type: 'worker', qty: 1) if workers == 0 end def down client.ps_scale(ENV['APP_NAME'], type: 'worker', qty: 0) unless workers == 0 or jobs.count > 0 end def workers client.ps(ENV['APP_NAME']).count { |p| p["process"] =~ /worker\.\d?/ } end private def client @client ||= ::Heroku::Client.new(ENV['HEROKU_USER'], ENV['HEROKU_PASSWORD']) end end end end end
Use more performant find instead of scope and 404 if record invalid
class API::DrawingsController < ApplicationController include Roar::Rails::ControllerAdditions respond_to :hal before_action :restrict_access! def index drawings = Drawing.complete_with_consent.desc.page params[:page] respond_with drawings, represent_with: DrawingCollectionRepresenter end def show # annoying bug with obfuscate_id, need to deobfuscate if using find with scopes deobs_id = Drawing.deobfuscate_id(params[:id]) drawing = Drawing.complete_with_consent.find(deobs_id).decorate respond_with drawing, represent_with: DrawingRepresenter end private def restrict_access! authenticate_or_request_with_http_token do |token, _| APIKey.exists?(access_token: token) end end end
class API::DrawingsController < ApplicationController include Roar::Rails::ControllerAdditions respond_to :hal before_action :restrict_access! def index drawings = Drawing.complete_with_consent.desc.page params[:page] respond_with drawings, represent_with: DrawingCollectionRepresenter end def show if (drawing = Drawing.find(params[:id])) && drawing.complete? && drawing.image_consent respond_with drawing.decorate, represent_with: DrawingRepresenter else render json: { error: 'Not found' }, status: :not_found end end private def restrict_access! authenticate_or_request_with_http_token do |token, _| APIKey.exists?(access_token: token) end end end
Add link helper for linking articles
include Nanoc::Helpers::LinkTo module LinkHelpers # # get link for the category # def link_category name "<a href='/categories/#{name}'>#{name}</a>" end # # get links for the categories # def link_categories cs cs.map { |c| "<a href='/categories/#{c}'>#{c}</a>" } end end include LinkHelpers
include Nanoc::Helpers::LinkTo module LinkHelpers # # get link for the category # def link_category name "<a href='/categories/#{name}'>#{name}</a>" end # # get links for the categories # def link_categories cs cs.map { |c| "<a href='/categories/#{c}'>#{c}</a>" } end # # link an article # def link_article name link_to name, "/articles/#{name.downcase.gsub(" ", "_")}" end end include LinkHelpers
Add sqlite3 as test db
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'settings_on_rails/version' Gem::Specification.new do |spec| spec.name = 'settings_on_rails' spec.version = SettingsOnRails::VERSION spec.authors = ['ALLEN WANG QIANG'] spec.email = ['qwang@comp.nus.edu.sg'] spec.summary = %q{Handle Model specific Settings for Rails.} spec.description = %q{Ruby Gem help to handle model specific settings for ActiveRecord, settings are stored as hashes. Supports multiple keys and default values.} spec.homepage = 'https://github.com/allenwq/settings_on_rails' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.required_ruby_version = '>= 1.9' spec.add_dependency 'activerecord', '>= 3.1' spec.add_development_dependency 'bundler' spec.add_development_dependency 'rake' spec.add_development_dependency 'rspec', '~> 3' end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'settings_on_rails/version' Gem::Specification.new do |spec| spec.name = 'settings_on_rails' spec.version = SettingsOnRails::VERSION spec.authors = ['ALLEN WANG QIANG'] spec.email = ['qwang@comp.nus.edu.sg'] spec.summary = %q{Handle Model specific Settings for Rails.} spec.description = %q{Ruby Gem help to handle model specific settings for ActiveRecord, settings are stored as hashes. Supports multiple keys and default values.} spec.homepage = 'https://github.com/allenwq/settings_on_rails' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.required_ruby_version = '>= 1.9' spec.add_dependency 'activerecord', '>= 3.1' spec.add_development_dependency 'sqlite3', '~> 1.3' spec.add_development_dependency 'bundler', '~> 1.6' spec.add_development_dependency 'rspec', '~> 3' spec.add_development_dependency 'rake', '~> 10' end
Add external id to lottery entrant parameters
# frozen_string_literal: true class LotteryEntrantParameters < BaseParameters def self.csv_export_attributes %w[ division_name first_name last_name gender birthdate city state country number_of_tickets ] end def self.mapping lottery_entrant_mapping = { tickets: :number_of_tickets, "#_of_tickets": :number_of_tickets, "#_tickets": :number_of_tickets } ::EffortParameters.mapping.merge(lottery_entrant_mapping) end def self.permitted [ :birthdate, :city, :country_code, :division, :first_name, :gender, :id, :last_name, :lottery_division_id, :number_of_tickets, :pre_selected, :state_code ] end end
# frozen_string_literal: true class LotteryEntrantParameters < BaseParameters def self.csv_export_attributes %w[ division_name first_name last_name gender birthdate city state country number_of_tickets pre_selected external_id ] end def self.mapping lottery_entrant_mapping = { tickets: :number_of_tickets, "#_of_tickets": :number_of_tickets, "#_tickets": :number_of_tickets } ::EffortParameters.mapping.merge(lottery_entrant_mapping) end def self.permitted [ :birthdate, :city, :country_code, :division, :external_id, :first_name, :gender, :id, :last_name, :lottery_division_id, :number_of_tickets, :pre_selected, :state_code ] end end
Mark everything as html_safe for now so we can use express templates within haml layouts
module ExpressTemplates module Template class Handler def self.call(template) new.call(template) end def call(template) # returns a string to be eval'd ExpressTemplates.compile(template) end end end end
module ExpressTemplates module Template class Handler def self.call(template) new.call(template) end def call(template) # returns a string to be eval'd "(#{ExpressTemplates.compile(template)}).html_safe" end end end end
Use RubyGettextExtractor for Haml files
require 'gettext/utils' begin require 'gettext/tools/rgettext' rescue LoadError #version prior to 2.0 require 'gettext/rgettext' end module GettextI18nRails module HamlParser module_function def target?(file) File.extname(file) == '.haml' end def parse(file, msgids = []) return msgids unless load_haml require 'gettext_i18n_rails/ruby_gettext_extractor' text = IO.readlines(file).join #first pass with real haml haml = Haml::Engine.new(text) code = haml.precompiled.split(/$/) GetText::RubyParser.parse_lines(file, code, msgids) end def load_haml return true if @haml_loaded begin require "#{RAILS_ROOT}/vendor/plugins/haml/lib/haml" rescue LoadError begin require 'haml' # From gem rescue LoadError puts "A haml file was found, but haml library could not be found, so nothing will be parsed..." return false end end @haml_loaded = true end end end GetText::RGetText.add_parser(GettextI18nRails::HamlParser)
require 'gettext/utils' begin require 'gettext/tools/rgettext' rescue LoadError #version prior to 2.0 require 'gettext/rgettext' end module GettextI18nRails module HamlParser module_function def target?(file) File.extname(file) == '.haml' end def parse(file, msgids = []) return msgids unless load_haml require 'gettext_i18n_rails/ruby_gettext_extractor' text = IO.readlines(file).join haml = Haml::Engine.new(text) code = haml.precompiled return RubyGettextExtractor.parse_string(code, file, msgids) end def load_haml return true if @haml_loaded begin require "#{RAILS_ROOT}/vendor/plugins/haml/lib/haml" rescue LoadError begin require 'haml' # From gem rescue LoadError puts "A haml file was found, but haml library could not be found, so nothing will be parsed..." return false end end @haml_loaded = true end end end GetText::RGetText.add_parser(GettextI18nRails::HamlParser)
Use rspec instead of rake because rubocop will fail for sure
require "spec_helper" RSpec.describe "Suspend a new project with --api flag" do before(:all) do drop_dummy_database remove_project_directory end it "ensures project specs pass" do run_suspenders("--api") Dir.chdir(project_path) do Bundler.with_clean_env do expect(`rake`).to include("0 failures") end end end end
require "spec_helper" RSpec.describe "Suspend a new project with --api flag" do before(:all) do drop_dummy_database remove_project_directory end it "ensures project specs pass" do run_suspenders("--api") Dir.chdir(project_path) do Bundler.with_clean_env do expect(`rspec spec/`).to include("0 failures") end end end end
Switch to before_filter to before_action
require_dependency 'dre/application_controller' module Dre class DevicesController < ApplicationController before_filter :authenticate! respond_to :json def index render json: { devices: collection } end def register @device = collection.where(token: params[:token]).first || Device.new(owner: user, token: params[:token]) @device.platform = detect_platform response = @device.persisted? ? 200 : 201 if @device.save render json: { device: @device }, root: false, status: response else render json: { errors: @device.errors }, status: :unprocessable_entity end end def deregister @device = collection.where(token: params[:token]).first if @device.nil? render nothing: true, status: :not_found elsif @device.destroy render nothing: true, status: :ok else render json: { errors: @device.errors }, status: :unprocessable_entity end end private def authenticate! method(Dre.authentication_method).call end def user @user ||= method(Dre.current_user_method).call end def collection @devices ||= Device.for_owner(user).limit(30) end end end
require_dependency 'dre/application_controller' module Dre class DevicesController < ApplicationController before_action :authenticate! respond_to :json def index render json: { devices: collection } end def register @device = collection.where(token: params[:token]).first || Device.new(owner: user, token: params[:token]) @device.platform = detect_platform response = @device.persisted? ? 200 : 201 if @device.save render json: { device: @device }, root: false, status: response else render json: { errors: @device.errors }, status: :unprocessable_entity end end def deregister @device = collection.where(token: params[:token]).first if @device.nil? render nothing: true, status: :not_found elsif @device.destroy render nothing: true, status: :ok else render json: { errors: @device.errors }, status: :unprocessable_entity end end private def authenticate! method(Dre.authentication_method).call end def user @user ||= method(Dre.current_user_method).call end def collection @devices ||= Device.for_owner(user).limit(30) end end end
Add some defaults to the git tag middleware
class Git::Deploy::GitTag include Git::Deploy::Shell def self.configure( opts ) opts.on :T, :tag, 'Tag the deployment.' end def initialize( app, options ) @app, @options = app, options end def call( env ) if env[ 'options.tag' ] now = DateTime.now tag = now.strftime @options[ :tagname ] msg = now.strftime @options[ :message ] sh 'git tag "%s" -m "%s"' % [ tag, msg ] sh 'git push origin --tags' end @app.call env end end
class Git::Deploy::GitTag include Git::Deploy::Shell def self.configure( opts ) opts.on :T, :tag, 'Tag the deployment.' end def initialize( app, options ) @app, @options = app, options # "2013-04-12.1132AM" @options[ :tagname ] ||= '%F.%I%M%p' # "Release: Friday, April 12, 2013 11:35:12 AM PDT" @options[ :message ] ||= 'Release: %A, %B %d, %Y %r %Z' end def call( env ) if env[ 'options.tag' ] now = DateTime.now tag = now.strftime @options[ :tagname ] msg = now.strftime @options[ :message ] sh 'git tag "%s" -m "%s"' % [ tag, msg ] sh 'git push origin --tags' end @app.call env end end
Add condition to extra image generation to only operate on 'files' returned by the glob
module Jekyll module ResponsiveImage class ExtraImageGenerator < Jekyll::Generator include Jekyll::ResponsiveImage::Utils def generate(site) config = Config.new(site).to_h site_source = Pathname.new(site.source) config['extra_images'].each do |pathspec| Dir.glob(site.in_source_dir(pathspec)) do |image_path| path = Pathname.new(image_path) relative_image_path = path.relative_path_from(site_source) result = ImageProcessor.process(relative_image_path, config) result[:resized].each { |image| keep_resized_image!(site, image) } end end end end end end
module Jekyll module ResponsiveImage class ExtraImageGenerator < Jekyll::Generator include Jekyll::ResponsiveImage::Utils include FileTest def generate(site) config = Config.new(site).to_h site_source = Pathname.new(site.source) config['extra_images'].each do |pathspec| Dir.glob(site.in_source_dir(pathspec)) do |image_path| if FileTest.file?(image_path) path = Pathname.new(image_path) relative_image_path = path.relative_path_from(site_source) result = ImageProcessor.process(relative_image_path, config) result[:resized].each { |image| keep_resized_image!(site, image) } end end end end end end end
Allow Serivce::HttpPost to be registered
class Service::HttpPost < Service Service.services.delete(self) include HttpHelper alias receive_event deliver def receive_event deliver data['url'], :content_type => data['content_type'], :insecure_ssl => data['insecure_ssl'].to_i == 1, :secret => data['secret'] end def original_body {:payload => payload, :event => event.to_s, :config => data, :guid => delivery_guid} end end
class Service::HttpPost < Service include HttpHelper alias receive_event deliver def receive_event deliver data['url'], :content_type => data['content_type'], :insecure_ssl => data['insecure_ssl'].to_i == 1, :secret => data['secret'] end def original_body {:payload => payload, :event => event.to_s, :config => data, :guid => delivery_guid} end end