Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Update HandbrakeCLI Nightly to v6605svn
cask :v1 => 'handbrakecli-nightly' do version '6592svn' sha256 '582143d519f51c44b4722583122fdc52ad35e1a24aa4a42e4569da2df06b04ae' url "http://download.handbrake.fr/nightly/HandBrake-#{version}-MacOSX.6_CLI_x86_64.dmg" homepage 'http://handbrake.fr' license :gpl binary 'HandBrakeCLI' end
cask :v1 => 'handbrakecli-nightly' do version '6605svn' sha256 '0c4da5c55355c5f6b8d59caa8a01bcfd5c06721b83a1bb9e09b7123c32aabdbb' url "http://download.handbrake.fr/nightly/HandBrake-#{version}-MacOSX.6_CLI_x86_64.dmg" homepage 'http://handbrake.fr' license :gpl binary 'HandBrakeCLI' end
Add cask for Battery Time Remaining
class BatteryTimeRemaining < Cask url 'http://yap.nu/battery-time-remaining/download/Battery%20Time%20Remaining%202-2.0.2.zip' homepage 'http://yap.nu/battery-time-remaining/' version '2.0.2' sha1 '351b0dd2c1251681cc5a0fcf8c0af784393e98d3' link 'Battery Time Remaining 2.app' end
Add spec for text reply
require 'spec_helper' describe TextReply do subject(:text_reply) { TextReply.new("aren't tacos great?") } describe '#body' do it 'returns a twilio sms response' do expect(text_reply.body).to match_xpath('Response/Sms') end it 'responds with the text' do node = Nokogiri::XML::Document.parse(text_reply.body).xpath('Response/Sms') expect(node.text).to eq("aren't tacos great?") end end end
Upgrade Rubymine EAP to v140.2694
cask :v1 => 'rubymine-eap' do version '139.262' sha256 'e255b6a0f94fee55e72c9969919619c3431bf6507e678e0ac9303edc0d441072' url "http://download.jetbrains.com/ruby/RubyMine-#{version}.dmg" homepage 'http://confluence.jetbrains.com/display/RUBYDEV/RubyMine+EAP' license :unknown app 'RubyMine.app' end
cask :v1 => 'rubymine-eap' do version '140.2694' sha256 '7376d5b04b49e503c203a2b1c9034a690835ea601847753710f3c8ec53566ebb' url "http://download.jetbrains.com/ruby/RubyMine-#{version}.dmg" homepage 'http://confluence.jetbrains.com/display/RUBYDEV/RubyMine+EAP' license :unknown app 'RubyMine EAP.app' end
Use equalizer for the test model (should make it pass on rbx)
require 'spec_helper' require 'ostruct' describe Mapper do subject(:mapper) { Mapper.new(relation, user_model) } let(:relation) { Relation.new(DB[:users]) } let(:user_model) { OpenStruct } let(:jane) { user_model.new(id: 1, name: 'Jane') } let(:joe) { user_model.new(id: 2, name: 'Joe') } describe "#each" do it "yields all mapped objects" do result = [] mapper.each do |user| result << user end expect(result).to eql([jane, joe]) end end end
require 'spec_helper' require 'ostruct' describe Mapper do subject(:mapper) { Mapper.new(relation, user_model) } let(:relation) { Relation.new(DB[:users]) } let(:user_model) { Class.new(OpenStruct) { include Equalizer.new(:id, :name) } } let(:jane) { user_model.new(id: 1, name: 'Jane') } let(:joe) { user_model.new(id: 2, name: 'Joe') } describe "#each" do it "yields all mapped objects" do result = [] mapper.each do |user| result << user end expect(result).to eql([jane, joe]) end end end
Add SponsorType model spec using factory. - nikita
require 'rails_helper' describe SponsorType, type: :model do pending "add some examples to (or delete) #{__FILE__}" end
require 'rails_helper' describe SponsorType, type: :model do let(:sponsor_type) { FactoryGirl.build_stubbed(:sponsor_type) } subject { sponsor_type } it { should be_valid } describe 'validations' do context 'when name is missing' do before { sponsor_type.name = '' } it { should_not be_valid } end context 'when code is missing' do before { sponsor_type.code = '' } it { should_not be_valid } end context 'when name is not unique' do before { FactoryGirl.create(:sponsor_type, name: sponsor_type.name) } it { should_not be_valid } end context 'when code is not unique' do before { FactoryGirl.create(:sponsor_type, code: sponsor_type.code) } it { should_not be_valid } end end end
Add a TODO for passing command line switches to Chrome.
module Selenium module WebDriver module Chrome # @api private class Bridge < Remote::Bridge def initialize(opts = {}) # TODO: pass options to Chrome::Service http_client = opts.delete(:http_client) unless opts.empty? raise ArgumentError, "unknown option#{'s' if opts.size != 1}: #{opts.inspect}" end @service = Service.default_service @service.start remote_opts = { :url => @service.uri, :desired_capabilities => :chrome } remote_opts.merge!(:http_client => http_client) if http_client super(remote_opts) end def browser :chrome end def driver_extensions [] end def capabilities @capabilities ||= Remote::Capabilities.chrome end def quit super ensure @service.stop end end # Bridge end # Chrome end # WebDriver end # Selenium
module Selenium module WebDriver module Chrome # @api private class Bridge < Remote::Bridge def initialize(opts = {}) http_client = opts.delete(:http_client) unless opts.empty? raise ArgumentError, "unknown option#{'s' if opts.size != 1}: #{opts.inspect}" end @service = Service.default_service @service.start # TODO: chrome command line switches when it's supported # in the released server # # http://peter.sh/experiments/chromium-command-line-switches/ # # { # :chrome => { # :customSwitches => { # "--disable-translate" => "" # } # } # } remote_opts = { :url => @service.uri, :desired_capabilities => :chrome } remote_opts.merge!(:http_client => http_client) if http_client super(remote_opts) end def browser :chrome end def driver_extensions [] end def capabilities @capabilities ||= Remote::Capabilities.chrome end def quit super ensure @service.stop end end # Bridge end # Chrome end # WebDriver end # Selenium
Switch to constants for direction.
module HTTParty module Logger class CurlLogger #:nodoc: TAG_NAME = HTTParty.name attr_accessor :level, :logger, :current_time def initialize(logger, level) @logger = logger @level = level.to_sym end def format(request, response) messages = [] time = Time.now.strftime("%Y-%m-%d %H:%M:%S %z") http_method = request.http_method.name.split("::").last.upcase path = request.path.to_s messages << print(time, ">", "#{http_method} #{path}") if request.options[:headers] && request.options[:headers].size > 0 request.options[:headers].each do |k, v| messages << print(time, ">", "#{k}: #{v}") end end messages << print(time, ">", request.raw_body) messages << print(time, ">", "") messages << print(time, "<", "HTTP/#{response.http_version} #{response.code}") headers = response.respond_to?(:headers) ? response.headers : response response.each_header do |response_header| messages << print(time, "<", "#{response_header.capitalize}: #{headers[response_header]}") end messages << print(time, "<", "\n#{response.body}") @logger.send @level, messages.join("\n") end def print(time, direction, line) "[#{TAG_NAME}] [#{time}] #{direction} #{line}" end end end end
module HTTParty module Logger class CurlLogger #:nodoc: TAG_NAME = HTTParty.name OUT = ">" IN = "<" attr_accessor :level, :logger, :current_time def initialize(logger, level) @logger = logger @level = level.to_sym end def format(request, response) messages = [] time = Time.now.strftime("%Y-%m-%d %H:%M:%S %z") http_method = request.http_method.name.split("::").last.upcase path = request.path.to_s messages << print(time, OUT, "#{http_method} #{path}") if request.options[:headers] && request.options[:headers].size > 0 request.options[:headers].each do |k, v| messages << print(time, OUT, "#{k}: #{v}") end end messages << print(time, OUT, request.raw_body) messages << print(time, OUT, "") messages << print(time, IN, "HTTP/#{response.http_version} #{response.code}") headers = response.respond_to?(:headers) ? response.headers : response response.each_header do |response_header| messages << print(time, IN, "#{response_header.capitalize}: #{headers[response_header]}") end messages << print(time, IN, "\n#{response.body}") @logger.send @level, messages.join("\n") end def print(time, direction, line) "[#{TAG_NAME}] [#{time}] #{direction} #{line}" end end end end
Add my email address since at least it's valid
require 'date' Gem::Specification.new do |s| s.name = %q{rmagick} s.version = "2.13.3.rc1" s.date = Date.today.to_s s.summary = %q{Ruby binding to ImageMagick} s.description = %q{RMagick is an interface between Ruby and ImageMagick.} s.authors = [%q{Tim Hunter}, %q{Omer Bar-or}, %q{Benjamin Thomas}, %q{Moncef Maiza}] s.post_install_message = "Please report any bugs. This bugfix release may contain bugs. See https://github.com/gemhome/rmagick/compare/RMagick_2-13-2...master and https://github.com/rmagick/rmagick/issues/18" s.email = %q{rmagick@rubyforge.org} s.homepage = %q{https://github.com/gemhome/rmagick} s.license = 'MIT' s.files = Dir.glob('**/*') s.bindir = 'bin' s.executables = Dir.glob('bin/*').collect {|f| File.basename(f)} s.require_paths << 'ext' s.rubyforge_project = %q{rmagick} s.extensions = %w{ext/RMagick/extconf.rb} s.has_rdoc = false s.required_ruby_version = '>= 1.8.5' s.requirements << 'ImageMagick 6.4.9 or later' end
require 'date' Gem::Specification.new do |s| s.name = %q{rmagick} s.version = "2.13.3.rc1" s.date = Date.today.to_s s.summary = %q{Ruby binding to ImageMagick} s.description = %q{RMagick is an interface between Ruby and ImageMagick.} s.authors = [%q{Tim Hunter}, %q{Omer Bar-or}, %q{Benjamin Thomas}, %q{Moncef Maiza}] s.post_install_message = "Please report any bugs. This bugfix release may contain bugs. See https://github.com/gemhome/rmagick/compare/RMagick_2-13-2...master and https://github.com/rmagick/rmagick/issues/18" s.email = %q{github@benjaminfleischer.com} s.homepage = %q{https://github.com/gemhome/rmagick} s.license = 'MIT' s.files = Dir.glob('**/*') s.bindir = 'bin' s.executables = Dir.glob('bin/*').collect {|f| File.basename(f)} s.require_paths << 'ext' s.rubyforge_project = %q{rmagick} s.extensions = %w{ext/RMagick/extconf.rb} s.has_rdoc = false s.required_ruby_version = '>= 1.8.5' s.requirements << 'ImageMagick 6.4.9 or later' end
Add a reader for bot_is_owner
require 'discordrb/data' module Discordrb::Light # Represents the bot account used for the light bot, but without any methods to change anything. class LightProfile include Discordrb::IDObject include Discordrb::UserAttributes # @!visibility private def initialize(data, bot) @bot = bot @username = data['username'] @id = data['id'].to_i @discriminator = data['discriminator'] @avatar_id = data['avatar'] @bot_account = false @bot_account = true if data['bot'] @verified = data['verified'] @email = data['email'] end end # Represents a light server which only has a fraction of the properties of any other server. class LightServer include Discordrb::IDObject include Discordrb::ServerAttributes # @!visibility private def initialize(data, bot) @bot = bot @id = data['id'].to_i @name = data['name'] @icon_id = data['icon'] @bot_is_owner = data['owner'] @bot_permissions = Discordrb::Permissions.new(data['permissions']) end end end
require 'discordrb/data' module Discordrb::Light # Represents the bot account used for the light bot, but without any methods to change anything. class LightProfile include Discordrb::IDObject include Discordrb::UserAttributes # @!visibility private def initialize(data, bot) @bot = bot @username = data['username'] @id = data['id'].to_i @discriminator = data['discriminator'] @avatar_id = data['avatar'] @bot_account = false @bot_account = true if data['bot'] @verified = data['verified'] @email = data['email'] end end # Represents a light server which only has a fraction of the properties of any other server. class LightServer include Discordrb::IDObject include Discordrb::ServerAttributes attr_reader :bot_is_owner alias_method :bot_is_owner?, :bot_is_owner # @!visibility private def initialize(data, bot) @bot = bot @id = data['id'].to_i @name = data['name'] @icon_id = data['icon'] @bot_is_owner = data['owner'] @bot_permissions = Discordrb::Permissions.new(data['permissions']) end end end
Add All The GIFs v1.0
class AllTheGifs < Cask version 'latest' sha256 :no_check url 'https://raw.github.com/orta/GIFs/master/web/GIFs.app.zip' homepage 'https://github.com/orta/GIFs' link 'All The GIFs.app' end
Rename `github` instance variable in Cli
# encoding: utf-8 module Rbk class Cli def self.run(argv=ARGV, options={}) new(argv, options).setup.run end def initialize(argv, options={}) @argv = argv @options = options @git = @options[:git] || Git @github = @options[:github_repos] || Github::Repos end def setup @config = Configuration.create(@argv) @shell = @options[:shell] || Shell.new(@config.quiet?) @archiver = Archiver.new(@shell) @s3 = @options[:s3] || AWS::S3.new(@config.aws_credentials) @uploader = Uploader.new(@s3.buckets[@config.bucket], @shell) self end def run if @config.help? @shell.puts(@config.usage) else Backup.new(repos, git, archiver, uploader, shell).run end end private attr_reader :git, :archiver, :uploader, :shell def repos @repos ||= begin r = @github.new(oauth_token: @config.github_access_token) r.list(org: @config.organization, auto_pagination: true) end end class Archiver def initialize(shell=Shell.new) @shell = shell end def create(path) archive = %(#{path}.tar.gz) @shell.exec(%(tar czf #{archive} #{path})) archive end end end end
# encoding: utf-8 module Rbk class Cli def self.run(argv=ARGV, options={}) new(argv, options).setup.run end def initialize(argv, options={}) @argv = argv @options = options @git = @options[:git] || Git @github_repos = @options[:github_repos] || Github::Repos end def setup @config = Configuration.create(@argv) @shell = @options[:shell] || Shell.new(@config.quiet?) @archiver = Archiver.new(@shell) @s3 = @options[:s3] || AWS::S3.new(@config.aws_credentials) @uploader = Uploader.new(@s3.buckets[@config.bucket], @shell) self end def run if @config.help? @shell.puts(@config.usage) else Backup.new(repos, git, archiver, uploader, shell).run end end private attr_reader :git, :archiver, :uploader, :shell def repos @repos ||= begin r = @github_repos.new(oauth_token: @config.github_access_token) r.list(org: @config.organization, auto_pagination: true) end end class Archiver def initialize(shell=Shell.new) @shell = shell end def create(path) archive = %(#{path}.tar.gz) @shell.exec(%(tar czf #{archive} #{path})) archive end end end end
Add spec coverage for rbenv_plugin resource.
require "chef/resource/lwrp_base" unless Chef::Resource.const_defined?("RbenvPlugin") Chef::Resource::LWRPBase.build_from_file( "rbenv", File.join(File.dirname(__FILE__), %w{.. .. .. resources plugin.rb}), nil ) end describe Chef::Resource::RbenvPlugin do let(:resource) { described_class.new("rbenv-goodies") } it "sets the default attribute to name" do expect(resource.name).to eq("rbenv-goodies") end it "attribute git_url defaults to nil" do expect(resource.git_url).to be_nil end it "attribute git_url takes a String value" do resource.git_url("https://example.com/rbenv-goodies.git") expect(resource.git_url).to eq("https://example.com/rbenv-goodies.git") end it "attribute git_ref defaults to nil" do expect(resource.git_ref).to be_nil end it "attribute git_ref takes a String value" do resource.git_ref("abc123") expect(resource.git_ref).to eq("abc123") end it "attribute user defaults to nil" do expect(resource.user).to be_nil end it "attribute user takes a String value" do resource.user("abed") expect(resource.user).to eq("abed") end it "attribute root_path defaults to nil" do expect(resource.root_path).to be_nil end it "attribute root_path takes a String value" do resource.root_path("/tmp/root") expect(resource.root_path).to eq("/tmp/root") end it "action defaults to :install" do expect(resource.action).to eq(:install) end it "#to_s includes user if provided" do resource.user("molly") expect(resource.to_s).to eq("rbenv_plugin[rbenv-goodies] (molly)") end it "#to_s includes system label if user is not provided" do expect(resource.to_s).to eq("rbenv_plugin[rbenv-goodies] (system)") end end
Update Docker Toolbox to 1.9.0c
cask :v1_1 => 'dockertoolbox' do version '1.9.0b' sha256 'dc8c2df85154e0604aca331dda5b6a0711d79f7f7fcd8df0a92bd712bf704811' url "https://github.com/docker/toolbox/releases/download/v#{version}/DockerToolbox-#{version}.pkg" appcast 'https://github.com/docker/toolbox/releases.atom' name 'Docker Toolbox' homepage 'https://www.docker.com/toolbox' license :apache pkg "DockerToolbox-#{version}.pkg" postflight do set_ownership '~/.docker' end uninstall :pkgutil => [ 'io.boot2dockeriso.pkg.boot2dockeriso', 'io.docker.pkg.docker', 'io.docker.pkg.dockercompose', 'io.docker.pkg.dockermachine', 'io.docker.pkg.dockerquickstartterminalapp', 'io.docker.pkg.kitematicapp', ] depends_on :cask => 'virtualbox' end
cask :v1_1 => 'dockertoolbox' do version '1.9.0c' sha256 '7aac99785e4739b11ba9a2a5a07ca33084252c9c06b8a4ae759f6a9ba5bf3ea9' url "https://github.com/docker/toolbox/releases/download/v#{version}/DockerToolbox-#{version}.pkg" appcast 'https://github.com/docker/toolbox/releases.atom' name 'Docker Toolbox' homepage 'https://www.docker.com/toolbox' license :apache pkg "DockerToolbox-#{version}.pkg" postflight do set_ownership '~/.docker' end uninstall :pkgutil => [ 'io.boot2dockeriso.pkg.boot2dockeriso', 'io.docker.pkg.docker', 'io.docker.pkg.dockercompose', 'io.docker.pkg.dockermachine', 'io.docker.pkg.dockerquickstartterminalapp', 'io.docker.pkg.kitematicapp', ] depends_on :cask => 'virtualbox' end
Modify podspec file to include swift files
Pod::Spec.new do |spec| spec.name = "ImagizerSwift" spec.version = "0.1.0" spec.summary = "The official swift client for the ImagizerEngine." spec.homepage = "https://github.com/nventify/ImagizerSwift" spec.license = { type: 'APACHE', file: 'LICENSE' } spec.authors = { "Nicholas Pettas" => 'nick@nventify.com' } spec.platform = :ios, "9.1" spec.requires_arc = true spec.source = { git: "https://github.com/nventify/ImagizerSwift.git", tag: "v#{spec.version}", submodules: true } spec.source_files = 'ImagizerSwift/*.{h,m}' end
Pod::Spec.new do |spec| spec.name = "ImagizerSwift" spec.version = "0.1.1" spec.summary = "The official swift client for the ImagizerEngine." spec.homepage = "https://github.com/nventify/ImagizerSwift" spec.license = { type: 'APACHE', file: 'LICENSE' } spec.authors = { "Nicholas Pettas" => 'nick@nventify.com' } spec.platform = :ios, "9.1" spec.requires_arc = true spec.source = { git: "https://github.com/nventify/ImagizerSwift.git", tag: "v#{spec.version}", submodules: true } spec.requires_arc = true spec.source_files = 'ImagizerSwift/*.{h,m,swift}' end
Add rake task to migrate files to S3
namespace :paperclip do desc "Move files from local to S3" task move_to_s3: :environment do StoredFile.all.each do |stored_file| id_partition = ("%09d" % stored_file.id).scan(/\d{3}/).join("/") filename = stored_file.file_file_name.gsub(/#/, "-") local_filepath = "#{Rails.root}/public/files/#{id_partition}/original/#{filename}" print "Processing #{local_filepath}" begin File.open(local_filepath) do |filehandle| stored_file.file.assign(filehandle) if stored_file.file.save puts "; stored to #{stored_file.file.url}" else puts "; S3 store failed!" end end rescue Errno::ENOENT => e puts ": Skipping! File does not exist." end end end end
Fix package name for uninstallation. Add name.
cask :v1 => 'qldds' do version '1.20' sha256 '8abd0978eb90b1ef55b5ac079960b028cbc926673535a0802bccd590fb253bc6' url "https://github.com/Marginal/QLdds/releases/download/rel-#{version.gsub('.','')}/QLdds_#{version.gsub('.','')}.pkg" homepage 'https://github.com/Marginal/QLdds' license :gpl pkg "QLdds_#{version.gsub('.','')}.pkg" uninstall :pkgutil => 'uk.org.marginal.*' end
cask :v1 => 'qldds' do version '1.20' sha256 '8abd0978eb90b1ef55b5ac079960b028cbc926673535a0802bccd590fb253bc6' url "https://github.com/Marginal/QLdds/releases/download/rel-#{version.gsub('.','')}/QLdds_#{version.gsub('.','')}.pkg" name 'QuickLook DDS' homepage 'https://github.com/Marginal/QLdds' license :gpl pkg "QLdds_#{version.gsub('.','')}.pkg" uninstall :pkgutil => 'uk.org.marginal.qldds' end
Fix :wrapper_html :class and :button_html :class options
module FormtasticBootstrap module Actions module Base # Bootstrap doesn't have wrappers. def wrapper(&block) # TODO Detect if user passed wrapper_html_options and issue # a warning that they're ignored. (See the original in # Formtastic.) template.capture(&block) end def default_button_html { :accesskey => accesskey, :class => "btn" } end end end end
module FormtasticBootstrap module Actions module Base # Bootstrap doesn't have wrappers. def wrapper(&block) template.capture(&block) end # Default button class def default_wrapper_classes ["btn"] end # :wrapper_html member :class is prefixed with btn # :button_html member :class is all encompassing def default_button_html { :accesskey => accesskey, :class => wrapper_class.strip, :id => wrapper_id } end end end end
Move class method calls to above class method definitions in Post model
module Forem class Post < ActiveRecord::Base belongs_to :topic, :touch => true belongs_to :user, :class_name => Forem.user_class.to_s belongs_to :reply_to, :class_name => "Post" has_many :replies, :class_name => "Post", :foreign_key => "reply_to_id", :dependent => :nullify delegate :forum, :to => :topic class << self def by_created_at order("created_at asc") end end validates :text, :presence => true after_create :subscribe_replier after_create :email_topic_subscribers def owner_or_admin?(other_user) self.user == other_user || other_user.forem_admin? end def subscribe_replier if self.topic && self.user self.topic.subscribe_user(self.user.id) end end def email_topic_subscribers if self.topic self.topic.subscriptions.includes(:subscriber).each do |subscription| if subscription.subscriber != self.user subscription.send_notification(self.id) end end end end end end
module Forem class Post < ActiveRecord::Base belongs_to :topic, :touch => true belongs_to :user, :class_name => Forem.user_class.to_s belongs_to :reply_to, :class_name => "Post" has_many :replies, :class_name => "Post", :foreign_key => "reply_to_id", :dependent => :nullify delegate :forum, :to => :topic validates :text, :presence => true after_create :subscribe_replier after_create :email_topic_subscribers class << self def by_created_at order("created_at asc") end end def owner_or_admin?(other_user) self.user == other_user || other_user.forem_admin? end def subscribe_replier if self.topic && self.user self.topic.subscribe_user(self.user.id) end end def email_topic_subscribers if self.topic self.topic.subscriptions.includes(:subscriber).each do |subscription| if subscription.subscriber != self.user subscription.send_notification(self.id) end end end end end end
Use alias_method in preference to alias.
# Override Chef LWRP creation to remove existing class to avoid redefinition warnings. class Chef class Provider class << self alias :old_build_from_file :build_from_file def build_from_file(cookbook_name, filename, run_context) remove_existing_lwrp(convert_to_class_name(filename_to_qualified_string(cookbook_name, filename))) old_build_from_file(cookbook_name, filename, run_context) end # Remove any existing Chef provider or resource with the specified name. # # @param [String] class_name The class name. Must be a valid constant name. def remove_existing_lwrp(class_name) [Chef::Resource, Chef::Provider].each do |resource_holder| if resource_holder.const_defined? class_name resource_holder.send(:remove_const, class_name) end end end end end end
# Override Chef LWRP creation to remove existing class to avoid redefinition warnings. class Chef class Provider class << self alias_method :old_build_from_file, :build_from_file def build_from_file(cookbook_name, filename, run_context) remove_existing_lwrp(convert_to_class_name(filename_to_qualified_string(cookbook_name, filename))) old_build_from_file(cookbook_name, filename, run_context) end # Remove any existing Chef provider or resource with the specified name. # # @param [String] class_name The class name. Must be a valid constant name. def remove_existing_lwrp(class_name) [Chef::Resource, Chef::Provider].each do |resource_holder| if resource_holder.const_defined? class_name resource_holder.send(:remove_const, class_name) end end end end end end
Use public Fog methods to get public IP address
module Veewee module Provider module Kvm module BoxCommand def ip_address ip=@connection.servers.all(:name => "#{name}").first.addresses[:public] return ip.first unless ip.nil? return ip end end # End Module end # End Module end # End Module end # End Module
module Veewee module Provider module Kvm module BoxCommand def ip_address ip=@connection.servers.all(:name => "#{name}").first.public_ip_address return ip.first unless ip.nil? return ip end end # End Module end # End Module end # End Module end # End Module
Write log messages one at a time
require 'stud/buffer' module LogStashLogger module Device class Connectable < Base include Stud::Buffer def initialize(opts = {}) super @batch_events = opts[:batch_events] || opts[:max_items] @batch_timeout = opts[:batch_timeout] || opts[:max_interval] buffer_initialize max_items: @batch_events, max_interval: @batch_timeout end def write(message) buffer_receive message buffer_flush(force: true) if @sync end def flush(*messages) if messages.empty? buffer_flush else write_batch(messages) end end def close buffer_flush(final: true) super end def to_io with_connection do @io end end def connected? !!@io end def write_batch(messages) with_connection do @io.write(messages.join) end end # Implemented by subclasses def connect fail NotImplementedError end def reconnect @io = nil connect end # Ensure the block is executed with a valid connection def with_connection(&block) connect unless connected? yield rescue => e warn "#{self.class} - #{e.class} - #{e.message}" @io = nil raise end end end end
require 'stud/buffer' module LogStashLogger module Device class Connectable < Base include Stud::Buffer def initialize(opts = {}) super @batch_events = opts[:batch_events] || opts[:max_items] @batch_timeout = opts[:batch_timeout] || opts[:max_interval] buffer_initialize max_items: @batch_events, max_interval: @batch_timeout end def write(message) buffer_receive message buffer_flush(force: true) if @sync end def flush(*args) if args.empty? buffer_flush else write_batch(args[0]) end end def close buffer_flush(final: true) super end def to_io with_connection do @io end end def connected? !!@io end def write_batch(messages) with_connection do messages.each do |message| @io.write(message) end end end # Implemented by subclasses def connect fail NotImplementedError end def reconnect @io = nil connect end # Ensure the block is executed with a valid connection def with_connection(&block) connect unless connected? yield rescue => e warn "#{self.class} - #{e.class} - #{e.message}" @io = nil raise end end end end
Update default to the latest version
default[:nodejs][:default] = "0.10.17" default[:nodejs][:versions] = [ node[:nodejs][:default] ] default[:nodejs][:aliases] = { node[:nodejs][:default] => node[:nodejs][:default][/\d+\.\d+/] }
default[:nodejs][:default] = "0.10.18" default[:nodejs][:versions] = [ node[:nodejs][:default] ] default[:nodejs][:aliases] = { node[:nodejs][:default] => node[:nodejs][:default][/\d+\.\d+/] }
Add tests around Host equality
require File.expand_path("#{File.dirname(__FILE__)}/../spec_helper.rb") require 'ghost/host' describe Ghost::Host do describe 'attributes' do subject { Ghost::Host.new('google.com', '74.125.225.102') } its(:name) { should == 'google.com' } its(:to_s) { should == 'google.com' } its(:host) { should == 'google.com' } its(:hostname) { should == 'google.com' } its(:ip) { should == '74.125.225.102'} its(:ip_address) { should == '74.125.225.102'} end it 'has a default IP of 127.0.0.1' do Ghost::Host.new('xyz.com').ip.should == '127.0.0.1' end end
require File.expand_path("#{File.dirname(__FILE__)}/../spec_helper.rb") require 'ghost/host' describe Ghost::Host do describe 'attributes' do subject { Ghost::Host.new('google.com', '74.125.225.102') } its(:name) { should == 'google.com' } its(:to_s) { should == 'google.com' } its(:host) { should == 'google.com' } its(:hostname) { should == 'google.com' } its(:ip) { should == '74.125.225.102'} its(:ip_address) { should == '74.125.225.102'} end it 'has a default IP of 127.0.0.1' do Ghost::Host.new('xyz.com').ip.should == '127.0.0.1' end describe 'equality' do it 'is equal to a host with the same hostname and IP' do Ghost::Host.new('google.com', '123.123.123.123').should == Ghost::Host.new('google.com', '123.123.123.123') end it 'is not equal to a host with a different host name' do Ghost::Host.new('google.com', '123.123.123.123').should_not == Ghost::Host.new('gmail.com', '123.123.123.123') end it 'is not equal to a host with a different IP' do Ghost::Host.new('google.com', '123.123.123.123').should_not == Ghost::Host.new('google.com', '222.222.222.222') end end end
Add (very) basic tests for public schedule.
require 'test_helper' class Public::ScheduleControllerTest < ActionController::TestCase # Replace this with your real tests. test "the truth" do assert true end end
require 'test_helper' class Public::ScheduleControllerTest < ActionController::TestCase setup do @conference = FactoryGirl.create(:conference) 10.times do FactoryGirl.create(:event, :conference => @conference, :state => "confirmed") end end test "displays schedule main page" do get :index, :conference_acronym => @conference.acronym assert_response :success end test "displays xml schedule" do get :index, :format => :xml, :conference_acronym => @conference.acronym assert_response :success end test "displays json schedule" do get :index, :format => :json, :conference_acronym => @conference.acronym assert_response :success end test "displays ical schedule" do get :index, :format => :ics, :conference_acronym => @conference.acronym assert_response :success end test "displays xcal schedule" do get :index, :format => :xcal, :conference_acronym => @conference.acronym assert_response :success end end
Remove extra args attr from Schedule
require 'active_support/core_ext/string/inflections' module Repeatable class Schedule def initialize(args) @args = args @expression = build_expression(args) end def occurrences(start_date, end_date) (start_date..end_date).select { |date| occurring?(date) } end def next_occurrence(start_date = Date.today) date = start_date until occurring?(date) date += 1 end date end def occurring?(date = Date.today) expression.include?(date) end private attr_reader :args, :expression def build_expression(hash) if hash.length != 1 fail "Invalid expression: '#{hash}' should have single key and value" else expression_for(*hash.first) end end def expression_for(key, value) klass = "repeatable/expression/#{key}".classify.safe_constantize case klass when nil fail "Unknown mapping: Can't map key '#{key.inspect}' to an expression class" when Repeatable::Expression::Set args = value.map { |hash| build_expression(hash) } klass.new(*args) else klass.new(value) end end end end
require 'active_support/core_ext/string/inflections' module Repeatable class Schedule def initialize(args) @expression = build_expression(args) end def occurrences(start_date, end_date) (start_date..end_date).select { |date| occurring?(date) } end def next_occurrence(start_date = Date.today) date = start_date until occurring?(date) date += 1 end date end def occurring?(date = Date.today) expression.include?(date) end private attr_reader :expression def build_expression(hash) if hash.length != 1 fail "Invalid expression: '#{hash}' should have single key and value" else expression_for(*hash.first) end end def expression_for(key, value) klass = "repeatable/expression/#{key}".classify.safe_constantize case klass when nil fail "Unknown mapping: Can't map key '#{key.inspect}' to an expression class" when Repeatable::Expression::Set args = value.map { |hash| build_expression(hash) } klass.new(*args) else klass.new(value) end end end end
Add functional tests for template rendering
require 'spec_helper' module Omnibus class RandomClass include Templating end describe Templating do subject { RandomClass.new } describe '#render_template' do let(:source) { "#{tmp_path}/source.erb" } let(:destination) { "#{tmp_path}/final" } let(:mode) { 0644 } let(:variables) { { name: 'Name' } } let(:contents) do <<-EOH.gsub(/^ {10}/, '') <%= name %> <% if false -%> This is magic! <% end -%> EOH end let(:options) do { destination: destination, variables: variables, mode: mode, } end before do File.open(source, 'w') { |f| f.write(contents) } end context 'when no destination is given' do let(:destination) { nil } it 'renders adjacent, without the erb extension' do subject.render_template(source, options) expect("#{tmp_path}/source").to be_a_file end end context 'when a destination is given' do it 'renders at the destination' do subject.render_template(source, options) expect(destination).to be_a_file end end context 'when a mode is given' do let(:mode) { 0755 } it 'renders the object with the mode' do subject.render_template(source, options) expect(destination).to be_an_executable end end context 'when an undefined variable is used' do let(:contents) { "<%= not_a_real_variable %>" } it 'raise an exception' do expect { subject.render_template(source, options) }.to raise_error end end end end end
Use before action to respond with 404 if prometheus metrics are missing
class Projects::PrometheusController < Projects::ApplicationController before_action :authorize_read_project! def active_metrics return render_404 unless has_prometheus_metrics? matched_metrics = prometheus_service.reactive_query(Gitlab::Prometheus::Queries::MatchedMetricsQuery.name, &:itself) if matched_metrics render json: matched_metrics, status: :ok else head :no_content end end def prometheus_service project.monitoring_service end def has_prometheus_metrics? prometheus_service&.respond_to?(:reactive_query) end end
class Projects::PrometheusController < Projects::ApplicationController before_action :authorize_read_project! before_action :require_prometheus_metrics! def active_metrics matched_metrics = prometheus_service.reactive_query(Gitlab::Prometheus::Queries::MatchedMetricsQuery.name, &:itself) if matched_metrics render json: matched_metrics, status: :ok else head :no_content end end private def prometheus_service project.monitoring_service end def has_prometheus_metrics? prometheus_service&.respond_to?(:reactive_query) end def require_prometheus_metrics! render_404 unless has_prometheus_metrics? end end
Update DBeaver Enterprise to 3.1.2
cask :v1 => 'dbeaver-enterprise' do version '3.1.1' if Hardware::CPU.is_32_bit? sha256 '692bf7ab300f0876ab3dac996e61f0b7c367db307c8190754fbf798dbb38daeb' url "http://dbeaver.jkiss.org/files/dbeaver-#{version}-ee-macosx.cocoa.x86.zip" else sha256 '27564968a4fd27dcaca5a9639cd787f63f006cab844017c7d094f922d506922d' url "http://dbeaver.jkiss.org/files/dbeaver-#{version}-ee-macosx.cocoa.x86_64.zip" end homepage 'http://dbeaver.jkiss.org/' license :oss app 'dbeaver/dbeaver.app' end
cask :v1 => 'dbeaver-enterprise' do version '3.1.2' if Hardware::CPU.is_32_bit? sha256 '69e3fbb77f6dfa4039f2535451849ae3811e0430764bd507ecc5df3cd7eb28ba' url "http://dbeaver.jkiss.org/files/dbeaver-#{version}-ee-macosx.cocoa.x86.zip" else sha256 'f868445eecae115245b5d0882917e548c1a799c3ea8e6e47c551557d62a857ff' url "http://dbeaver.jkiss.org/files/dbeaver-#{version}-ee-macosx.cocoa.x86_64.zip" end homepage 'http://dbeaver.jkiss.org/' license :oss app 'dbeaver/dbeaver.app' end
Fix destroy in vagrant 1.5.1+
require 'yaml' module VagrantPlugins module ProviderLibvirt module Action class PruneNFSExports def initialize(app, env) @app = app end def call(env) if env[:host] uuid = env[:machine].id # get all uuids uuids = env[:libvirt_compute].servers.all.map(&:id) # not exiisted in array will removed from nfs uuids.delete(uuid) env[:host].nfs_prune(uuids) end @app.call(env) end end end end end
require 'yaml' module VagrantPlugins module ProviderLibvirt module Action class PruneNFSExports def initialize(app, env) @app = app end def call(env) if env[:host] uuid = env[:machine].id # get all uuids uuids = env[:libvirt_compute].servers.all.map(&:id) # not exiisted in array will removed from nfs uuids.delete(uuid) env[:host].capability( :nfs_prune, env[:machine].ui, uuids) end @app.call(env) end end end end end
Update Macaw to latest version
cask :v1 => 'macaw' do version '1.5.9' sha256 '390a052022e92289a9c8ef2973e91d7f6928ff88eb3702f0feebe52c8036a717' url "http://download.macaw.co/#{version}/Macaw#{version}.dmg" appcast 'http://download.macaw.co/appcast.xml', :sha256 => '33dff9f8acedaf8d8213e5d88b18219fc2686f38d32b42dae6a55ace3dc917ad' homepage 'http://macaw.co/' license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder app 'Macaw.app' end
cask :v1 => 'macaw' do version '1.5.10' sha256 'e9a038afe2ad28e9110afd1aedd442f2e3cbf3daf0edcba6d08841fdbc9bfd4b' url "http://download.macaw.co/#{version}/Macaw#{version}.dmg" appcast 'http://download.macaw.co/appcast.xml', :sha256 => '6db73e26f6d1d9a891762e9622e594c79fc0d2bb57ff14a98951e7d8ade37d92' homepage 'http://macaw.co/' license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder app 'Macaw.app' end
Add Fiery Color Profiler Suite v4.6.2.08
class FieryColorProfilerSuite < Cask version '4.6.2.08' sha256 'cc9614227e7f3e24fbb8862fc16ae1e27d81e8e03f2c07ad30a0ed9823b1c92f' url 'https://d1umxs9ckzarso.cloudfront.net/Products/CPS/Mac_FCPS_4.6.2.08.dmg' homepage 'http://w3.efi.com/en/Fiery/Products/Workflow-Suite/CPS/Download/thank-you' license :unknown installer :manual => 'Fiery Color Profiler Suite 4.app' end
Use password field to hide token.
class Service::Travis < Service default_events :push, :pull_request, :issue_comment, :public, :member string :user, :token, :domain white_list :domain, :user def receive_event http.ssl[:verify] = false http.basic_auth user, token http.headers['X-GitHub-Event'] = event.to_s http_post travis_url, :payload => payload.to_json end def travis_url "#{scheme}://#{domain}" end def user if data['user'].to_s == '' payload['repository']['owner']['name'] else data['user'] end.strip end def token data['token'].to_s.strip end def scheme domain_parts.size == 1 ? 'http' : domain_parts.first end def domain domain_parts.last end protected def full_domain if data['domain'].present? data['domain'] else 'http://notify.travis-ci.org' end.strip end def domain_parts @domain_parts ||= full_domain.split('://') end end
class Service::Travis < Service default_events :push, :pull_request, :issue_comment, :public, :member string :user password :token string :domain white_list :domain, :user def receive_event http.ssl[:verify] = false http.basic_auth user, token http.headers['X-GitHub-Event'] = event.to_s http_post travis_url, :payload => payload.to_json end def travis_url "#{scheme}://#{domain}" end def user if data['user'].to_s == '' payload['repository']['owner']['name'] else data['user'] end.strip end def token data['token'].to_s.strip end def scheme domain_parts.size == 1 ? 'http' : domain_parts.first end def domain domain_parts.last end protected def full_domain if data['domain'].present? data['domain'] else 'http://notify.travis-ci.org' end.strip end def domain_parts @domain_parts ||= full_domain.split('://') end end
Update PostgreSQLAdapter to work with jdbc-postgres
require 'spectacles/schema_statements/abstract_adapter' module Spectacles module SchemaStatements module PostgreSQLAdapter include Spectacles::SchemaStatements::AbstractAdapter def views(name = nil) #:nodoc: q = <<-SQL SELECT table_name, table_type FROM information_schema.tables WHERE table_schema IN (#{schemas}) AND table_type = 'VIEW' SQL query(q, name).map { |row| row[0] } end def view_build_query(view, name = nil) q = <<-SQL SELECT view_definition FROM information_schema.views WHERE table_catalog = (SELECT catalog_name FROM information_schema.information_schema_catalog_name) AND table_schema IN (#{schemas}) AND table_name = '#{view}' SQL select_value(q, name) or raise "No view called #{view} found" end private def schemas schema_search_path.split(/,/).map { |p| quote(p) }.join(',') end end end end
require 'spectacles/schema_statements/abstract_adapter' module Spectacles module SchemaStatements module PostgreSQLAdapter include Spectacles::SchemaStatements::AbstractAdapter def views(name = nil) #:nodoc: q = <<-SQL SELECT table_name, table_type FROM information_schema.tables WHERE table_schema IN (#{schemas}) AND table_type = 'VIEW' SQL execute(q, name).map { |row| row['table_name'] } end def view_build_query(view, name = nil) q = <<-SQL SELECT view_definition FROM information_schema.views WHERE table_catalog = (SELECT catalog_name FROM information_schema.information_schema_catalog_name) AND table_schema IN (#{schemas}) AND table_name = '#{view}' SQL select_value(q, name) or raise "No view called #{view} found" end private def schemas schema_search_path.split(/,/).map { |p| quote(p) }.join(',') end end end end
Update description of the home page
# Renders the home page. class HomeController < ApplicationController def about @page_title = 'About us' @page_description = 'About MENA devs' @page_keywords = AppSettings.meta_tags_keywords end def index @page_title = 'Homepage' @page_description = 'Home of MENA devs' @page_keywords = AppSettings.meta_tags_keywords end def contact @page_title = 'Contact us' @page_description = 'Contact MENA devs community' @page_keywords = AppSettings.meta_tags_keywords end def events @page_title = 'Events' @page_description = 'Community events organised by MENA devs' @page_keywords = AppSettings.meta_tags_keywords respond_to do |format| format.html # events.html.erb end end def partners @page_title = 'Community Partners' @page_description = 'Community partners listing' @page_keywords = AppSettings.meta_tags_keywords respond_to do |format| format.html # partners.html.erb end end def partner @page_title = 'Community Partners' @page_description = 'Community partner' @page_keywords = AppSettings.meta_tags_keywords respond_to do |format| format.html # partner.html.erb end end end
# Renders the home page. class HomeController < ApplicationController def about @page_title = 'About us' @page_description = 'About MENA devs' @page_keywords = AppSettings.meta_tags_keywords end def index @page_title = 'Homepage' @page_description = "Home of MENA devs. One of the largest online communities for developers in the MENA region. Join in if you're looking for software developers, CTO, technical expertise or to connect with mentors and community leaders." @page_keywords = AppSettings.meta_tags_keywords end def contact @page_title = 'Contact us' @page_description = 'Contact MENA devs community' @page_keywords = AppSettings.meta_tags_keywords end def events @page_title = 'Events' @page_description = 'Community events organised by MENA devs' @page_keywords = AppSettings.meta_tags_keywords respond_to do |format| format.html # events.html.erb end end def partners @page_title = 'Community Partners' @page_description = 'Community partners listing' @page_keywords = AppSettings.meta_tags_keywords respond_to do |format| format.html # partners.html.erb end end def partner @page_title = 'Community Partners' @page_description = 'Community partner' @page_keywords = AppSettings.meta_tags_keywords respond_to do |format| format.html # partner.html.erb end end end
Remove gem spec from environment
# Settings specified here will take precedence over those in config/environment.rb config.log_level = :info # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.action_controller.consider_all_requests_local = true config.action_controller.perform_caching = true config.action_view.debug_rjs = true # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_deliveries = false config.action_mailer.delivery_method = :sendmail # so is queued, rather than giving immediate errors # Writes useful log files to debug memory leaks, of the sort where have # unintentionally kept references to objects, especially strings. # require 'memory_profiler' # MemoryProfiler.start :string_debug => true, :delay => 10 config.gem "gettext", :version => '>=1.9.3', :lib => false
# Settings specified here will take precedence over those in config/environment.rb config.log_level = :info # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.action_controller.consider_all_requests_local = true config.action_controller.perform_caching = true config.action_view.debug_rjs = true # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_deliveries = false config.action_mailer.delivery_method = :sendmail # so is queued, rather than giving immediate errors # Writes useful log files to debug memory leaks, of the sort where have # unintentionally kept references to objects, especially strings. # require 'memory_profiler' # MemoryProfiler.start :string_debug => true, :delay => 10
Update to latest Premailer syntax for strings
class PagesController < ApplicationController skip_authorization_check skip_before_action :authenticate_user! # Preview html email template def email tpl = (params[:layout] || 'hero').to_sym tpl = :hero unless [:email, :hero, :simple].include? tpl file = 'user_mailer/welcome_email' @user = User.new FactoryGirl.attributes_for(:user) render file, layout: "emails/#{tpl}" if params[:premail] == 'true' puts "\n!!! USING PREMAILER !!!\n\n" pre = Premailer.new(response_body[0], warn_level: Premailer::Warnings::SAFE) reset_response # pre.warnings render text: pre.to_inline_css, layout: false end end def error redirect_to root_path if flash.empty? end end
class PagesController < ApplicationController skip_authorization_check skip_before_action :authenticate_user! # Preview html email template def email tpl = (params[:layout] || 'hero').to_sym tpl = :hero unless [:email, :hero, :simple].include? tpl file = 'user_mailer/welcome_email' @user = User.new FactoryGirl.attributes_for(:user) render file, layout: "emails/#{tpl}" if params[:premail] == 'true' puts "\n!!! USING PREMAILER !!!\n\n" pre = Premailer.new(response_body[0], warn_level: Premailer::Warnings::SAFE, with_html_string: true) reset_response # pre.warnings render text: pre.to_inline_css, layout: false end end def error redirect_to root_path if flash.empty? end end
Update Beatport Pro to 2.1.1_137
class BeatportPro < Cask version '2.1.0_133' sha256 'd668c8fb82be5a5402a2470f7f65df75d08bad84352a609ea694290e29df93e2' url "http://pro.beatport.com/mac/#{version}/beatportpro_#{version}.dmg" homepage 'http://pro.beatport.com/' license :unknown app 'Beatport Pro.app' end
class BeatportPro < Cask version '2.1.1_137' sha256 '62526d08723e5a54953473a2c1530e5b298ab2a50a491dd2a846bf7c0b9499cb' url "http://pro.beatport.com/mac/#{version}/beatportpro_#{version}.dmg" homepage 'http://pro.beatport.com/' license :unknown app 'Beatport Pro.app' end
Make a new Errors module for the errors
module Discordrb # Raised when authentication data is invalid or incorrect. class InvalidAuthenticationException < RuntimeError; end # Raised when a HTTP status code indicates a failure class HTTPStatusException < RuntimeError attr_reader :status def initialize(status) @status = status end end # Raised when a message is over the character limit class MessageTooLong < RuntimeError; end # Raised when the bot can't do something because its permissions on the server are insufficient class NoPermission < RuntimeError; end end
module Discordrb module Errors # Raised when authentication data is invalid or incorrect. class InvalidAuthenticationException < RuntimeError; end # Raised when a HTTP status code indicates a failure class HTTPStatusException < RuntimeError attr_reader :status def initialize(status) @status = status end end # Raised when a message is over the character limit class MessageTooLong < RuntimeError; end # Raised when the bot can't do something because its permissions on the server are insufficient class NoPermission < RuntimeError; end end end
Allow ChargeBookingTemplate.amount with no date.
class ChargeBookingTemplate < BookingTemplate # Charge Rates def charge_rate(date = nil) ChargeRate.current(charge_rate_code, date) end def amount(date) return 0.0 unless charge_rate(date) charge_rate(date).rate / 100 end def booking_parameters(params = {}) # Prepare parameters set by template booking_params = attributes.reject!{|key, value| !["title", "comments", "credit_account_id", "debit_account_id"].include?(key)} # Calculate amount booking_amount = self.amount(params['value_date']) if ref_type = params['reference_type'] and ref_id = params['reference_id'] reference = ref_type.constantize.find(ref_id) case self.amount_relates_to when 'reference_amount' booking_amount *= reference.amount when 'reference_balance' booking_amount *= reference.balance end end booking_params['amount'] = booking_amount # Override by passed in parameters booking_params.merge!(params) end end
class ChargeBookingTemplate < BookingTemplate # Charge Rates def charge_rate(date = nil) ChargeRate.current(charge_rate_code, date) end def amount(date = nil) return 0.0 unless charge_rate(date) charge_rate(date).rate / 100 end def booking_parameters(params = {}) # Prepare parameters set by template booking_params = attributes.reject!{|key, value| !["title", "comments", "credit_account_id", "debit_account_id"].include?(key)} # Calculate amount booking_amount = self.amount(params['value_date']) if ref_type = params['reference_type'] and ref_id = params['reference_id'] reference = ref_type.constantize.find(ref_id) case self.amount_relates_to when 'reference_amount' booking_amount *= reference.amount when 'reference_balance' booking_amount *= reference.balance end end booking_params['amount'] = booking_amount # Override by passed in parameters booking_params.merge!(params) end end
Fix topic/post creation error. Now we use build in HTML::WhiteLIstSanitizer instaead of removed white_list plugin. But plugin white_list_formatted_content still needed.
ActiveRecord::Base.class_eval do include ActionView::Helpers::TagHelper, ActionView::Helpers::TextHelper def self.format_attribute(attr_name) class << self; include ActionView::Helpers::TagHelper, ActionView::Helpers::TextHelper; end define_method(:body) { read_attribute attr_name } define_method(:body_html) { read_attribute "#{attr_name}_html" } define_method(:body_html=) { |value| write_attribute "#{attr_name}_html", value } before_save :format_content end def dom_id [self.class.name.downcase.pluralize.dasherize, id] * '-' end protected def format_content body.strip! if body.respond_to?(:strip!) self.body_html = body.blank? ? '' : body_html_with_formatting end def body_html_with_formatting body_html = auto_link body { |text| truncate(text, 50) } textilized = RedCloth.new(body_html) #, [ :hard_breaks ]) # textilized.hard_breaks = true if textilized.respond_to?("hard_breaks=") logger.info(textilized.to_html) white_list(textilized.to_html) end end
ActiveRecord::Base.class_eval do include ActionView::Helpers::TagHelper, ActionView::Helpers::TextHelper def self.format_attribute(attr_name) class << self; include ActionView::Helpers::TagHelper, ActionView::Helpers::TextHelper; end define_method(:body) { read_attribute attr_name } define_method(:body_html) { read_attribute "#{attr_name}_html" } define_method(:body_html=) { |value| write_attribute "#{attr_name}_html", value } before_save :format_content end def dom_id [self.class.name.downcase.pluralize.dasherize, id] * '-' end protected def format_content body.strip! if body.respond_to?(:strip!) self.body_html = body.blank? ? '' : body_html_with_formatting end def body_html_with_formatting body_html = auto_link body { |text| truncate(text, 50) } textilized = RedCloth.new(body_html) #, [ :hard_breaks ]) # textilized.hard_breaks = true if textilized.respond_to?("hard_breaks=") logger.info(textilized.to_html) HTML::WhiteListSanitizer.new.sanitize(textilized.to_html) end end
Fix dependency issues with octokit.
$LOAD_PATH.unshift 'lib' Gem::Specification.new do |s| s.name = "git-review" s.version = "1.0.5" s.date = Time.now.strftime('%F') s.summary = "facilitates GitHub code reviews" s.homepage = "http://github.com/b4mboo/git-review" s.email = "bamberger.dominik@gmail.com" s.authors = ["Dominik Bamberger"] s.files = %w( LICENSE ) s.files += Dir.glob("lib/**/*") s.files += Dir.glob("bin/**/*") s.executables = %w( git-review ) s.description = "Manage review workflow for projects hosted on GitHub (using pull requests)." s.add_runtime_dependency 'launchy' s.add_runtime_dependency 'octokit', '>= 0.6.5' s.add_runtime_dependency 'yajl-ruby' end
$LOAD_PATH.unshift 'lib' Gem::Specification.new do |s| s.name = "git-review" s.version = "1.0.6" s.date = Time.now.strftime('%F') s.summary = "facilitates GitHub code reviews" s.homepage = "http://github.com/b4mboo/git-review" s.email = "bamberger.dominik@gmail.com" s.authors = ["Dominik Bamberger"] s.files = %w( LICENSE ) s.files += Dir.glob("lib/**/*") s.files += Dir.glob("bin/**/*") s.executables = %w( git-review ) s.description = "Manage review workflow for projects hosted on GitHub (using pull requests)." s.add_runtime_dependency 'launchy' s.add_runtime_dependency 'octokit', '= 0.6.5' s.add_runtime_dependency 'yajl-ruby' end
Remove spurious require of AR.
require 'turnout' require 'rack/turnout' require 'rails' unless defined? Rails # For Rails 3 if defined? Rails::Engine require 'active_record' module Turnout class Engine < Rails::Engine initializer 'turnout.add_to_middleware_stack' do |app| app.config.middleware.use Rack::Turnout end end end end
require 'turnout' require 'rack/turnout' require 'rails' unless defined? Rails # For Rails 3 if defined? Rails::Engine #require 'active_record' module Turnout class Engine < Rails::Engine initializer 'turnout.add_to_middleware_stack' do |app| app.config.middleware.use Rack::Turnout end end end end
Update podspec to use CocoaLumberjack if it's available, and define the minimum deployment targets
Pod::Spec.new do |s| s.name = 'MagicalRecord' s.version = '2.3.0-beta.1' s.license = 'MIT' s.summary = 'Super Awesome Easy Fetching for Core Data 1!!!11!!!!1!.' s.homepage = 'http://github.com/magicalpanda/MagicalRecord' s.author = { 'Saul Mora' => 'saul@magicalpanda.com' } s.source = { :git => 'https://github.com/magicalpanda/MagicalRecord.git', :tag => "v#{s.version}" } s.description = 'Handy fetching, threading and data import helpers to make Core Data a little easier to use.' s.source_files = 'MagicalRecord/**/*.{h,m}' s.framework = 'CoreData' s.requires_arc = true s.prefix_header_contents = "#ifdef __OBJC__\n#define MR_SHORTHAND\n#import \"CoreData+MagicalRecord.h\"\n#endif" end
Pod::Spec.new do |s| s.name = 'MagicalRecord' s.version = '2.3.0-beta.2' s.license = 'MIT' s.summary = 'Super Awesome Easy Fetching for Core Data 1!!!11!!!!1!.' s.homepage = 'http://github.com/magicalpanda/MagicalRecord' s.author = { 'Saul Mora' => 'saul@magicalpanda.com' } s.source = { :git => 'https://github.com/magicalpanda/MagicalRecord.git', :tag => "v#{s.version}" } s.description = 'Handy fetching, threading and data import helpers to make Core Data a little easier to use.' s.requires_arc = true s.default_subspec = 'Core' s.ios.deployment_target = '6.0' s.osx.deployment_target = '10.8' s.subspec "Core" do |sp| sp.framework = 'CoreData' sp.source_files = 'MagicalRecord/**/*.{h,m}' sp.prefix_header_contents = <<-EOS #ifdef __OBJC__ #if defined(COCOAPODS_POD_AVAILABLE_CocoaLumberjack) #import "DDLog.h" #endif #import <CoreData/CoreData.h> #import "CoreData+MagicalRecord.h" #endif EOS end s.subspec "Shorthand" do |sp| sp.framework = 'CoreData' sp.source_files = 'MagicalRecord/**/*.{h,m}' sp.prefix_header_contents = <<-EOS #ifdef __OBJC__ #if defined(COCOAPODS_POD_AVAILABLE_CocoaLumberjack) #import "DDLog.h" #endif #import <CoreData/CoreData.h> #define MR_SHORTHAND 0 #import "CoreData+MagicalRecord.h" #endif EOS end end
Use string in gemspec instead of using constant
$:.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", "LICENSE"] s.add_dependency "sprockets", "~> 2.8" s.add_dependency "actionpack", ">= 3.0" s.add_dependency "activesupport", ">= 3.0" s.add_development_dependency "rake" s.add_development_dependency "railties", ">= 3.0" s.author = "Joshua Peek" s.email = "josh@joshpeek.com" end
Gem::Specification.new do |s| s.name = "sprockets-rails" s.version = "2.1.2" s.homepage = "https://github.com/rails/sprockets-rails" s.summary = "Sprockets Rails integration" s.license = "MIT" s.files = Dir["README.md", "lib/**/*.rb", "LICENSE"] s.add_dependency "sprockets", "~> 2.8" s.add_dependency "actionpack", ">= 3.0" s.add_dependency "activesupport", ">= 3.0" s.add_development_dependency "rake" s.add_development_dependency "railties", ">= 3.0" s.author = "Joshua Peek" s.email = "josh@joshpeek.com" end
Update Vienna.app to version 3.0.3
cask :v1 => 'vienna' do version '3.0.2' sha256 'a52a8de9591483d4c440ab1390ab7f66bbafee0e27e23517b7300b0df4e461e0' # sourceforge.net is the official download host per the vendor homepage url "http://downloads.sourceforge.net/vienna-rss/Vienna#{version}.tgz" appcast 'http://vienna-rss.org/changelog.xml', :sha256 => 'fcfbae9fe2ccae3bd3531436daa2060c16fab7d72de2a8eea1d13ccbcb66814d' name 'Vienna' homepage 'http://www.vienna-rss.org' license :apache app 'Vienna.app' zap :delete => [ '~/Library/Application Support/Vienna', '~/Library/Caches/uk.co.opencommunity.vienna2', '~/Library/Preferences/uk.co.opencommunity.vienna2.plist', ] end
cask :v1 => 'vienna' do version '3.0.3' sha256 '106c25c623866b5c2fe14fb38ffb19918fb15e753d7a05c5e15121ac546b3e05' # sourceforge.net is the official download host per the vendor homepage url "http://downloads.sourceforge.net/vienna-rss/Vienna#{version}.tgz" appcast 'http://vienna-rss.org/changelog.xml', :sha256 => '7ea4ef75c789e1ba1be0d977b5a6d20e8331dba5e6ae34339412cb71670955a6' name 'Vienna' homepage 'http://www.vienna-rss.org' license :apache app 'Vienna.app' zap :delete => [ '~/Library/Application Support/Vienna', '~/Library/Caches/uk.co.opencommunity.vienna2', '~/Library/Preferences/uk.co.opencommunity.vienna2.plist', ] end
Add spec for user_id uniq in NotificationSetting model
require 'rails_helper' RSpec.describe NotificationSetting, type: :model do describe "Associations" do it { is_expected.to belong_to(:user) } it { is_expected.to belong_to(:source) } end describe "Validation" do subject { NotificationSetting.new } it { is_expected.to validate_presence_of(:user) } it { is_expected.to validate_presence_of(:source) } it { is_expected.to validate_presence_of(:level) } end end
require 'rails_helper' RSpec.describe NotificationSetting, type: :model do describe "Associations" do it { is_expected.to belong_to(:user) } it { is_expected.to belong_to(:source) } end describe "Validation" do subject { NotificationSetting.new(source_id: 1, source_type: 'Project') } it { is_expected.to validate_presence_of(:user) } it { is_expected.to validate_presence_of(:source) } it { is_expected.to validate_presence_of(:level) } it { is_expected.to validate_uniqueness_of(:user_id).scoped_to([:source_id, :source_type]).with_message(/already exists in source/) } end end
Fix reject! method call in CommentsController
class CommentsController < ApplicationController before_filter :authenticate_user! # lol embedded documents before_filter :find_book_and_chapter_and_note def create @comment = @note.comments.build(params[:comment].merge!(:user => current_user)) if @comment.save change_note_state! @comment.send_notifications! flash[:notice] = "Comment has been created." redirect_to [@book, @chapter, @note] else @comments = @note.comments flash[:error] = "Comment could not be created." render "notes/show" end end private def change_note_state! if current_user.author? case params[:commit] when "Accept" @comment.note.accept! when "Reject" @comment.note.rejected! when "Reopen" @comment.note.reopen! end end end def find_book_and_chapter_and_note @book = Book.where(permalink: params[:book_id]).first @chapter = @book.chapters.where(:position => params[:chapter_id]).first @note = @chapter.notes.where(:number => params[:note_id]).first end end
class CommentsController < ApplicationController before_filter :authenticate_user! # lol embedded documents before_filter :find_book_and_chapter_and_note def create @comment = @note.comments.build(params[:comment].merge!(:user => current_user)) if @comment.save change_note_state! @comment.send_notifications! flash[:notice] = "Comment has been created." redirect_to [@book, @chapter, @note] else @comments = @note.comments flash[:error] = "Comment could not be created." render "notes/show" end end private def change_note_state! if current_user.author? case params[:commit] when "Accept" @comment.note.accept! when "Reject" @comment.note.reject! when "Reopen" @comment.note.reopen! end end end def find_book_and_chapter_and_note @book = Book.where(permalink: params[:book_id]).first @chapter = @book.chapters.where(:position => params[:chapter_id]).first @note = @chapter.notes.where(:number => params[:note_id]).first end end
Add basic JSON compare test
class JSONCompareTests < Test::Unit::TestCase include BrakemanTester::DiffHelper def setup @path = File.expand_path "#{TEST_PATH}/apps/rails3.2" @json_path = File.join @path, "report.json" File.delete @json_path if File.exist? @json_path Brakeman.run :app_path => @path, :output_files => [@json_path] @report = JSON.parse File.read(@json_path) end def update_json File.open @json_path, "w" do |f| f.puts @report.to_json end end def diff @diff = Brakeman.compare :app_path => @path, :previous_results_json => @json_path end def test_sanity diff assert_fixed 0 assert_new 0 end end
Add methods for destroy and save.
require 'fog/core/model' require 'fog/hp/models/storage/shared_files' module Fog module Storage class HP class SharedDirectory < Fog::Model identity :url attribute :bytes, :aliases => 'X-Container-Bytes-Used' attribute :count, :aliases => 'X-Container-Object-Count' def files @files ||= begin Fog::Storage::HP::SharedFiles.new( :shared_directory => self, :connection => connection ) end end end end end end
require 'fog/core/model' require 'fog/hp/models/storage/shared_files' module Fog module Storage class HP class SharedDirectory < Fog::Model identity :url attribute :bytes, :aliases => 'X-Container-Bytes-Used' attribute :count, :aliases => 'X-Container-Object-Count' def files @files ||= begin Fog::Storage::HP::SharedFiles.new( :shared_directory => self, :connection => connection ) end end def destroy requires :url # delete is not allowed false end def save(options = {}) requires :url data = connection.put_shared_container(url, options) merge_attributes(data.headers) true rescue Fog::Storage::HP::NotFound, Fog::HP::Errors::Forbidden false end end end end end
Add AC::Helpers module to jbuilder for api only apps
require 'rails/railtie' require 'jbuilder/jbuilder_template' class Jbuilder class Railtie < ::Rails::Railtie initializer :jbuilder do |app| ActiveSupport.on_load :action_view do ActionView::Template.register_template_handler :jbuilder, JbuilderHandler require 'jbuilder/dependency_tracker' end if app.config.respond_to?(:api_only) && app.config.api_only ActiveSupport.on_load :action_controller do include ActionView::Rendering end end end if Rails::VERSION::MAJOR >= 4 generators do |app| Rails::Generators.configure! app.config.generators Rails::Generators.hidden_namespaces.uniq! require 'generators/rails/scaffold_controller_generator' end end end end
require 'rails/railtie' require 'jbuilder/jbuilder_template' class Jbuilder class Railtie < ::Rails::Railtie initializer :jbuilder do |app| ActiveSupport.on_load :action_view do ActionView::Template.register_template_handler :jbuilder, JbuilderHandler require 'jbuilder/dependency_tracker' end if app.config.respond_to?(:api_only) && app.config.api_only ActiveSupport.on_load :action_controller do include ActionView::Rendering include ActionController::Helpers end end end if Rails::VERSION::MAJOR >= 4 generators do |app| Rails::Generators.configure! app.config.generators Rails::Generators.hidden_namespaces.uniq! require 'generators/rails/scaffold_controller_generator' end end end end
Create UploadingFaildError and use it
module Metalbird module Twitter class Publisher def initialize(auth) @client = auth.client end def publish(args) fail NotValidArgsError unless args.validate? options = {} options[:media_ids] = upload_images(args.images) if args.images? @client.update(args.tweet, options) rescue => error Metalbird::Logger.error(error) return false end def retweet(args) tweet = ::Twitter::Tweet.new(id: args.tweet_id) @client.retweet(tweet) rescue => error Metalbird::Logger.error(error) return false end private def upload_images(images) images.map { |image| upload(image) }.join(',') end def upload(file) @client.upload(file) rescue => error Metalbird::Logger.error(error) return false end end class NotValidArgsError < StandardError; end end end
module Metalbird module Twitter class Publisher def initialize(auth) @client = auth.client end def publish(args) fail NotValidArgsError unless args.validate? options = {} options[:media_ids] = upload_images(args.images) if args.images? @client.update(args.tweet, options) rescue => error Metalbird::Logger.error(error) return false end def retweet(args) tweet = ::Twitter::Tweet.new(id: args.tweet_id) @client.retweet(tweet) rescue => error Metalbird::Logger.error(error) return false end private def upload_images(images) images.map { |image| upload(image) }.join(',') end def upload(file) @client.upload(file) rescue => error Metalbird::Logger.error(error) raise UploadingFailedError end end class NotValidArgsError < StandardError; end class UploadingFailedError < StandardError; end end end
Update Time Tracker Cask to use SHA256
class TimeTrackerMac < Cask url 'https://time-tracker-mac.googlecode.com/files/Time%20Tracker-1.3.13.zip' homepage 'https://code.google.com/p/time-tracker-mac' version '1.3.13' sha1 '1d3fb3f824658856e18eb285d0ed92d81a1e9784' link 'Time Tracker.app' end
class TimeTrackerMac < Cask url 'https://time-tracker-mac.googlecode.com/files/Time%20Tracker-1.3.13.zip' homepage 'https://code.google.com/p/time-tracker-mac' version '1.3.13' sha256 'a6c982ee82f8babcf0f42d49950e5b3a1d613946736a7ee4a272b05916271aeb' link 'Time Tracker.app' end
Update download URL for Balsamiq Mockups
class BalsamiqMockups < Cask version :latest sha256 :no_check url 'http://builds.balsamiq.com/b/mockups-desktop/MockupsForDesktop.dmg' homepage 'http://balsamiq.com/' license :commercial app 'Balsamiq Mockups.app' end
class BalsamiqMockups < Cask version :latest sha256 :no_check # amazonaws is the official download host per the vendor homepage url 'http://s3.amazonaws.com/build_production/mockups-desktop/MockupsForDesktop.dmg' homepage 'http://balsamiq.com/' license :commercial app 'Balsamiq Mockups.app' end
Update Devise bypass sign in method
class Releaf::Permissions::ProfileController < Releaf::ActionController def load_resource # assign current user @resource = user.becomes(resource_class) end def success_url url_for(action: :edit) end def update load_resource old_password = @resource.password super # reload resource as password has been changed if @resource.password != old_password sign_in(user, bypass: true) end end def self.resource_class Releaf.application.config.permissions.devise_model_class end def controller_breadcrumb; end def features [:edit] end def permitted_params %w[name surname email password password_confirmation locale] end end
class Releaf::Permissions::ProfileController < Releaf::ActionController def load_resource # assign current user @resource = user.becomes(resource_class) end def success_url url_for(action: :edit) end def update load_resource old_password = @resource.password super # reload resource as password has been changed if @resource.password != old_password bypass_sign_in(user) end end def self.resource_class Releaf.application.config.permissions.devise_model_class end def controller_breadcrumb; end def features [:edit] end def permitted_params %w[name surname email password password_confirmation locale] end end
Add test-unit as a dependency to fix tests on 2.2.0
# -*- encoding: utf-8 -*- require File.expand_path('../lib/knife-block/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["proffalken"] gem.email = ["theprofessor@threedrunkensysadsonthe.net"] gem.description = %q{Create and manage knife.rb files for OpsCodes' Chef} gem.summary = %q{Create and manage knife.rb files for OpsCodes' Chef} gem.homepage = "https://github.com/greenandsecure/knife-block" gem.license = "MIT" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "knife-block" gem.require_paths = ["lib"] gem.version = Knife::Block::VERSION end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/knife-block/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["proffalken"] gem.email = ["theprofessor@threedrunkensysadsonthe.net"] gem.description = %q{Create and manage knife.rb files for OpsCodes' Chef} gem.summary = %q{Create and manage knife.rb files for OpsCodes' Chef} gem.homepage = "https://github.com/greenandsecure/knife-block" gem.license = "MIT" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "knife-block" gem.require_paths = ["lib"] gem.version = Knife::Block::VERSION gem.add_dependency('test-unit', '~> 2.5') end
Make it compatible with 1.8.7
require 'aruba/processes/spawn_process' module Aruba module Processes # Debug Process class DebugProcess < BasicProcess # Use only if mode is :debug def self.match?(mode) mode == :debug || (mode.is_a?(Class) && mode <= DebugProcess) end # rubocop:disable Metrics/MethodLength # rubocop:disable Metrics/CyclomaticComplexity def start if RUBY_VERSION < '2' Dir.chdir @working_directory do with_local_env(environment) do @exit_status = system(command, *arguments) ? 0 : 1 end end else with_local_env(environment) do @exit_status = system(command, *arguments, :chdir => @working_directory) ? 0 : 1 end end end # rubocop:enable Metrics/CyclomaticComplexity # rubocop:enable Metrics/MethodLength def stdin(*); end def stdout(*) 'This is the debug launcher on STDOUT. If this output is unexpected, please check your setup.' end def stderr(*) 'This is the debug launcher on STDERR. If this output is unexpected, please check your setup.' end def stop(_reader) @stopped = true @exit_status end def terminate(*) stop end end end end
require 'aruba/processes/spawn_process' module Aruba module Processes # Debug Process class DebugProcess < BasicProcess # Use only if mode is :debug def self.match?(mode) mode == :debug || (mode.is_a?(Class) && mode <= DebugProcess) end # rubocop:disable Metrics/MethodLength # rubocop:disable Metrics/CyclomaticComplexity def start Dir.chdir @working_directory do with_local_env(environment) do @exit_status = system(command, *arguments) ? 0 : 1 end end end # rubocop:enable Metrics/CyclomaticComplexity # rubocop:enable Metrics/MethodLength def stdin(*); end def stdout(*) 'This is the debug launcher on STDOUT. If this output is unexpected, please check your setup.' end def stderr(*) 'This is the debug launcher on STDERR. If this output is unexpected, please check your setup.' end def stop(_reader) @stopped = true @exit_status end def terminate(*) stop end end end end
Exclude `vendor` path from simplecov
require 'puppetlabs_spec_helper/module_spec_helper' require 'rspec-puppet-facts' include RspecPuppetFacts if Dir.exist?(File.expand_path('../../lib', __FILE__)) && RUBY_VERSION !~ %r{^1.9} require 'coveralls' require 'simplecov' require 'simplecov-console' SimpleCov.formatters = [ SimpleCov::Formatter::HTMLFormatter, SimpleCov::Formatter::Console, Coveralls::SimpleCov::Formatter ] SimpleCov.start do track_files 'lib/**/*.rb' add_filter '/spec' end end RSpec.configure do |c| default_facts = { puppetversion: Puppet.version, facterversion: Facter.version } default_facts.merge!(YAML.load(File.read(File.expand_path('../default_facts.yml', __FILE__)))) if File.exist?(File.expand_path('../default_facts.yml', __FILE__)) default_facts.merge!(YAML.load(File.read(File.expand_path('../default_module_facts.yml', __FILE__)))) if File.exist?(File.expand_path('../default_module_facts.yml', __FILE__)) c.default_facts = default_facts <%- if @configs['mock_with'] -%> c.mock_with <%= @configs['mock_with'] %> <%- end -%> end <%- [@configs['spec_overrides']].flatten.compact.each do |line| -%> <%= line %> <%- end -%> # vim: syntax=ruby
require 'puppetlabs_spec_helper/module_spec_helper' require 'rspec-puppet-facts' include RspecPuppetFacts if Dir.exist?(File.expand_path('../../lib', __FILE__)) && RUBY_VERSION !~ %r{^1.9} require 'coveralls' require 'simplecov' require 'simplecov-console' SimpleCov.formatters = [ SimpleCov::Formatter::HTMLFormatter, SimpleCov::Formatter::Console, Coveralls::SimpleCov::Formatter ] SimpleCov.start do track_files 'lib/**/*.rb' add_filter '/spec' add_filter '/vendor' add_filter '/.vendor' end end RSpec.configure do |c| default_facts = { puppetversion: Puppet.version, facterversion: Facter.version } default_facts.merge!(YAML.load(File.read(File.expand_path('../default_facts.yml', __FILE__)))) if File.exist?(File.expand_path('../default_facts.yml', __FILE__)) default_facts.merge!(YAML.load(File.read(File.expand_path('../default_module_facts.yml', __FILE__)))) if File.exist?(File.expand_path('../default_module_facts.yml', __FILE__)) c.default_facts = default_facts <%- if @configs['mock_with'] -%> c.mock_with <%= @configs['mock_with'] %> <%- end -%> end <%- [@configs['spec_overrides']].flatten.compact.each do |line| -%> <%= line %> <%- end -%> # vim: syntax=ruby
Add an API for reading event objects from a Notifier.
require 'singleton' module INotify class Notifier < IO def initialize @fd = Native.inotify_init return super(@fd) unless @fd < 0 raise SystemCallError.new( "Failed to initialize inotify" + case FFI.errno when Errno::EMFILE::Errno; ": the user limit on the total number of inotify instances has been reached." when Errno::ENFILE::Errno; ": the system limit on the total number of file descriptors has been reached." when Errno::ENOMEM::Errno; ": insufficient kernel memory is available." else; "" end, FFI.errno) end attr_reader :fd def watch(path, *flags) Watch.new(self, path, *flags) end end end
require 'singleton' module INotify class Notifier < IO def initialize @fd = Native.inotify_init return super(@fd) unless @fd < 0 raise SystemCallError.new( "Failed to initialize inotify" + case FFI.errno when Errno::EMFILE::Errno; ": the user limit on the total number of inotify instances has been reached." when Errno::ENFILE::Errno; ": the system limit on the total number of file descriptors has been reached." when Errno::ENOMEM::Errno; ": insufficient kernel memory is available." else; "" end, FFI.errno) end attr_reader :fd def watch(path, *flags) Watch.new(self, path, *flags) end def read_events size = 64 * Native::Event.size tries = 1 begin data = readpartial(size) rescue SystemCallError => er # EINVAL means that there's more data to be read # than will fit in the buffer size raise er unless er.errno == EINVAL || tries == 5 size *= 2 tries += 1 retry end events = [] while ev = Event.consume(data) events << ev end events end end end
Use display port provided by Fog
require 'veewee/provider/core/box' require 'veewee/provider/core/box/vnc' require 'veewee/provider/kvm/box/validate_kvm' module Veewee module Provider module Kvm module BoxCommand # Type on the console def console_type(sequence,type_options={}) vnc_port=@connection.servers.all(:name => name).first.vnc_port display_port=vnc_port.to_i - 5900 ui.success "Sending keystrokes to VNC port :#{display_port} - TCP port: #{vnc_port}" vnc_type(sequence,"127.0.0.1",display_port) end end # End Module end # End Module end # End Module end # End Module
require 'veewee/provider/core/box' require 'veewee/provider/core/box/vnc' require 'veewee/provider/kvm/box/validate_kvm' module Veewee module Provider module Kvm module BoxCommand # Type on the console def console_type(sequence,type_options={}) tcp_port=@connection.servers.all(:name => name).first.display[:port] display_port=tcp_port.to_i - 5900 ui.success "Sending keystrokes to VNC port :#{display_port} - TCP port: #{tcp_port}" vnc_type(sequence,"127.0.0.1",display_port) end end # End Module end # End Module end # End Module end # End Module
Add drbd and heartbeat, like peas and carrots
# # Cookbook Name:: drbd # Recipe:: default # # Copyright 2009, Opscode, 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. # # = Requirements # Templates:: # * /etc/drbd.conf include_recipe "lvm" package "drbd8-utils" do action :install end service "drbd" do supports( :restart => true, :status => true ) action :enable end
Add a migration that fixes the data problems caused by the PublicBody bug
# The PublicBody model class had a bug that meant the # translations for first_letter and publication_scheme # were not being correctly populated. # # This migration fixes up the data to correct this. # # Note that the "update ... from" syntax is a Postgres # extension to SQL. class FixPublicBodyTranslations < ActiveRecord::Migration def self.up execute <<-SQL update public_body_translations set first_letter = upper(substr(name, 1, 1)) where first_letter is null ; SQL execute <<-SQL update public_body_translations set publication_scheme = public_bodies.publication_scheme from public_bodies where public_body_translations.public_body_id = public_bodies.id and public_body_translations.publication_scheme is null ; SQL end def self.down # This is a bug-fix migration, that does not involve a schema change. # It doesn't make sense to reverse it. end end
Remove forem prefix from forum_topic_path call in link_to_latest_post
module Forem module TopicsHelper def link_to_latest_post(post) text = "#{time_ago_in_words(post.created_at)} #{t("ago_by")} #{post.user}" link_to text, forem.forum_topic_path(post.topic.forum, post.topic, :anchor => "post-#{post.id}") end end end
module Forem module TopicsHelper def link_to_latest_post(post) text = "#{time_ago_in_words(post.created_at)} #{t("ago_by")} #{post.user}" link_to text, forum_topic_path(post.topic.forum, post.topic, :anchor => "post-#{post.id}") end end end
Use fewer conditionals & simplify the required files
require 'active_support/core_ext' require 'ransack/configuration' if defined?(::Mongoid) require 'ransack/adapters/mongoid/ransack/constants' else require 'ransack/adapters/active_record/ransack/constants' end module Ransack extend Configuration class UntraversableAssociationError < StandardError; end; end Ransack.configure do |config| Ransack::Constants::AREL_PREDICATES.each do |name| config.add_predicate name, :arel_predicate => name end Ransack::Constants::DERIVED_PREDICATES.each do |args| config.add_predicate *args end end require 'ransack/translate' require 'ransack/adapters/active_record/ransack/translate' if defined?(::ActiveRecord::Base) require 'ransack/adapters/mongoid/ransack/translate' if defined?(::Mongoid) require 'ransack/search' require 'ransack/ransacker' require 'ransack/adapters/active_record' if defined?(::ActiveRecord::Base) require 'ransack/adapters/mongoid' if defined?(::Mongoid) require 'ransack/helpers' require 'action_controller' ActionController::Base.helper Ransack::Helpers::FormHelper
require 'active_support/core_ext' require 'ransack/configuration' if defined?(::Mongoid) require 'ransack/adapters/mongoid/ransack/constants' else require 'ransack/adapters/active_record/ransack/constants' end module Ransack extend Configuration class UntraversableAssociationError < StandardError; end; end Ransack.configure do |config| Ransack::Constants::AREL_PREDICATES.each do |name| config.add_predicate name, :arel_predicate => name end Ransack::Constants::DERIVED_PREDICATES.each do |args| config.add_predicate *args end end require 'ransack/search' require 'ransack/ransacker' require 'ransack/helpers' require 'action_controller' require 'ransack/translate' if defined?(::ActiveRecord::Base) require 'ransack/adapters/active_record/ransack/translate' require 'ransack/adapters/active_record' end if defined?(::Mongoid) require 'ransack/adapters/mongoid/ransack/translate' require 'ransack/adapters/mongoid' end ActionController::Base.helper Ransack::Helpers::FormHelper
Remove version constraint for Rake
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "localdoc/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "localdoc" s.version = Localdoc::VERSION s.authors = ["Marica Odagaki"] s.email = ["marica@noredink.com"] s.homepage = "https://github.com/NoRedInk/localdoc" s.summary = "Documentation browser." s.description = "A Rails engine for viewing and editing local documentation." s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 3.2.22" s.add_dependency "haml-rails", "~> 0.4.0" s.add_dependency "rake", "~> 10.5.0" s.add_development_dependency "sqlite3" s.add_development_dependency "test-unit", "~> 3.0" s.add_development_dependency "rspec-rails" s.add_development_dependency "pry-rails" s.add_development_dependency "byebug" end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "localdoc/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "localdoc" s.version = Localdoc::VERSION s.authors = ["Marica Odagaki"] s.email = ["marica@noredink.com"] s.homepage = "https://github.com/NoRedInk/localdoc" s.summary = "Documentation browser." s.description = "A Rails engine for viewing and editing local documentation." s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 3.2.22" s.add_dependency "haml-rails", "~> 0.4.0" s.add_dependency "rake" s.add_development_dependency "sqlite3" s.add_development_dependency "test-unit", "~> 3.0" s.add_development_dependency "rspec-rails" s.add_development_dependency "pry-rails" s.add_development_dependency "byebug" end
Add an accessor for the title
module Discordrb::Webhooks # An embed is a multipart-style attachment to a webhook message that can have a variety of different purposes and # appearances. class Embed def initialize(title: nil, description: nil, url: nil, timestamp: nil, colour: nil, footer: nil, image: nil, thumbnail: nil, video: nil, provider: nil, author: nil, fields: []) @title = title @description = description @url = url @timestamp = timestamp @colour = colour @footer = footer @image = image @thumbnail = thumbnail @video = video @provider = provider @author = author @fields = fields end end end
module Discordrb::Webhooks # An embed is a multipart-style attachment to a webhook message that can have a variety of different purposes and # appearances. class Embed def initialize(title: nil, description: nil, url: nil, timestamp: nil, colour: nil, footer: nil, image: nil, thumbnail: nil, video: nil, provider: nil, author: nil, fields: []) @title = title @description = description @url = url @timestamp = timestamp @colour = colour @footer = footer @image = image @thumbnail = thumbnail @video = video @provider = provider @author = author @fields = fields end # The title of this embed that will be displayed above everything else. # @return [String] attr_accessor :title end end
Add a test for enabling Ezine::Member migration
require 'spec_helper' require Rails.root.join('lib/migrations/ezine/20150408081234_enable_member_state.rb') RSpec.describe SS::Migration20150408081234, dbscope: :example do before do member = create :ezine_member member.unset :state end it do expect { described_class.new.change } .to change { Ezine::Member.enabled.count }.by 1 end end
Add spec for ActionView template handler.
require 'spec_helper' require 'action_view' require 'active_support/core_ext/object/to_json' require 'haml_coffee_assets/action_view/template_handler' describe HamlCoffeeAssets::ActionView::TemplateHandler do def new_template(body) ::ActionView::Template.new(body, "template", described_class, {}) end let(:context) { Object.new } let(:locals) { Hash.new } it "renders basic templates" do output = new_template("Foo").render(context, locals) output.should == "Foo" end it "renders Haml" do output = new_template("%h1 Foo").render(context, locals) output.should == "<h1>Foo</h1>" end it "renders CoffeeScript" do output = new_template("= @foo").render(context, :foo => "Foo") output.should == "Foo" end it "has access to the helpers" do template = new_template("!= surround '(', ')', ->\n %span Foo") output = template.render(context, locals) output.should == "(<span>Foo</span>)" end end
Add spec for timestamp stat
# universe_timestamp stat tests # # Copyright (C) 2014 Mohammed Morsi <mo@morsi.org> # Licensed under the AGPLv3 http://www.gnu.org/licenses/agpl.txt require 'spec_helper' require 'stats/registry' describe Stats do describe "#universe_timestamp" do before(:each) do @stat = Stats.get_stat(:universe_timestamp) end it "returns current server time" do t = Time.now Time.stub!(:now).and_return(t) @stat.generate.value.should == t.to_f end end end
Add note about vendor/official homepage
cask :v1 => 'mac2imgur' do version :latest sha256 :no_check url 'https://mac2imgur.mileswd.com/static/mac2imgur.zip' name 'mac2imgur' homepage 'https://github.com/mileswd/mac2imgur' license :gpl app 'mac2imgur.app' zap :delete => [ '~/Library/Caches/com.mileswd.mac2imgur', '~/Library/Preferences/com.mileswd.mac2imgur.plist' ] end
cask :v1 => 'mac2imgur' do version :latest sha256 :no_check # mileswd.com is the official download host per the vendor homepage url 'https://mac2imgur.mileswd.com/static/mac2imgur.zip' name 'mac2imgur' homepage 'https://github.com/mileswd/mac2imgur' license :gpl app 'mac2imgur.app' zap :delete => [ '~/Library/Caches/com.mileswd.mac2imgur', '~/Library/Preferences/com.mileswd.mac2imgur.plist' ] end
Update podspec for 1.0.0 release.
Pod::Spec.new do |s| s.name = 'Valet' s.version = '0.9.9' s.license = 'Apache' s.summary = 'Valet lets you securely store data in the iOS or OS X Keychain without knowing a thing about how the Keychain works. It\'s easy. We promise.' s.homepage = 'https://stash.corp.squareup.com/projects/IOS/repos/valet/browse' s.authors = { 'Dan Federman' => 'federman@squareup.com', 'Eric Muller' => 'emuller@squareup.com' } s.source = { :git => 'https://stash.corp.squareup.com/scm/ios/valet.git', :tag => s.version } s.source_files = 'Valet/*.{h,m}', 'Other/*.{h,m}' s.ios.deployment_target = '6.0' s.osx.deployment_target = '10.9' end
Pod::Spec.new do |s| s.name = 'Valet' s.version = '1.0.0' s.license = 'Apache' s.summary = 'Valet lets you securely store data in the iOS or OS X Keychain without knowing a thing about how the Keychain works. It\'s easy. We promise.' s.homepage = 'https://github.com/square/objc-Valet' s.authors = 'Square' s.source = { :git => 'https://github.com/square/objc-Valet.git', :tag => s.version } s.source_files = 'Valet/*.{h,m}', 'Other/*.{h,m}' s.frameworks = 'Security' s.ios.deployment_target = '6.0' s.osx.deployment_target = '10.9' end
Update Bit Slicer (quick 1.7.5 bug-fix)
cask :v1 => 'bit-slicer' do version '1.7.5' sha256 '286487687fbd9a46f3d7bfa943a912a3e05183af06ebfaef8f6820253d5f93e7' # bitbucket.org is the official download host per the vendor homepage url "https://bitbucket.org/zorgiepoo/bit-slicer/downloads/Bit%20Slicer%20#{version}.zip" name 'Bit Slicer' appcast 'http://zorg.tejat.net/bitslicer/update.php', :sha256 => '2dca07d414e8888b06c0354fe4b381e91ff0945b381081db8f32bc0563d3b51e' homepage 'https://github.com/zorgiepoo/bit-slicer/' license :bsd app 'Bit Slicer.app' end
cask :v1 => 'bit-slicer' do version '1.7.5' sha256 '1180666794b41ddba4895c6f90ba9e428f49c115f0eb260d76061c6c6aa9f1a9' # bitbucket.org is the official download host per the vendor homepage url "https://bitbucket.org/zorgiepoo/bit-slicer/downloads/Bit%20Slicer%20#{version}.zip" name 'Bit Slicer' appcast 'http://zorg.tejat.net/bitslicer/update.php', :sha256 => 'ad8cdd11fb138f98a29bf24a31d3f82f086e6abf813787f91679ce5ec015239c' homepage 'https://github.com/zorgiepoo/bit-slicer/' license :bsd app 'Bit Slicer.app' end
Add a ruby client for receiving events
# encoding: utf-8 # To use this client install following gems # gem install msgpack # gem install rbczmq require 'zmq' require 'pp' require "msgpack" # PUB / SUB topology Thread.abort_on_exception = true ctx = ZMQ::Context.new socket = ctx.socket(:SUB) socket.verbose = true socket.subscribe("") socket.connect("tcp://localhost:5555") loop do message = socket.recv unpacked_message = MessagePack.unpack(message) p unpacked_message end
Load factories from /factories at the Rails root, just like the default definition_file_paths.
require 'factory_girl' require 'rails' module FactoryGirl class Railtie < Rails::Railtie config.after_initialize do FactoryGirl.definition_file_paths = [ File.join(Rails.root, 'test', 'factories'), File.join(Rails.root, 'spec', 'factories') ] FactoryGirl.find_definitions end end end
require 'factory_girl' require 'rails' module FactoryGirl class Railtie < Rails::Railtie config.after_initialize do FactoryGirl.definition_file_paths = [ File.join(Rails.root, 'factories'), File.join(Rails.root, 'test', 'factories'), File.join(Rails.root, 'spec', 'factories') ] FactoryGirl.find_definitions end end end
Update iTerm2 Beta to 2.9.20150626
cask :v1 => 'iterm2-beta' do version '2.1.1' sha256 'b8f1bbd11cdb3e26fd9fab6971c28ebeb422361b2cc5fd6e4a843836d5dedeb0' url 'https://iterm2.com/downloads/beta/iTerm2-2_1_1.zip' homepage 'http://www.iterm2.com/' license :oss app 'iTerm.app' end
cask :v1 => 'iterm2-beta' do version '2.9.20150626' sha256 '18cf11393ed81d351d739257185bc33414c440c4281e576f9d0b54405970f902' url 'https://iterm2.com/downloads/beta/iTerm2-2_9_20150626.zip' homepage 'http://www.iterm2.com/' license :oss app 'iTerm.app' end
Make focusing on certain specs easier.
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 require 'rspec' require 'twitter_cldr' class FastGettext class << self def locale @@locale || :en end def locale=(value) @@locale = value end end end RSpec.configure do |config| config.mock_with :rr config.filter_run_excluding(:slow => true) unless ENV['FULL_SPEC'] config.before(:each) do FastGettext.locale = :en end end RSpec::Matchers.define :match_normalized do |expected| match do |actual| expected.localize.normalize(:using => :NFKC).to_s == actual.localize.normalize(:using => :NFKC).to_s end end def check_token_list(got, expected) got.size.should == expected.size expected.each_with_index do |exp_hash, index| exp_hash.each_pair do |exp_key, exp_val| got[index].send(exp_key).should == exp_val end end end
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 require 'rspec' require 'twitter_cldr' class FastGettext class << self def locale @@locale || :en end def locale=(value) @@locale = value end end end RSpec.configure do |config| config.mock_with :rr config.filter_run(:focus => true) config.run_all_when_everything_filtered = true config.filter_run_excluding(:slow => true) unless ENV['FULL_SPEC'] config.before(:each) do FastGettext.locale = :en end end RSpec::Matchers.define :match_normalized do |expected| match do |actual| expected.localize.normalize(:using => :NFKC).to_s == actual.localize.normalize(:using => :NFKC).to_s end end def check_token_list(got, expected) got.size.should == expected.size expected.each_with_index do |exp_hash, index| exp_hash.each_pair do |exp_key, exp_val| got[index].send(exp_key).should == exp_val end end end
Simplify matcher by using RSpec3 syntax
RSpec::Matchers.define :perform_queries do |expected| match do |block| query_count(&block) == expected end failure_message do |actual| "Expected to run #{expected} queries, got #{@counter.query_count}" end def query_count(&block) @counter = ActiveRecord::QueryCounter.new ActiveSupport::Notifications.subscribe('sql.active_record', @counter.to_proc) yield ActiveSupport::Notifications.unsubscribe(@counter.to_proc) @counter.query_count end def supports_block_expectations? true end end
RSpec::Matchers.define :perform_queries do |expected| supports_block_expectations match do |block| query_count(&block) == expected end failure_message do |actual| "Expected to run #{expected} queries, got #{@counter.query_count}" end def query_count(&block) @counter = ActiveRecord::QueryCounter.new ActiveSupport::Notifications.subscribed(@counter.to_proc, 'sql.active_record', &block) @counter.query_count end end
Revert "update cocoapods to 2.0.4"
Pod::Spec.new do |spec| # Node was taken, so using NodeCocoapods here ... we'll see how that works # in code do `#if COCOAPODS` to use correct import spec.name = 'NodeCocoapods' spec.version = '2.0.4' spec.license = 'MIT' spec.homepage = 'https://github.com/vapor/node' spec.authors = { 'Vapor' => 'contact@vapor.codes' } spec.summary = 'A formatted data encapsulation meant to facilitate the transformation from one object to another.' spec.source = { :git => "#{spec.homepage}.git", :tag => "#{spec.version}" } spec.ios.deployment_target = "8.0" spec.osx.deployment_target = "10.10" spec.watchos.deployment_target = "2.0" spec.tvos.deployment_target = "9.0" spec.requires_arc = true spec.social_media_url = 'https://twitter.com/codevapor' spec.default_subspec = "Default" spec.subspec "Default" do |ss| ss.source_files = 'Sources/**/*.{swift}' ss.dependency 'Core', '~> 2.0' ss.dependency 'Bits', '~> 1.0' ss.dependency 'Debugging', '~> 1.0' end end
Pod::Spec.new do |spec| # Node was taken, so using NodeCocoapods here ... we'll see how that works # in code do `#if COCOAPODS` to use correct import spec.name = 'NodeCocoapods' spec.version = '2.0.3' spec.license = 'MIT' spec.homepage = 'https://github.com/vapor/node' spec.authors = { 'Vapor' => 'contact@vapor.codes' } spec.summary = 'A formatted data encapsulation meant to facilitate the transformation from one object to another.' spec.source = { :git => "#{spec.homepage}.git", :tag => "#{spec.version}" } spec.ios.deployment_target = "8.0" spec.osx.deployment_target = "10.10" spec.watchos.deployment_target = "2.0" spec.tvos.deployment_target = "9.0" spec.requires_arc = true spec.social_media_url = 'https://twitter.com/codevapor' spec.default_subspec = "Default" spec.subspec "Default" do |ss| ss.source_files = 'Sources/**/*.{swift}' ss.dependency 'Core', '~> 2.0' ss.dependency 'Bits', '~> 1.0' ss.dependency 'Debugging', '~> 1.0' end end
Add test for checking interchangeability between KubernetesService and Clusters::Platform::Kubernetes
require 'spec_helper' feature 'Interchangeability between KubernetesService and Platform::Kubernetes' do let!(:project) { create(:project, :repository) } EXCEPT_METHODS = %i[test title description help fields initialize_properties namespace namespace= api_url api_url=] EXCEPT_METHODS_GREP_V = %w[_touched? _changed? _was] it 'Clusters::Platform::Kubernetes covers core interfaces in KubernetesService' do expected_interfaces = KubernetesService.instance_methods(false) expected_interfaces = expected_interfaces - EXCEPT_METHODS EXCEPT_METHODS_GREP_V.each do |g| expected_interfaces = expected_interfaces.grep_v(/#{Regexp.escape(g)}\z/) end expect(expected_interfaces - Clusters::Platforms::Kubernetes.instance_methods).to be_empty end shared_examples 'selects kubernetes instance' do context 'when user configured kubernetes from Integration > Kubernetes' do let!(:kubernetes_service) { create(:kubernetes_service, project: project) } it { is_expected.to eq(kubernetes_service) } end context 'when user configured kubernetes from CI/CD > Clusters' do let!(:cluster) { create(:cluster, :provided_by_gcp, projects: [project]) } let(:platform_kubernetes) { cluster.platform_kubernetes } it { is_expected.to eq(platform_kubernetes) } end end describe 'Project#deployment_service' do subject { project.deployment_service } it_behaves_like 'selects kubernetes instance' end describe 'Project#kubernetes_service' do subject { project.kubernetes_service } it_behaves_like 'selects kubernetes instance' end end
Use full constant name in ElementToPage join model
# frozen_string_literal: true module Alchemy class ElementToPage def self.table_name [Element.table_name, Page.table_name].join('_') end end end
# frozen_string_literal: true module Alchemy class ElementToPage def self.table_name [Alchemy::Element.table_name, Alchemy::Page.table_name].join('_') end end end
Add support for php on redhat/centos/fedora.
# # Cookbook Name:: apache2 # Recipe:: php5 # # Copyright 2008, OpsCode, 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. # case node[:platform] when "debian", "ubuntu" package "libapache2-mod-php5" do action :install end end apache_module "php5"
# # Cookbook Name:: apache2 # Recipe:: php5 # # Copyright 2008, OpsCode, 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. # case node[:platform] when "debian", "ubuntu" package "libapache2-mod-php5" do action :install end when "centos", "redhat", "fedora" package "php" do action :install end end apache_module "php5"
Add depends for include_recipe working with testkitchen
name "ossec" maintainer "Joshua Timberman" maintainer_email "cookbooks@housepub.org" license "Apache 2.0" description "Installs/Configures ossec" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "1.0.5" depends "build-essential" %w{ debian ubuntu arch redhat centos fedora }.each do |os| supports os end
name "ossec" maintainer "Joshua Timberman" maintainer_email "cookbooks@housepub.org" license "Apache 2.0" description "Installs/Configures ossec" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "1.0.5" %w{ build-essential apt apache2 }.each do |pkg| depends pkg end %w{ debian ubuntu arch redhat centos fedora }.each do |os| supports os end
Update PhpStorm EAP Cask to v139.1226
cask :v1 => 'phpstorm-eap' do version '139.873' sha256 '8405a198ee9720e05f0b589367514ae4b86bb28064cd7d2a9cc9a015b30a53c3' url "http://download.jetbrains.com/webide/PhpStorm-EAP-#{version}.dmg" homepage 'http://confluence.jetbrains.com/display/PhpStorm/PhpStorm+Early+Access+Program' license :commercial app 'PhpStorm EAP.app' postflight do plist_set(':JVMOptions:JVMVersion', '1.6+') end zap :delete => [ '~/Library/Application Support/WebIde80', '~/Library/Preferences/WebIde80', '~/Library/Preferences/com.jetbrains.PhpStorm.plist', ] end
cask :v1 => 'phpstorm-eap' do version '139.1226' sha256 '7f9e55d3f5070fb5869eb7053566f21067600d11f93435074fad9cf399ea1626' url "http://download.jetbrains.com/webide/PhpStorm-EAP-#{version}.dmg" homepage 'http://confluence.jetbrains.com/display/PhpStorm/PhpStorm+Early+Access+Program' license :commercial app 'PhpStorm EAP.app' postflight do plist_set(':JVMOptions:JVMVersion', '1.6+') end zap :delete => [ '~/Library/Application Support/WebIde80', '~/Library/Preferences/WebIde80', '~/Library/Preferences/com.jetbrains.PhpStorm.plist', ] end
Fix exception notifier: load local settings befor app initialized.
# Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application Clockingit::Application.initialize! require File.expand_path('../environment.local.rb', __FILE__) if File.exist?(File.expand_path('../environment.local.rb', __FILE__))
# Load the rails application require File.expand_path('../application', __FILE__) require File.expand_path('../environment.local.rb', __FILE__) if File.exist?(File.expand_path('../environment.local.rb', __FILE__)) # Initialize the rails application Clockingit::Application.initialize!
Add missing stanzas to Adium Nightly15
cask :v1 => 'adium-nightly15' do version '1.5.11b2r5922' sha256 '828c2e2f21a2e500aeb580d018afba0f360956334d655a8280d4f9ba09af7b9d' url "http://nightly.adium.im/adium-adium-1.5.11/Adium_#{version}.dmg" homepage 'http://nightly.adium.im/?repo_branch=adium-adium-1.5.11' license :oss app 'Adium.app' end
cask :v1 => 'adium-nightly15' do version '1.5.11b2r5922' sha256 '828c2e2f21a2e500aeb580d018afba0f360956334d655a8280d4f9ba09af7b9d' url "http://nightly.adium.im/adium-adium-1.5.11/Adium_#{version}.dmg" name 'Adium' homepage 'http://nightly.adium.im/?repo_branch=adium-adium-1.5.11' license :gpl app 'Adium.app' zap :delete => [ '~/Library/Caches/Adium', '~/Library/Caches/com.adiumX.adiumX', '~/Library/Preferences/com.adiumX.adiumX.plist', ] end
Update Apache HTTP Server documentation (2.4.20)
module Docs class Apache < UrlScraper self.name = 'Apache HTTP Server' self.slug = 'apache_http_server' self.type = 'apache' self.release = '2.4.18' self.base_url = 'http://httpd.apache.org/docs/2.4/en/' self.links = { home: 'http://httpd.apache.org/' } html_filters.push 'apache/clean_html', 'apache/entries' options[:container] = '#page-content' options[:skip] = %w( upgrading.html license.html sitemap.html glossary.html mod/quickreference.html mod/directive-dict.html mod/directives.html mod/module-dict.html programs/other.html) options[:skip_patterns] = [ /\A(da|de|en|es|fr|ja|ko|pt-br|tr|zh-cn)\//, /\Anew_features/, /\Adeveloper\// ] options[:attribution] = <<-HTML &copy; 2016 The Apache Software Foundation<br> Licensed under the Apache License, Version 2.0. HTML end end
module Docs class Apache < UrlScraper self.name = 'Apache HTTP Server' self.slug = 'apache_http_server' self.type = 'apache' self.release = '2.4.20' self.base_url = 'https://httpd.apache.org/docs/2.4/en/' self.links = { home: 'https://httpd.apache.org/' } html_filters.push 'apache/clean_html', 'apache/entries' options[:container] = '#page-content' options[:skip] = %w( upgrading.html license.html sitemap.html glossary.html mod/quickreference.html mod/directive-dict.html mod/directives.html mod/module-dict.html programs/other.html) options[:skip_patterns] = [ /\A(da|de|en|es|fr|ja|ko|pt-br|tr|zh-cn)\//, /\Anew_features/, /\Adeveloper\// ] options[:attribution] = <<-HTML &copy; 2016 The Apache Software Foundation<br> Licensed under the Apache License, Version 2.0. HTML end end
Make sure raw emails are loaded before running integration spec
# -*- coding: utf-8 -*- require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe RequestController, "when classifying an information request" do describe 'when the request is internal' do before(:each) do @dog_request = info_requests(:fancy_dog_request) # This should happen automatically before each test but doesn't with these integration # tests for some reason. ActionMailer::Base.deliveries = [] end describe 'when logged in as the requestor' do before :each do @request_owner = @dog_request.user visit signin_path fill_in "Your e-mail:", :with => @request_owner.email fill_in "Password:", :with => "jonespassword" click_button "Sign in" end it "should send an email including the message" do visit describe_state_message_path(:url_title => @dog_request.url_title, :described_state => "requires_admin") fill_in "Please tell us more:", :with => "Okay. I don't quite understand." click_button "Submit status and send message" response.should contain "Thank you! We'll look into what happened and try and fix it up." deliveries = ActionMailer::Base.deliveries deliveries.size.should == 1 mail = deliveries[0] mail.body.should =~ /as needing admin/ mail.body.should =~ /Okay. I don't quite understand./ end end end end
# -*- coding: utf-8 -*- require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe RequestController, "when classifying an information request" do describe 'when the request is internal' do before(:each) do load_raw_emails_data @dog_request = info_requests(:fancy_dog_request) # This should happen automatically before each test but doesn't with these integration # tests for some reason. ActionMailer::Base.deliveries = [] end describe 'when logged in as the requestor' do before :each do @request_owner = @dog_request.user visit signin_path fill_in "Your e-mail:", :with => @request_owner.email fill_in "Password:", :with => "jonespassword" click_button "Sign in" end it "should send an email including the message" do visit describe_state_message_path(:url_title => @dog_request.url_title, :described_state => "requires_admin") fill_in "Please tell us more:", :with => "Okay. I don't quite understand." click_button "Submit status and send message" response.should contain "Thank you! We'll look into what happened and try and fix it up." deliveries = ActionMailer::Base.deliveries deliveries.size.should == 1 mail = deliveries[0] mail.body.should =~ /as needing admin/ mail.body.should =~ /Okay. I don't quite understand./ end end end end
Update xACT 2.28 to 2.29
class Xact < Cask url 'http://xact.scottcbrown.org/xACT2.28.zip' homepage 'http://xact.scottcbrown.org' version '2.28' sha256 '0296e366f6b7f0a35ef6d1707695b67b8299efa678071f82a877000f4587d3d3' link 'xACT 2.28/xACT.app' end
class Xact < Cask url 'http://xact.scottcbrown.org/xACT2.29.zip' homepage 'http://xact.scottcbrown.org' version '2.29' sha256 'bc8805f94b9f2320da64ca23b53e1b029fd65920ded2bc56c0291f0a73866674' link 'xACT 2.29/xACT.app' end
Allow specifying custom gems for jruby.
ENV['PATH'] = "#{ENV['PATH']}:/opt/jruby/bin" include_recipe "java" package "libjffi-jni" do action :install end remote_file "/var/tmp/#{node[:jruby][:deb]}" do source node[:jruby][:deb_url] end dpkg_package "/var/tmp/#{node[:jruby][:deb]}" do action :install end %w{rake bundler}.each do |gem| gem_package gem do gem_binary "/opt/jruby/bin/jgem" action :install end end
ENV['PATH'] = "#{ENV['PATH']}:/opt/jruby/bin" include_recipe "java" package "libjffi-jni" do action :install end remote_file "/var/tmp/#{node[:jruby][:deb]}" do source node[:jruby][:deb_url] end dpkg_package "/var/tmp/#{node[:jruby][:deb]}" do action :install end (node[:jruby][:gems] || %w{rake bundler}).each do |gem| gem_package gem do gem_binary "/opt/jruby/bin/jgem" action :install options "--no-ri --no-rdoc" end end
Update Opera developer to 29.0.1781.0
cask :v1 => 'opera-developer' do version '28.0.1750.5' sha256 '323d8a24b6afd63fba8c0d17a6e810cc4cfd454df488499a395bf0ff70421335' url "http://get.geo.opera.com/pub/opera-developer/#{version}/mac/Opera_Developer_#{version}_Setup.dmg" homepage 'http://www.opera.com/developer' license :unknown app 'Opera Developer.app' end
cask :v1 => 'opera-developer' do version '29.0.1781.0' sha256 'b3b24c1456722318eea3549169af43f268ccc0f015d3a8ad739bbe2c57a42d26' url "http://get.geo.opera.com/pub/opera-developer/#{version}/mac/Opera_Developer_#{version}_Setup.dmg" homepage 'http://www.opera.com/developer' license :unknown app 'Opera Developer.app' end
Add regex to address on artist controller
class ArtistsController < ApplicationController include ArtistsHelper def index @artists = Artist.all @organization = Organization.find_by(id: session[:organization_id]) end def user_location end def local_artists @artists = Artist.near([params[:lat], params[:lng]], 5) end def show @artist = Artist.find(params[:id]) @pieces = @artist.pieces @citystate = @artist.address.scan(/(.+?),\s*(.+?)(?:,\s|\s\s)(.+?)\s(\d{5})/) @location= @citystate[0][1] + ", " + @citystate[0][2] end def new @artist = Artist.new end def create @artist = Artist.new(artist_params) if @artist.save redirect_to artist_path(@artist) else render 'new' end end def edit @artist = Artist.find_by(id: params[:id]) end def update @artist = Artist.find_by(id: params[:id]) if @artist.update(artist_params) redirect_to artist_path else render 'edit' end end def destroy @artist = Artist.find_by(id: params[:id]) @artist.destroy redirect_to root_path end private def artist_params params.require(:artist).permit(:name, :email, :password, :address, :facebook, :twitter, :website, :bio, :avatar) end end
class ArtistsController < ApplicationController include ArtistsHelper def index @artists = Artist.all @organization = Organization.find_by(id: session[:organization_id]) end def user_location end def local_artists @artists = Artist.near([params[:lat], params[:lng]], 5) end def show @artist = Artist.find_by(id: params[:id]) @pieces = @artist.pieces @citystate = @artist.address.scan(/(.+?),\s*(.+?)(?:,\s|\s\s)(.+?)\s(\d{5})/) @location= @citystate[0][1] + ", " + @citystate[0][2] end def new @artist = Artist.new end def create @artist = Artist.new(artist_params) if @artist.save redirect_to artist_path(@artist) else render 'new' end end def edit @artist = Artist.find_by(id: params[:id]) end def update @artist = Artist.find_by(id: params[:id]) if @artist.update(artist_params) redirect_to artist_path else render 'edit' end end def destroy @artist = Artist.find_by(id: params[:id]) @artist.destroy redirect_to root_path end private def artist_params params.require(:artist).permit(:name, :email, :password, :address, :facebook, :twitter, :website, :bio, :avatar) end end
Add test to illustrate TIFF bug
require "spec_helper" describe VIPS::Writer do before :all do @image = simg 'wagon.v' @writer = VIPS::Writer.new(@image) @path = tmp('wagon.ppm').to_s end before :each do File.unlink @path if File.exists?(@path) end it "should write an arbitrary file" do @writer.write @path File.exists?(@path).should be_true im = VIPS::Image.new @path im.should match_image(@image) end it "should write through the image class" do @image.write @path File.exists?(@path).should be_true im = VIPS::Image.new @path im.should match_image(@image) end it "should create a generic writer" do @writer.class.should == VIPS::Writer @writer.image.should == @image end end
require "spec_helper" describe VIPS::Writer do before :all do @image = simg 'wagon.v' @writer = VIPS::Writer.new(@image) @path = tmp('wagon.ppm').to_s end before :each do File.unlink @path if File.exists?(@path) end it "should write an arbitrary file" do @writer.write @path File.exists?(@path).should be_true im = VIPS::Image.new @path im.should match_image(@image) end it "should write through the image class" do @image.write @path File.exists?(@path).should be_true im = VIPS::Image.new @path im.should match_image(@image) end it "should create a generic writer" do @writer.class.should == VIPS::Writer @writer.image.should == @image end it "should write a tiled TIFF" do @tiff_out = tmp('temp.tiff').to_s File.unlink(@tiff_out) if File.exists?(@tiff_out) @image.tiff(@tiff_out, :layout => :tile) end end
Upgrade IntelliJ Idea EAP to v139.872.1
cask :v1 => 'intellij-idea-eap' do version '139.791.2' sha256 'bb9859ab068360cefe2351c84b3c96653c7395351102e4ab03f2b7834753c0cb' url "http://download-cf.jetbrains.com/idea/ideaIU-#{version}.dmg" homepage 'https://confluence.jetbrains.com/display/IDEADEV/IDEA+14+EAP' license :commercial app 'IntelliJ IDEA 14 EAP.app' end
cask :v1 => 'intellij-idea-eap' do version '139.872.1' sha256 'f9ea80b72d0d1aa78685cda89eb6e7a1719636901957193b167fb884e40e47c4' url "http://download-cf.jetbrains.com/idea/ideaIU-#{version}.dmg" homepage 'https://confluence.jetbrains.com/display/IDEADEV/IDEA+14+EAP' license :commercial app 'IntelliJ IDEA 14 EAP.app' postflight do plist_set(':JVMOptions:JVMVersion', '1.6+') end zap :delete => [ '~/Library/Application Support/IntelliJIdea14', '~/Library/Preferences/IntelliJIdea14', ] end
Update IntelliJ IDEA EAP to version 141.104.1 (14.1)
cask :v1 => 'intellij-idea-eap' do version '141.2.2' sha256 '7701e4805f9cd5e93391d148991b86c1292c6ddc919251088eb6726de70b6384' url "http://download-cf.jetbrains.com/idea/ideaIU-#{version}.dmg" homepage 'https://confluence.jetbrains.com/display/IDEADEV/IDEA+14.1+EAP' license :commercial app 'IntelliJ IDEA 14 EAP.app' postflight do plist_set(':JVMOptions:JVMVersion', '1.6+') end zap :delete => [ '~/Library/Application Support/IntelliJIdea14', '~/Library/Preferences/IntelliJIdea14', ] end
cask :v1 => 'intellij-idea-eap' do version '141.104.1' sha256 'a59b096cbf012f42dbaf108026de12fa1a3caf16a0f87cbc5f20aa44fa2f2156' url "http://download-cf.jetbrains.com/idea/ideaIU-#{version}.dmg" homepage 'https://confluence.jetbrains.com/display/IDEADEV/IDEA+14.1+EAP' license :commercial app 'IntelliJ IDEA 14 EAP.app' postflight do plist_set(':JVMOptions:JVMVersion', '1.6+') end zap :delete => [ '~/Library/Application Support/IntelliJIdea14', '~/Library/Preferences/IntelliJIdea14', ] end
Extend tests for delete branch service
require 'spec_helper' describe DeleteBranchService, services: true do let(:project) { create(:project) } let(:user) { create(:user) } let(:service) { described_class.new(project, user) } describe '#execute' do let(:result) { service.execute('feature') } context 'when user has access to push to repository' do before do project.team << [user, :developer] end it 'removes the branch' do expect(result[:status]).to eq :success end end context 'when user does not have access to push to repository' do it 'does not remove branch' do expect(result[:status]).to eq :error expect(result[:message]).to eq 'You dont have push access to repo' end end end end
require 'spec_helper' describe DeleteBranchService, services: true do let(:project) { create(:project) } let(:repository) { project.repository } let(:user) { create(:user) } let(:service) { described_class.new(project, user) } describe '#execute' do context 'when user has access to push to repository' do before do project.team << [user, :developer] end it 'removes the branch' do expect(branch_exists?('feature')).to be true result = service.execute('feature') expect(result[:status]).to eq :success expect(branch_exists?('feature')).to be false end end context 'when user does not have access to push to repository' do it 'does not remove branch' do expect(branch_exists?('feature')).to be true result = service.execute('feature') expect(result[:status]).to eq :error expect(result[:message]).to eq 'You dont have push access to repo' expect(branch_exists?('feature')).to be true end end end def branch_exists?(branch_name) repository.ref_exists?("refs/heads/#{branch_name}") end end
Fix tokens having no scope
require "github_dash/version" require "github_dash/repository" require "github_dash/data_depository" require "octokit" module GithubDash # Fetch repository information given a reposoitory name def self.fetch_repository(repository_name) Repository.new repository_name end # Add a repository to the list of followed repositories def self.add_repo_to_following(name) # Make sure the repository exists in github Repository.new(name) DataDepository.add_repo name end # Remove a repository from the list of followed repositories def self.remove_repo_from_following(name) # Tell the user whether it removed a repo or not DataDepository.remove_repo name end # Get an array of the names of followed repositories def self.get_following DataDepository.get_following end # Save a user's token for getting private repositories def self.add_user(username, password) # Create new token client = Octokit::Client.new :login => username, :password => password token = client.create_authorization(:note => "github-dash token").token # Save it DataDepository.save_token(token) end # Get either an Octokit::Client if a token has been saved, # or nil if one hasn't. def self.get_client # Return nil if no token has been saved nil if DataDepository.get_token.nil? # Return new client Octokit::Client.new(:access_token => DataDepository.get_token) end end
require "github_dash/version" require "github_dash/repository" require "github_dash/data_depository" require "octokit" module GithubDash # Fetch repository information given a reposoitory name def self.fetch_repository(repository_name) Repository.new repository_name end # Add a repository to the list of followed repositories def self.add_repo_to_following(name) # Make sure the repository exists in github Repository.new(name) DataDepository.add_repo name end # Remove a repository from the list of followed repositories def self.remove_repo_from_following(name) # Tell the user whether it removed a repo or not DataDepository.remove_repo name end # Get an array of the names of followed repositories def self.get_following DataDepository.get_following end # Save a user's token for getting private repositories def self.add_user(username, password) # Create new token client = Octokit::Client.new :login => username, :password => password token = client.create_authorization(:scopes => ["repo"], :note => "github-dash token").token # Save it DataDepository.save_token(token) end # Get either an Octokit::Client if a token has been saved, # or nil if one hasn't. def self.get_client # Return nil if no token has been saved nil if DataDepository.get_token.nil? # Return new client Octokit::Client.new(:access_token => DataDepository.get_token) end end
Add a doc comment to ReactionEvent
# frozen_string_literal: true require 'discordrb/events/generic' require 'discordrb/data' module Discordrb::Events class ReactionEvent end end
# frozen_string_literal: true require 'discordrb/events/generic' require 'discordrb/data' module Discordrb::Events # Generic superclass for events about adding and removing reactions class ReactionEvent end end
Update sugarable spec to check ancestors instead
require 'spec_helper' module Omnibus describe Software do it 'is a sugarable' do expect(subject).to be_a(Sugarable) end end describe Project do it 'is a sugarable' do expect(subject).to be_a(Sugarable) end end describe Sugarable do context 'in a cleanroom' do let(:klass) do Class.new do include Cleanroom include Sugarable end end let(:instance) { klass.new } before { stub_ohai(platform: 'ubuntu') } it 'includes the DSL methods' do expect(klass).to be_method_defined(:windows?) expect(klass).to be_method_defined(:vagrant?) expect(klass).to be_method_defined(:_64_bit?) end it 'makes the DSL methods available in the cleanroom' do expect { instance.evaluate <<-EOH.gsub(/^ {12}/, '') windows? vagrant? EOH }.to_not raise_error end end end end
require 'spec_helper' module Omnibus describe Software do it 'is a sugarable' do expect(described_class.ancestors).to include(Sugarable) end end describe Project do it 'is a sugarable' do expect(described_class.ancestors).to include(Sugarable) end end describe Sugarable do context 'in a cleanroom' do let(:klass) do Class.new do include Cleanroom include Sugarable end end let(:instance) { klass.new } before { stub_ohai(platform: 'ubuntu') } it 'includes the DSL methods' do expect(klass).to be_method_defined(:windows?) expect(klass).to be_method_defined(:vagrant?) expect(klass).to be_method_defined(:_64_bit?) end it 'makes the DSL methods available in the cleanroom' do expect { instance.evaluate <<-EOH.gsub(/^ {12}/, '') windows? vagrant? EOH }.to_not raise_error end end end end
Use binary for homebrew recipe
require 'formula' class Gh < Formula VERSION = '0.7.0' homepage 'https://github.com/jingweno/gh' url "https://github.com/jingweno/gh/archive/#{VERSION}.tar.gz" sha1 '1e4ca70ebf018ae192a641f18b735beca5df5c31' version VERSION head 'https://github.com/jingweno/gh.git' depends_on 'hg' depends_on 'go' def install go_path = Dir.getwd system "GOPATH='#{go_path}' go get -d ./..." system "GOPATH='#{go_path}' go build -o gh" bin.install 'gh' end def caveats; <<-EOS.undent To upgrade gh, run `brew upgrade https://raw.github.com/jingweno/gh/master/homebrew/gh.rb` More information here: https://github.com/jingweno/gh/blob/master/README.md EOS end test do assert_equal VERSION, `#{bin}/gh version`.split.last end end
require 'formula' class Gh < Formula VERSION = '0.7.0' ARCH = if MacOS.prefer_64_bit? 'amd64' else '386' end homepage 'https://github.com/jingweno/gh' head 'https://github.com/jingweno/gh.git' url "https://dl.dropboxusercontent.com/u/1079131/gh/#{VERSION}-snapshot/darwin_#{ARCH}/gh_#{VERSION}-snapshot_darwin_#{ARCH}.tar.gz" version VERSION def install bin.install 'gh' end def caveats; <<-EOS.undent To upgrade gh, run `brew upgrade https://raw.github.com/jingweno/gh/master/homebrew/gh.rb` More information here: https://github.com/jingweno/gh/blob/master/README.md EOS end test do assert_equal VERSION, `#{bin}/gh version`.split.last end end
Fix library load gem issue
require 'open-uri' require 'open_uri_redirections' require 'openssl' require 'digest' module JavaSE class <<self def download(url, file, limit = 5) raise ArgumentError, 'too many download failures' if limit == 0 uri = URI(url) begin open(uri, 'Cookie' => 'oraclelicense=accept-securebackup-cookie', allow_redirections: :all, ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE) do |fin| open(file, 'w') do |fout| while (buf = fin.read(8192)) fout.write buf end end end rescue download(url, file, limit - 1) end end def valid?(file, checksum) sha256 = Digest::SHA256.file file sha256.hexdigest == checksum end def validate(file, checksum) raise "#{file} does not match checksum #{checksum}" unless valid?(file, checksum) end end end
require 'open-uri' require 'openssl' require 'digest' module JavaSE class <<self def load_open_uri_redirections # Libraries are loaded before recipes are compiled, so you can't install gems for direct use by libraries. require 'open_uri_redirections' end def download(url, file, limit = 5) raise ArgumentError, 'too many download failures' if limit == 0 load_open_uri_redirections uri = URI(url) begin open(uri, 'Cookie' => 'oraclelicense=accept-securebackup-cookie', allow_redirections: :all, ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE) do |fin| open(file, 'wb') do |fout| while (buf = fin.read(8192)) fout.write buf end end end rescue download(url, file, limit - 1) end end def valid?(file, checksum) sha256 = Digest::SHA256.file file sha256.hexdigest == checksum end def validate(file, checksum) raise "#{File.basename(file)} does not match checksum #{checksum}" unless valid?(file, checksum) end end end