Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Return empty string rather than nil for path prefix
require "given_filesystem/spec_helpers" include GivenFilesystemSpecHelpers def setup_test_git_repo(version, dir) tarball = "spec/data/red_herring-#{version}.tar.gz" tarball_path = File.expand_path(tarball) if !system("cd #{dir}; tar xzf #{tarball_path}") raise "Unable to extract tarball #{tarball}" end end def path_prefix /darwin/ =~ RUBY_PLATFORM ? '/private' : nil end
require "given_filesystem/spec_helpers" include GivenFilesystemSpecHelpers def setup_test_git_repo(version, dir) tarball = "spec/data/red_herring-#{version}.tar.gz" tarball_path = File.expand_path(tarball) if !system("cd #{dir}; tar xzf #{tarball_path}") raise "Unable to extract tarball #{tarball}" end end def path_prefix /darwin/ =~ RUBY_PLATFORM ? '/private' : '' end
Fix slashes and spacing issue for system call for Run worker thread
module WatirRobotGui module Worker class RunButton < javax.swing.SwingWorker attr_accessor :status_bar, :test_path def doInBackground self.status_bar.text = "Running tests. Wait until all browsers have closed." # Ensure the parameter to -d below is a directory if File.directory? self.test_path output_path = self.test_path else output_path = File.dirname(self.test_path) end # Don't know if/how we can start RF tests via a class, # so for now we're just running it command-line style rf_jar = 'lib/standalone/robotframework.jar' # @TODO get some kind of logging in place results = IO.popen("java -jar #{rf_jar} -T -d #{output_path} #{self.test_path}") end end end end
module WatirRobotGui module Worker class RunButton < javax.swing.SwingWorker attr_accessor :status_bar, :test_path def doInBackground self.status_bar.text = "Running tests. Wait until all browsers have closed." self.test_path = self.test_path.gsub('\\', '/') # Ensure the parameter to -d below is a directory if File.directory? self.test_path output_path = self.test_path else output_path = File.dirname(self.test_path) end # Don't know if/how we can start RF tests via a class, # so for now we're just running it command-line style rf_jar = 'lib/standalone/robotframework.jar' # @TODO get some kind of logging in place results = IO.popen("java -jar #{rf_jar} -T -d \"#{output_path}\" \"#{self.test_path}\"") end end end end
Remove method_missing and dynamically create methods
require 'mongoid' module Mongoid module AppSettings extend ActiveSupport::Concern class Record #:nodoc: include Mongoid::Document identity :type => String store_in :settings end module ClassMethods # Defines a setting. Options can include: # # * default -- Specify a default value # # Example usage: # # class MySettings # include Mongoid::AppSettings # setting :organization_name, :default => "demo" # end def setting(name, options = {}) settings[name.to_s] = options end # Force a reload from the database def reload @record = nil end protected def method_missing(name, *args, &block) # :nodoc: if name.to_s =~ /^(.*)=$/ and setting_defined?($1) self[$1] = args[0] elsif setting_defined?(name.to_s) self[name.to_s] else super end end def settings # :nodoc: @settings ||= {} end def setting_defined?(name) # :nodoc: settings.include?(name) end def record # :nodoc: return @record if @record @record = Record.find_or_create_by(:id => "settings") end def [](name) # :nodoc: if record.attributes.include?(name) record.read_attribute(name) else settings[name][:default] end end def []=(name, value) # :nodoc: record.set(name, value) end end end end
require 'mongoid' module Mongoid module AppSettings extend ActiveSupport::Concern included do |base| @base = base end class Record #:nodoc: include Mongoid::Document identity :type => String store_in :settings end module ClassMethods # Defines a setting. Options can include: # # * default -- Specify a default value # # Example usage: # # class MySettings # include Mongoid::AppSettings # setting :organization_name, :default => "demo" # end def setting(name, options = {}) settings[name.to_s] = options @base.class.class_eval do define_method(name.to_s) do @base[name.to_s] end define_method(name.to_s + "=") do |value| @base[name.to_s] = value end end end # Force a reload from the database def reload @record = nil end protected def settings # :nodoc: @settings ||= {} end def setting_defined?(name) # :nodoc: settings.include?(name) end def record # :nodoc: return @record if @record @record = Record.find_or_create_by(:id => "settings") end def [](name) # :nodoc: if record.attributes.include?(name) record.read_attribute(name) else settings[name][:default] end end def []=(name, value) # :nodoc: record.set(name, value) end end end end
Return error response when pattern is invalid
class Blueprint < ActiveRecord::Base belongs_to :project has_many :patterns, dependent: :destroy, inverse_of: :blueprint accepts_nested_attributes_for :patterns validates_presence_of :name, :project, :patterns validates :name, uniqueness: true validate do patterns.each(&:set_metadata_from_repository) unless patterns.any? { |pattern| pattern.type == 'platform' } errors.add(:patterns, 'don\'t contain platform pattern') end end before_create :set_consul_secret_key def set_consul_secret_key return unless CloudConductor::Config.consul.options.acl self.consul_secret_key ||= generate_consul_secret_key end def generate_consul_secret_key SecureRandom.base64(16) end def status pattern_states = patterns.map(&:status) if pattern_states.all? { |status| status == :CREATE_COMPLETE } :CREATE_COMPLETE elsif pattern_states.any? { |status| status == :ERROR } :ERROR else :PENDING end end def as_json(options = {}) super({ except: :consul_secret_key, methods: :status }.merge(options)) end end
class Blueprint < ActiveRecord::Base belongs_to :project has_many :patterns, dependent: :destroy, inverse_of: :blueprint accepts_nested_attributes_for :patterns validates_presence_of :name, :project, :patterns validates :name, uniqueness: true validate do begin patterns.each(&:set_metadata_from_repository) unless patterns.any? { |pattern| pattern.type == 'platform' } errors.add(:patterns, 'don\'t contain platform pattern') end rescue => e errors.add(:patterns, "is invalid(#{e.message})") end end before_create :set_consul_secret_key def set_consul_secret_key return unless CloudConductor::Config.consul.options.acl self.consul_secret_key ||= generate_consul_secret_key end def generate_consul_secret_key SecureRandom.base64(16) end def status pattern_states = patterns.map(&:status) if pattern_states.all? { |status| status == :CREATE_COMPLETE } :CREATE_COMPLETE elsif pattern_states.any? { |status| status == :ERROR } :ERROR else :PENDING end end def as_json(options = {}) super({ except: :consul_secret_key, methods: :status }.merge(options)) end end
Add automation engine service model for SwiftManager
module MiqAeMethodService class MiqAeServiceManageIQ_Providers_StorageManager_SwiftManager < MiqAeServiceManageIQ_Providers_StorageManager expose :parent_manager, :association => true expose :cloud_object_store_containers, :association => true expose :cloud_object_store_objects, :association => true end end
Remove date query from version collections
class ContractorsController < ApplicationController def index @contractors = Contractor.all.sort { |a, b| b.total_est_contract_value <=> a.total_est_contract_value } @contractor_history = PaperTrail::Version.where("created_at > ? and item_type = ? and event = ?", 2.week.ago, "Contractor", "create") @contract_history = PaperTrail::Version.where("created_at > ? and item_type = ? and event = ?", 2.week.ago, "Contract", "create") @days_with_changes = PaperTrail::Version.group_by_day(:created_at).keys.map{|k| k.to_date}.reverse end end
class ContractorsController < ApplicationController def index @contractors = Contractor.all.sort { |a, b| b.total_est_contract_value <=> a.total_est_contract_value } @contractor_history = PaperTrail::Version.where("item_type = ? and event = ?", "Contractor", "create") @contract_history = PaperTrail::Version.where("item_type = ? and event = ?", "Contract", "create") @days_with_changes = PaperTrail::Version.group_by_day(:created_at).keys.map{|k| k.to_date}.reverse end end
Change the invalid migration message to live in a method
describe "migration order" do let(:current_release_migrations) do File.read(File.join(__dir__, 'data/euwe_migrations')).split.map(&:to_i).sort end let(:migrations_now) do Dir.glob(File.join(Rails.root, "db/migrate/*.rb")).map do |f| File.basename(f, ".rb").split("_").first.to_i end.sort end let(:new_migrations) do migrations_now - current_release_migrations end let(:last_released_migration) do current_release_migrations.last end it "is correct" do incorrect_migration_time_stamps = [] new_migrations.each do |m| incorrect_migration_time_stamps << m if m < last_released_migration end expect(incorrect_migration_time_stamps).to be_empty, <<-EOS.gsub!(/^ +/, "") The following migration timestamps are too early to be included in the next release: #{incorrect_migration_time_stamps.join("\n")} These migrations must be regenerated so that they will run after the latest released migration, #{last_released_migration}. This is done to prevent schema differences between migrated databases and newly created ones where all the migrations are run in timestamp order. EOS end end
describe "migration order" do let(:current_release_migrations) do File.read(File.join(__dir__, 'data/euwe_migrations')).split.map(&:to_i).sort end let(:migrations_now) do Dir.glob(File.join(Rails.root, "db/migrate/*.rb")).map do |f| File.basename(f, ".rb").split("_").first.to_i end.sort end let(:new_migrations) do migrations_now - current_release_migrations end let(:last_released_migration) do current_release_migrations.last end def invalid_migrations_message(incorrect_migration_time_stamps, last_released_migration) <<-EOS The following migration timestamps are too early to be included in the next release: #{incorrect_migration_time_stamps.join("\n")} These migrations must be regenerated so that they will run after the latest released migration, #{last_released_migration}. This is done to prevent schema differences between migrated databases and newly created ones where all the migrations are run in timestamp order. EOS end it "is correct" do incorrect_migration_time_stamps = [] new_migrations.each do |m| incorrect_migration_time_stamps << m if m < last_released_migration end expect(incorrect_migration_time_stamps).to( be_empty, invalid_migrations_message(incorrect_migration_time_stamps, last_released_migration) ) end end
Mark args as non executable
module DeepCover class Node class Arg < Node has_child name: Symbol def executable? false end end Kwarg = Arg class Restarg < Node has_child name: [Symbol, nil] def executable? false end end Kwrestarg = Restarg class Optarg < Node has_tracker :default has_child name: Symbol has_child default: Node, flow_entry_count: :default_tracker_hits, rewrite: '(%{default_tracker};%{node})' def executable? false end end Kwoptarg = Optarg # foo(&block) class Blockarg < Node has_child name: Symbol def executable? false end # TODO end class Args < Node has_child arguments: [Arg, Optarg, Restarg, Kwarg, Kwoptarg, Kwrestarg, Blockarg], rest: true end end end
module DeepCover class Node class Arg < Node has_child name: Symbol def executable? false end end Kwarg = Arg class Restarg < Node has_child name: [Symbol, nil] def executable? false end end Kwrestarg = Restarg class Optarg < Node has_tracker :default has_child name: Symbol has_child default: Node, flow_entry_count: :default_tracker_hits, rewrite: '(%{default_tracker};%{node})' def executable? false end end Kwoptarg = Optarg # foo(&block) class Blockarg < Node has_child name: Symbol def executable? false end # TODO end class Args < Node has_child arguments: [Arg, Optarg, Restarg, Kwarg, Kwoptarg, Kwrestarg, Blockarg], rest: true def executable? false end end end end
Correct the require not to use relative path
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require File.expand_path('../lib/activesupport-db-cache', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Sergei O. Udalov"] gem.email = ["sergei.udalov@gmail.com"] gem.description = %q{ActiveRecord DB Store engine for ActiveSupport::Cache} gem.summary = %q{ActiveRecord DB Store engine for ActiveSupport::Cache} gem.homepage = "https://github.com/sergio-fry/activesupport-db-cache" 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 = "activesupport-db-cache" gem.require_paths = ["lib"] gem.version = ActiveSupport::Cache::ActiveRecordStore::VERSION gem.add_dependency "activesupport", ">=3.0.0" gem.add_dependency "activerecord", ">=3.0.0" gem.add_development_dependency "rspec" gem.add_development_dependency "sqlite3" gem.add_development_dependency "timecop" end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require 'activesupport-db-cache' Gem::Specification.new do |gem| gem.authors = ["Sergei O. Udalov"] gem.email = ["sergei.udalov@gmail.com"] gem.description = %q{ActiveRecord DB Store engine for ActiveSupport::Cache} gem.summary = %q{ActiveRecord DB Store engine for ActiveSupport::Cache} gem.homepage = "https://github.com/sergio-fry/activesupport-db-cache" 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 = "activesupport-db-cache" gem.require_paths = ["lib"] gem.version = ActiveSupport::Cache::ActiveRecordStore::VERSION gem.add_dependency "activesupport", ">=3.0.0" gem.add_dependency "activerecord", ">=3.0.0" gem.add_development_dependency "rspec" gem.add_development_dependency "sqlite3" gem.add_development_dependency "timecop" end
Add tests for sessions controller; all tests pass
require 'rails_helper' RSpec.describe SessionsController, type: :controller do let!(:user) { build(:user) } context "GET #new)" do it "responds successfully with an HTTP 200 status code" do get :new expect(response).to be_success expect(response).to have_http_status(200) end it "renders the login template" do get :new expect(response).to render_template("new") end end context "POST #create" do before(:each) { user.save } context "with valid attributes" do it "logs the user in" do post :create, params: { email: user.email, password: user.password } expect(session['user_id']).to eq user.id end it "redirects to the current user" do post :create, params: { email: user.email, password: user.password } expect(response).to redirect_to user end end context "with invalid attributes" do before(:each) { user.save } it "does not log the user in" do post :create, params: { email: "tj@momicello.com", password: user.password } expect(session['user_id']).to be nil end it "re-renders the new template" do post :create, params: { email: user.email, password: "1253sir3" } expect(response).to redirect_to '/login' end end end context "DELETE #destroy)" do before(:each) { user.save } it "redirects to /login" do delete :destroy expect(response).to redirect_to login_path end it "empties the sessions hash" do delete :destroy expect(session['user_id']).to be nil end end end
Put back rake task that was used in migration. Oops.
namespace :onebody do desc 'Move existing pictures and files to new locations for OneBody 2.0.0.' task :move_to_paperclip => :environment do require 'fileutils' paths = Dir[DB_PHOTO_PATH.join('**/*')].to_a + \ Dir[DB_ATTACHMENTS_PATH.join('**/*')].to_a paths.each_with_index do |path, index| if path =~ %r{db/photos} _, collection, id, _, env, size = path.match(%r{db/photos/(.+)/(\d+)(\.(test|development))?\.(tn|small|medium|large|full)\.jpg}).to_a next if size != 'full' attribute = 'photo' else _, collection, id, _, env, extension = path.match(%r{db/(.+)/(\d+)(\.(test|development))?\.(.+)$}).to_a attribute = 'file' end next if collection.nil? next if collection == 'recipes' klass = Object.const_get(collection.singularize.capitalize) env = 'production' if env.nil? next if Rails.env.to_s != env begin object = klass.unscoped { klass.find(id) } rescue ActiveRecord::RecordNotFound puts "Warning: #{klass.name} with id #{id} was not found." puts " This file/photo was not copied: #{path}" else object.send("#{attribute}=", File.open(path)) #klass.skip_callback :save do #object.save(:validate => false) #end #object.save_attached_files # manually update db so as to not trigger any callbacks Person.connection.execute("UPDATE #{collection} SET #{attribute}_updated_at='#{Time.now.utc}', #{attribute}_fingerprint='#{object.attributes[attribute + '_fingerprint']}', #{attribute}_file_size=#{object.attributes[attribute + '_file_size']}, #{attribute}_content_type='#{object.attributes[attribute + '_content_type']}', #{attribute}_file_name='#{object.attributes[attribute + '_file_name']}' WHERE id=#{object.id}") puts "Copied #{path} =>\n #{object.send(attribute).path}" end puts " #{index+1}/#{paths.length} complete." end if paths.any? puts puts "============================================================================" puts "Operation complete." puts "Please check that all photos and files are in place in public/system." puts "Then you can delete the db/photos and db/attachments dirs." puts "============================================================================" puts end end end
Use Celluloid::Group for defining the test node
# The DCell specs start a completely separate Ruby VM running this code # for complete integration testing using 0MQ over TCP require 'rubygems' require 'bundler' Bundler.setup require 'dcell' DCell.setup :id => 'test_node', :addr => 'tcp://127.0.0.1:21264' class TestActor include Celluloid attr_reader :value def initialize @value = 42 end def the_answer DCell::Global[:the_answer] end def crash raise "the spec purposely crashed me :(" end end class TestApplication < Celluloid::Application supervise DCell::Application supervise TestActor, :as => :test_actor end TestApplication.run
# The DCell specs start a completely separate Ruby VM running this code # for complete integration testing using 0MQ over TCP require 'rubygems' require 'bundler' Bundler.setup require 'dcell' DCell.setup :id => 'test_node', :addr => 'tcp://127.0.0.1:21264' class TestActor include Celluloid attr_reader :value def initialize @value = 42 end def the_answer DCell::Global[:the_answer] end def crash raise "the spec purposely crashed me :(" end end class TestGroup < Celluloid::Group supervise DCell::Group supervise TestActor, :as => :test_actor end TestGroup.run
Fix Story start date detection
module ActivePivot class Activity attr_accessor :remote_activity def initialize(remote_activity) self.remote_activity = remote_activity end def store story.update_attribute(:started_at, updated_at) if store? end private def store? started? && started_before?(updated_at) end def started_before?(updated_at) story.started_at.nil? || story.started_at < updated_at end def story @story ||= ActivePivot::Story.find_by_pivotal_id(story_id) end def started? current_state.present? && current_state == 'started' end def kind @kind ||= primary_resource['kind'] end def story_id @story_id ||= primary_resource['id'] end def current_state new_values.present? ? new_values['current_state'] : 'unstarted' end def updated_at @updated_at ||= new_values['updated_at'] end def primary_resource remote_activity.primary_resources[0] end def new_values remote_activity.changes[0]['new_values'] end end end
module ActivePivot class Activity attr_accessor :remote_activity def initialize(remote_activity) self.remote_activity = remote_activity end def store story.update_attribute(:started_at, updated_at) if store? end private def store? started? && started_before?(updated_at) end def started_before?(updated_at) story.started_at.nil? || story.started_at < updated_at end def story @story ||= ActivePivot::Story.find_by_pivotal_id(story_id) end def started? current_state.present? && current_state == 'started' end def kind @kind ||= primary_resource['kind'] end def story_id @story_id ||= primary_resource['id'] end def current_state new_values.present? ? new_values['current_state'] : 'unstarted' end def updated_at @updated_at ||= new_values['updated_at'] end def primary_resource remote_activity.primary_resources[0] end def new_values remote_activity.changes.each do |change| if change['new_values'] && change['new_values']['current_state'] return change['new_values'] end end return nil end end end
Define default attribute methods on Attributes::Base
module Aoede module Attributes # @abstract Include in any format specific module module Base extend ActiveSupport::Concern ATTRIBUTES = [:album, :artist, :comment, :genre, :title, :track, :year] MAPPING = Hash.new # @return [Hash] def attributes attrs = Hash.new self.singleton_class::ATTRIBUTES.each do |attribute| if value = send(attribute) attrs[attribute] = value end end attrs end end end end
module Aoede module Attributes # @abstract Include in any format specific module module Base extend ActiveSupport::Concern ATTRIBUTES = [:album, :artist, :comment, :genre, :title, :track_number, :release_date] MAPPING = Hash.new # @return [Hash] def attributes attrs = Hash.new self.singleton_class::ATTRIBUTES.each do |attribute| if value = send(attribute) attrs[attribute] = value end end attrs end # @param method_name [Symbol, String] # @param method [Symbol, String] def define_attribute_getter(method_name, method) define_method(method_name) do audio.tag.send(method) end end module_function :define_attribute_getter # @param method_name [Symbol, String] # @param method [Symbol, String] def define_attribute_setter(method_name, method) define_method("#{method_name}=") do |value| audio.tag.send("#{method}=", value) end end module_function :define_attribute_setter # Define module attributes getters and setters dynamically ATTRIBUTES.each do |method_name| mapping = { track_number: :track, release_date: :year } method = mapping[method_name] ? mapping[method_name] : method_name define_attribute_getter(method_name, method) define_attribute_setter(method_name, method) end end end end
Remove unused methods from InOutPointer
# frozen_string_literal: true module GirFFI # The InOutPointer class handles conversion between ruby types and # pointers for arguments with direction :inout and :out. # class InOutPointer < FFI::Pointer attr_reader :value_type def initialize(type, ptr) @value_type = type super ptr end def to_value case value_ffi_type when Module value_ffi_type.get_value_from_pointer(self, 0) when Symbol send("get_#{value_ffi_type}", 0) else raise NotImplementedError end end # Convert more fully to a ruby value than #to_value def to_ruby_value bare_value = to_value case value_type when :utf8 bare_value.to_utf8 when Array value_type[1].wrap bare_value when Class value_type.wrap bare_value else bare_value end end def clear put_bytes 0, "\x00" * value_type_size, 0, value_type_size end def self.allocate_new(type) ffi_type = TypeMap.type_specification_to_ffi_type type ptr = AllocationHelper.allocate_for_type(ffi_type) new type, ptr end private def value_ffi_type @value_ffi_type ||= TypeMap.type_specification_to_ffi_type value_type end def value_type_size @value_type_size ||= FFI.type_size value_ffi_type end end end
# frozen_string_literal: true module GirFFI # The InOutPointer class handles conversion between ruby types and # pointers for arguments with direction :inout and :out. # class InOutPointer < FFI::Pointer attr_reader :value_type def initialize(type, ptr) @value_type = type super ptr end def to_value case value_ffi_type when Module value_ffi_type.get_value_from_pointer(self, 0) when Symbol send("get_#{value_ffi_type}", 0) else raise NotImplementedError end end # Convert more fully to a ruby value than #to_value def to_ruby_value bare_value = to_value case value_type when :utf8 bare_value.to_utf8 when Array value_type[1].wrap bare_value when Class value_type.wrap bare_value else bare_value end end def self.allocate_new(type) ffi_type = TypeMap.type_specification_to_ffi_type type ptr = AllocationHelper.allocate_for_type(ffi_type) new type, ptr end private def value_ffi_type @value_ffi_type ||= TypeMap.type_specification_to_ffi_type value_type end end end
Make sure $MSPEC_DEBUG is initialized
class ExceptionState attr_reader :description, :describe, :it, :exception def initialize(state, location, exception) @exception = exception @description = location ? "An exception occurred during: #{location}" : "" if state @description += "\n" unless @description.empty? @description += state.description @describe = state.describe @it = state.it else @describe = @it = "" end end def failure? [SpecExpectationNotMetError, SpecExpectationNotFoundError].any? { |e| @exception.is_a? e } end def message if @exception.message.empty? "<No message>" elsif @exception.class == SpecExpectationNotMetError || @exception.class == SpecExpectationNotFoundError @exception.message else "#{@exception.class}: #{@exception.message}" end end def backtrace @backtrace_filter ||= MSpecScript.config[:backtrace_filter] begin bt = @exception.awesome_backtrace.show.split "\n" rescue Exception bt = @exception.backtrace || [] end bt.select { |line| $MSPEC_DEBUG or @backtrace_filter !~ line }.join("\n") end end
# Initialize $MSPEC_DEBUG $MSPEC_DEBUG = false unless defined?($MSPEC_DEBUG) class ExceptionState attr_reader :description, :describe, :it, :exception def initialize(state, location, exception) @exception = exception @description = location ? "An exception occurred during: #{location}" : "" if state @description += "\n" unless @description.empty? @description += state.description @describe = state.describe @it = state.it else @describe = @it = "" end end def failure? [SpecExpectationNotMetError, SpecExpectationNotFoundError].any? { |e| @exception.is_a? e } end def message if @exception.message.empty? "<No message>" elsif @exception.class == SpecExpectationNotMetError || @exception.class == SpecExpectationNotFoundError @exception.message else "#{@exception.class}: #{@exception.message}" end end def backtrace @backtrace_filter ||= MSpecScript.config[:backtrace_filter] begin bt = @exception.awesome_backtrace.show.split "\n" rescue Exception bt = @exception.backtrace || [] end bt.select { |line| $MSPEC_DEBUG or @backtrace_filter !~ line }.join("\n") end end
Check for symbols in YamlConfig as well
require 'psych' require 'pathname' module Sequelizer class YamlConfig attr_reader :config_file_path class << self def pwd new end def home new(Pathname.new("~") + ".config" + "sequelizer" + "database.yml") end end def initialize(config_file_path = nil) @config_file_path = Pathname.new(config_file_path || Pathname.pwd + "config" + "database.yml").expand_path end # Returns a set of options pulled from config/database.yml # or +nil+ if config/database.yml doesn't exist def options return {} unless config_file_path.exist? config['adapter'] ? config : config[environment] end # The environment to load from database.yml # # Searches the following environment variables in this order: # * SEQUELIZER_ENV # * RAILS_ENV # * RACK_ENV # # Lastly, if none of those environment variables are specified, the # environment defaults to 'development' def environment ENV['SEQUELIZER_ENV'] || ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development' end private # The config as read from config/database.yml def config @config ||= Psych.load_file(config_file_path) end end end
require 'psych' require 'pathname' module Sequelizer class YamlConfig attr_reader :config_file_path class << self def pwd new end def home new(Pathname.new("~") + ".config" + "sequelizer" + "database.yml") end end def initialize(config_file_path = nil) @config_file_path = Pathname.new(config_file_path || Pathname.pwd + "config" + "database.yml").expand_path end # Returns a set of options pulled from config/database.yml # or +nil+ if config/database.yml doesn't exist def options return {} unless config_file_path.exist? config['adapter'] || config[:adapter] ? config : config[environment] end # The environment to load from database.yml # # Searches the following environment variables in this order: # * SEQUELIZER_ENV # * RAILS_ENV # * RACK_ENV # # Lastly, if none of those environment variables are specified, the # environment defaults to 'development' def environment ENV['SEQUELIZER_ENV'] || ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development' end private # The config as read from config/database.yml def config @config ||= Psych.load_file(config_file_path) end end end
Add geminabox as a dev dependency
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "mailchimp/version" Gem::Specification.new do |s| s.name = "mailchimp" s.version = Mailchimp::VERSION s.authors = ["Chris Kelly"] s.email = ["chris@highgroove.com"] s.homepage = "" s.summary = %q{Mailchimp APIs in Ruby} s.description = %q{This provides Ruby access to (eventually) all of Mailchimp's APIs} s.rubyforge_project = "mailchimp" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_dependency('httparty') s.add_development_dependency('ruby-debug19') s.add_development_dependency('rake') s.add_development_dependency('shoulda') s.add_development_dependency('mocha') s.add_development_dependency('cover_me') s.add_development_dependency('fakeweb') end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "mailchimp/version" Gem::Specification.new do |s| s.name = "mailchimp" s.version = Mailchimp::VERSION s.authors = ["Chris Kelly"] s.email = ["chris@highgroove.com"] s.homepage = "" s.summary = %q{Mailchimp APIs in Ruby} s.description = %q{This provides Ruby access to (eventually) all of Mailchimp's APIs} s.rubyforge_project = "mailchimp" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_dependency('httparty') s.add_development_dependency('ruby-debug19') s.add_development_dependency('rake') s.add_development_dependency('shoulda') s.add_development_dependency('mocha') s.add_development_dependency('cover_me') s.add_development_dependency('fakeweb') s.add_development_dependency('geminabox') end
Add my initial pseudocode for 5.3
=begin # Calculate the mode Pairing Challenge # I worked on this challenge [by myself, with: ] # I spent [] hours on this challenge. # Complete each step below according to the challenge directions and # include it in this file. Also make sure everything that isn't code # is commented. # 0. Pseudocode # What is the input? - an array of fixed numbers or strings # What is the output? (i.e. What should the code return?) - an array of the most frequent values # What are the steps needed to solve the problem? CREATE a most_frequent array and set it equal to the array argument # 1. Initial Solution =end def mode(array) histogram = Hash.new array.each do |item| histogram[item] = 0 end array.each do |item| histogram[item] += 1 end histogram.each do |key, val| puts "#{key}:#{val}" end #NOW I WANT TO MOVE THE KEY(S) WITH THE HIGHEST VALUE(S) INTO AN ARRAY #THEN I WANT TO RETURN THAT ARRAY end # mode([1,2,3,3,-2,"cat", "dog", "cat"]) mode(["who", "what", "where", "who"]) # 3. Refactored Solution =begin # 4. Reflection Which data structure did you and your pair decide to implement and why? Were you more successful breaking this problem down into implementable pseudocode than the last with a pair? What issues/successes did you run into when translating your pseudocode to code? What methods did you use to iterate through the content? Did you find any good ones when you were refactoring? Were they difficult to implement? =end
=begin # Calculate the mode Pairing Challenge # I worked on this challenge [with: Alan Alcesto] # I spent [] hours on this challenge. # Complete each step below according to the challenge directions and # include it in this file. Also make sure everything that isn't code # is commented. # 0. Pseudocode # What is the input? - an array of fixed numbers or strings # What is the output? (i.e. What should the code return?) - an array of the most frequent values # What are the steps needed to solve the problem? CREATE a most_frequent array and set it equal to the array argument # 1. Initial Solution =end def mode(array) end # 3. Refactored Solution =begin # 4. Reflection Which data structure did you and your pair decide to implement and why? Were you more successful breaking this problem down into implementable pseudocode than the last with a pair? What issues/successes did you run into when translating your pseudocode to code? What methods did you use to iterate through the content? Did you find any good ones when you were refactoring? Were they difficult to implement? =end
Send through post attributes using posts_attributes when creating a topic
FactoryGirl.define do factory :topic, :class => Forem::Topic do |t| t.subject "FIRST TOPIC" t.forum {|f| f.association(:forum) } t.user {|u| u.association(:user) } t.posts { |p| [p.association(:post)]} trait :approved do after_create { |topic| topic.approve! } end factory :approved_topic, :traits => [:approved] end end
FactoryGirl.define do factory :topic, :class => Forem::Topic do |t| t.subject "FIRST TOPIC" t.forum {|f| f.association(:forum) } t.user {|u| u.association(:user) } t.posts_attributes { [Factory.attributes_for(:post)] } trait :approved do after_create { |topic| topic.approve! } end factory :approved_topic, :traits => [:approved] end end
Fix implementation of question in ruby:bob
class AnswerSilence def self.handles?(input) input.empty? end def reply 'Fine. Be that way.' end end class AnswerQuestion def self.handles?(input) input.include?('?') end def reply 'Sure.' end end class AnswerShout def self.handles?(input) input == input.upcase end def reply 'Woah, chill out!' end end class AnswerDefault def self.handles?(input) true end def reply 'Whatever.' end end class Alice def hey(input) answerer(input).reply end private def answerer(input) handlers.find {|answer| answer.handles?(input)}.new end def handlers [AnswerSilence, AnswerQuestion, AnswerShout, AnswerDefault] end end class Bob def hey(something) if silent?(something) 'Fine. Be that way.' elsif question?(something) 'Sure.' elsif shouting?(something) 'Woah, chill out!' else 'Whatever.' end end private def question?(s) s.end_with?('?') end def silent?(s) s.empty? end def shouting?(s) s.upcase == s end end
class AnswerSilence def self.handles?(input) input.empty? end def reply 'Fine. Be that way.' end end class AnswerQuestion def self.handles?(input) input.end_with?('?') end def reply 'Sure.' end end class AnswerShout def self.handles?(input) input == input.upcase end def reply 'Woah, chill out!' end end class AnswerDefault def self.handles?(input) true end def reply 'Whatever.' end end class Alice def hey(input) answerer(input).reply end private def answerer(input) handlers.find {|answer| answer.handles?(input)}.new end def handlers [AnswerSilence, AnswerQuestion, AnswerShout, AnswerDefault] end end class Bob def hey(something) if silent?(something) 'Fine. Be that way.' elsif question?(something) 'Sure.' elsif shouting?(something) 'Woah, chill out!' else 'Whatever.' end end private def question?(s) s.end_with?('?') end def silent?(s) s.empty? end def shouting?(s) s.upcase == s end end
Use benchmark_suite to benchmark the parser and other bits.
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'lunokhod/version' Gem::Specification.new do |spec| spec.name = "lunokhod" spec.version = Lunokhod::VERSION spec.authors = ["David Yip"] spec.email = ["yipdw@northwestern.edu"] spec.description = %q{Parsing and compilation tools for Surveyor surveys} spec.summary = %q{Parsing and compilation tools for Surveyor surveys} spec.homepage = "https://github.com/NUBIC/lunokhod" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency 'case' spec.add_dependency 'uuidtools' spec.add_development_dependency "bundler", "~> 1.2" spec.add_development_dependency "rake" spec.add_development_dependency 'kpeg' spec.add_development_dependency 'rspec' end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'lunokhod/version' Gem::Specification.new do |spec| spec.name = "lunokhod" spec.version = Lunokhod::VERSION spec.authors = ["David Yip"] spec.email = ["yipdw@northwestern.edu"] spec.description = %q{Parsing and compilation tools for Surveyor surveys} spec.summary = %q{Parsing and compilation tools for Surveyor surveys} spec.homepage = "https://github.com/NUBIC/lunokhod" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency 'case' spec.add_dependency 'uuidtools' spec.add_development_dependency "bundler", "~> 1.2" spec.add_development_dependency "rake" spec.add_development_dependency 'benchmark_suite' spec.add_development_dependency 'kpeg' spec.add_development_dependency 'rspec' end
Add initial methods for saving back to disk
module Gitolite class GitoliteAdmin attr_accessor :gl_admin, :ssh_keys, :config CONF = "/conf/gitolite.conf" KEYDIR = "/keydir" #Intialize with the path to #the gitolite-admin repository def initialize(path, options = {}) @gl_admin = Grit::Repo.new(path) conf = options[:conf] || CONF keydir = options[:keydir] || KEYDIR @ssh_keys = load_keys(File.join(path, keydir)) @config = Config.new(File.join(path, conf)) end def add_key(key) end def key_exists?(key) end private #Loads all .pub files in the gitolite-admin #keydir directory def load_keys(path) keys = {} Dir.chdir(path) Dir.glob("**/*.pub").each do |key| new_key = SSHKey.new(File.join(path, key)) owner = new_key.owner keys[owner] ||= [] keys[owner] << new_key end keys end end end
module Gitolite class GitoliteAdmin attr_accessor :gl_admin, :ssh_keys, :config CONF = "/conf/gitolite.conf" KEYDIR = "/keydir" #Intialize with the path to #the gitolite-admin repository def initialize(path, options = {}) @gl_admin = Grit::Repo.new(path) conf = options[:conf] || CONF keydir = options[:keydir] || KEYDIR @ssh_keys = load_keys(File.join(path, keydir)) @config = Config.new(File.join(path, conf)) end #Writes all aspects out to the file system #will also stage all changes def save #Process config file #Process ssh keys end #commits all staged changes and pushes back #to origin def apply status = @gl_admin.status end #Calls save and apply in order def save_and_apply end private #Loads all .pub files in the gitolite-admin #keydir directory def load_keys(path) keys = {} Dir.chdir(path) Dir.glob("**/*.pub").each do |key| new_key = SSHKey.new(File.join(path, key)) owner = new_key.owner keys[owner] ||= [] keys[owner] << new_key end keys end end end
Add multiple arguments test for brew cat
describe "brew cat", :integration_test do it "prints the content of a given Formula" do formula_file = setup_test_formula "testball" content = formula_file.read expect { brew "cat", "testball" } .to output(content).to_stdout .and not_to_output.to_stderr .and be_a_success end end
describe "brew cat", :integration_test do it "prints the content of a given Formula" do formula_file = setup_test_formula "testball" content = formula_file.read expect { brew "cat", "testball" } .to output(content).to_stdout .and not_to_output.to_stderr .and be_a_success end it "fails when given multiple arguments" do setup_test_formula "foo" setup_test_formula "bar" expect { brew "cat", "foo", "bar" } .to output(/doesn't support multiple arguments/).to_stderr .and not_to_output.to_stdout .and be_a_failure end end
Fix to work with 1.8.7 again.
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "kumade/version" Gem::Specification.new do |s| s.name = "kumade" s.version = Kumade::VERSION s.authors = ["Gabe Berke-Williams", "thoughtbot"] s.email = ["gabe@thoughtbot.com", "support@thoughtbot.com"] s.homepage = "" s.summary = %q{Simple rake tasks for deploying to Heroku} s.description = s.summary s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_dependency('heroku', '~> 2.0') s.add_dependency('thor', '~> 0.14') s.add_development_dependency('rake', '~> 0.8.7') s.add_development_dependency('rspec', '~> 2.6.0') s.add_development_dependency('cucumber', '~> 1.0.2') s.add_development_dependency('aruba', '~> 0.4.3') s.add_development_dependency('jammit', '~> 0.6.3') end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "kumade/version" Gem::Specification.new do |s| s.name = "kumade" s.version = Kumade::VERSION s.authors = ["Gabe Berke-Williams", "thoughtbot"] s.email = ["gabe@thoughtbot.com", "support@thoughtbot.com"] s.homepage = "" s.summary = %q{Simple rake tasks for deploying to Heroku} s.description = s.summary s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_dependency('heroku', '~> 2.0') s.add_dependency('thor', '~> 0.14') s.add_dependency('rake', '~> 0.8.7') s.add_development_dependency('rake', '~> 0.8.7') s.add_development_dependency('rspec', '~> 2.6.0') s.add_development_dependency('cucumber', '~> 1.0.2') s.add_development_dependency('aruba', '~> 0.4.3') s.add_development_dependency('jammit', '~> 0.6.3') end
Fix webadmin to run bundle before migrations.
require 'facets/kernel/ergo' RAILS_ROOT = File.dirname(File.dirname(File.expand_path(__FILE__))) RESTART_TXT = "#{RAILS_ROOT}/tmp/restart.txt" def get_current_revision return `(cd #{RAILS_ROOT} && git --no-pager log -1) 2>&1` end get '/' do @revision = get_current_revision haml :index end post '/' do @revision = get_current_revision action = params[:action].ergo.to_s[/(\w+)/, 1] revision = params[:revision].ergo.to_s[/(\w+)/, 1] @command = nil common_restart = %{bundle exec rake RAILS_ENV=production clear && (bundle check || bundle --local || sudo bundle) && touch #{RESTART_TXT}} common_deploy = %{bundle exec rake RAILS_ENV=production db:migrate && #{common_restart}} case action when "deploy_and_migrate_via_update" if revision @command = %{git pull --rebase && git checkout #{revision} && #{common_deploy}} else @message = "ERROR: must specify revision to deploy via update" end when "restart", "start", "stop", "status" @command = %{#{common_restart}} end if @command @message = "Executing: #{@command}\n\n" @message << `(cd #{RAILS_ROOT} && #{@command}) 2>&1` end haml :index end
require 'facets/kernel/ergo' RAILS_ROOT = File.dirname(File.dirname(File.expand_path(__FILE__))) RESTART_TXT = "#{RAILS_ROOT}/tmp/restart.txt" def get_current_revision return `(cd #{RAILS_ROOT} && git --no-pager log -1) 2>&1` end get '/' do @revision = get_current_revision haml :index end post '/' do @revision = get_current_revision action = params[:action].ergo.to_s[/(\w+)/, 1] revision = params[:revision].ergo.to_s[/(\w+)/, 1] @command = nil common_bundle = %{bundle check || bundle --local || sudo bundle} common_restart = %{(#{common_bundle}) && bundle exec rake RAILS_ENV=production clear && touch #{RESTART_TXT}} common_deploy = %{(#{common_bundle}) && bundle exec rake RAILS_ENV=production db:migrate && #{common_restart}} case action when "deploy_and_migrate_via_update" if revision @command = %{git pull --rebase && git checkout #{revision} && #{common_deploy}} else @message = "ERROR: must specify revision to deploy via update" end when "restart", "start", "stop", "status" @command = %{#{common_restart}} end if @command @message = "Executing: #{@command}\n\n" @message << `(cd #{RAILS_ROOT} && #{@command}) 2>&1` end haml :index end
Add integration test for receiving Twilio SMS on carrier network
require 'test_helper' require 'twilio-ruby' class TwilioSmsTest < ActionDispatch::IntegrationTest test 'Send and receive Twilio SMS on carrier network' do skip 'Run this test manually with TEST_SMS=1' unless ENV['TEST_SMS'] # This end-to-end SMS test requires a smartphone with carrier-specific (e.g. AT&T) phone number twilio_phone_test_to, # running an auto-forwarder configured to forward SMS messages from twilio_phone to twilio_phone_test_forward. # # Tested using Auto SMS(lite) https://play.google.com/store/apps/details?id=com.tmnlab.autoresponder # # The test will use the Twilio API to send a test message from twilio_phone to twilio_phone_test_to, # wait for a short period of time, then use the Twilio API to locate an inbound message to # twilio_phone_test_forward containing the same unique ID. # credentials ACCOUNT_SID = CDO.twilio_sid AUTH_TOKEN = CDO.twilio_auth SMS_FROM = CDO.twilio_phone SMS_TEST_FORWARD = CDO.twilio_phone_test_forward SMS_TEST_TO = CDO.twilio_phone_test_to # Send a message from twilio_phone to test_to number @client = Twilio::REST::Client.new ACCOUNT_SID, AUTH_TOKEN test_body = "Test: #{SecureRandom.urlsafe_base64}." @client.messages.create( :from => SMS_FROM, :to => SMS_TEST_TO, :body => test_body ) # Wait for test_forward number to receive the auto-forwarded response TOTAL_TRIES = 10 num_tries = 0 loop do sleep 3 @client = Twilio::REST::Client.new ACCOUNT_SID, AUTH_TOKEN break if @client.messages.list( to: SMS_TEST_FORWARD, from: SMS_TEST_TO, date_sent: DateTime.now.strftime('%Y-%m-%d') ).detect { |message| message.body.include? test_body } num_tries += 1 if num_tries > TOTAL_TRIES raise "SMS test failed. From: #{SMS_FROM}, to: #{SMS_TEST_TO}, forward: #{SMS_TEST_FORWARD}, message: #{test_body}" end end end end
Send the products SKU inside note for reference later
require 'net/http' require 'json' module RlmRuby class License def self.generate_keys(contact = {}, products = []) req = Net::HTTP::Post.new(RlmRuby.configuration.uri, initheader = {'Content-Type' =>'application/json'}) req.basic_auth RlmRuby.configuration.username, RlmRuby.configuration.password req.body = { header:{ isv: RlmRuby.configuration.isv, operation: 'post', table: RlmRuby.configuration.table }, data: { contact: contact[:name], contact_notes: "via Cogmation Storefront on #{Time.now.strftime('%m/%d/%Y')}", phone: contact[:phone], email: contact[:email], notes: "via Cogmation Storefront on #{Time.now.strftime('%m/%d/%Y')}", products: products } }.to_json Net::HTTP.new(RlmRuby.configuration.host, RlmRuby.configuration.port).start {|http| http.request(req) } end end end
require 'net/http' require 'json' module RlmRuby class License def self.generate_keys(contact = {}, products = []) uri = URI(RlmRuby.configuration.uri) req = Net::HTTP::Post.new(uri, {'Content-Type' => 'application/json'}) req.basic_auth RlmRuby.configuration.username, RlmRuby.configuration.password req.body = { header:{ isv: RlmRuby.configuration.isv, operation: 'post', table: RlmRuby.configuration.table }, data: { contact: contact[:name], phone: contact[:phone], email: contact[:email], products: products } }.to_json Net::HTTP.new(RlmRuby.configuration.host).start {|http| http.request(req) } end end end
Replace quotes with % for searching by name
class Firm include DataMapper::Resource property :id, Integer property :firm_id, Integer, :key => true property :name, String property :parent_name, String property :total_critical, Integer property :total_noncritical, Integer property :address, Text property :lat, Float, :index => :latlng property :lng, Float, :index => :latlng has n, :inspections, :child_key => [ :firm_id ] def self.bbox(bbox) # top, left, bottom, right coordinates = bbox.split(',').map {|el| el.to_f || 0.0} return all(:lat.lte => coordinates[0], :lat.gte => coordinates[2], :lng.gte => coordinates[1], :lng.lte => coordinates[3]) end def self.byname(name) ret = [] all_data = Firm.all(:name.ilike => name) all_data.each do |firm| ret.push(firm['firm_id']) end return ret end def self.byparent(parent_name) ret = [] all_data = Firm.all(:parent_name.like => parent_name) all_data.each do |firm| ret.push(firm['firm_id']) end return ret end end
class Firm include DataMapper::Resource property :id, Integer property :firm_id, Integer, :key => true property :name, String property :parent_name, String property :total_critical, Integer property :total_noncritical, Integer property :address, Text property :lat, Float, :index => :latlng property :lng, Float, :index => :latlng has n, :inspections, :child_key => [ :firm_id ] def self.bbox(bbox) # top, left, bottom, right coordinates = bbox.split(',').map {|el| el.to_f || 0.0} return all(:lat.lte => coordinates[0], :lat.gte => coordinates[2], :lng.gte => coordinates[1], :lng.lte => coordinates[3]) end def self.byname(name) ret = [] modified_name = name.sub(/'|"/, '%') all_data = Firm.all(:name.ilike => modified_name) all_data.each do |firm| ret.push(firm['firm_id']) end return ret end def self.byparent(parent_name) ret = [] all_data = Firm.all(:parent_name.like => parent_name) all_data.each do |firm| ret.push(firm['firm_id']) end return ret end end
Add cask for VisTrails 2.0.3.
class Vistrails < Cask url 'http://downloads.sourceforge.net/project/vistrails/vistrails/v2.0.3/vistrails-mac-10.6-intel-2.0.3-a6ad79347667.dmg' homepage 'http://www.vistrails.org/index.php/Main_Page' version '2.0.3' sha1 '1381f58a8946792ed448ae072607cee9ed32a041' link 'VisTrails' end
Fix class name for Tmptoml in Formula
class TmpToml < Formula desc "Command-line utility to render Tera templates using a toml config file as the variable source." homepage "https://github.com/uptech/tmptoml" url "https://github.com/uptech/tmptoml.git", tag: "0.1.3", revision: "f4faf718dddc00b1e31dcb455fe0c28bca1fc574" version "0.1.3" head "https://github.com/uptech/tmptoml.git" depends_on "rust" => :build def install system "cargo", "build", "--release" bin.install "target/release/tmptoml" # man1.install "doc/tmptoml.1" # only in versions > 2.3.0 end test do assert_match version.to_s, shell_output("#{bin}/tmptoml --version") end end
class Tmptoml < Formula desc "Command-line utility to render Tera templates using a toml config file as the variable source." homepage "https://github.com/uptech/tmptoml" url "https://github.com/uptech/tmptoml.git", tag: "0.1.3", revision: "f4faf718dddc00b1e31dcb455fe0c28bca1fc574" version "0.1.3" head "https://github.com/uptech/tmptoml.git" depends_on "rust" => :build def install system "cargo", "build", "--release" bin.install "target/release/tmptoml" # man1.install "doc/tmptoml.1" # only in versions > 2.3.0 end test do assert_match version.to_s, shell_output("#{bin}/tmptoml --version") end end
Implement basic tests for cs_property provider
require 'spec_helper' describe Puppet::Type.type(:cs_property).provider(:crm) do before do described_class.stubs(:command).with(:crm).returns 'crm' end context 'when getting instances' do let :instances do test_cib = <<-EOS <cib> <configuration> <crm_config> <cluster_property_set> <nvpair name="apples" value="red"/> <nvpair name="oranges" value="orange"/> </cluster_property_set> </crm_config> </configuration> </cib> EOS described_class.expects(:block_until_ready).returns(nil) Puppet::Util::SUIDManager.expects(:run_and_capture).with(['crm', 'configure', 'show', 'xml']).at_least_once.returns([test_cib, 0]) instances = described_class.instances end it 'should have an instance for each <nvpair> in <cluster_property_set>' do expect(instances.count).to eq(2) end describe 'each instance' do let :instance do instances.first end it "is a kind of #{described_class.name}" do expect(instance).to be_a_kind_of(described_class) end it "is named by the <nvpair>'s name attribute" do expect(instance.name).to eq("apples") end it "has a value corresponding to the <nvpair>'s value attribute" do expect(instance.value).to eq("red") end end end end
Add a cask for Tiled.app
class Tiled < Cask url 'http://downloads.sourceforge.net/project/tiled/tiled-qt/0.9.1/tiled-qt-0.9.1.dmg' homepage 'http://www.mapeditor.org/' version '0.9.1' sha1 'f7f30ec8761ffd7f293242287ff4d462e7ee17fb' link 'Tiled.app' end
Correct ovftool path for Fusion 5
require 'tempfile' module Veewee module Provider module Vmfusion module BoxCommand # This function 'exports' the box based on the definition def export_ova(options) debug="--X:logToConsole=true --X:logLevel=\"verbose\"" debug="" flags="--compress=9" if File.exists?("#{name}.ova") if options["force"] env.logger.debug("#{name}.ova exists, but --force was provided") env.logger.debug("removing #{name}.ova first") FileUtils.rm("#{name}.ova") env.logger.debug("#{name}.ova removed") else raise Veewee::Error, "export file #{name}.ova already exists. Use --force option to overwrite." end end # Need to check binary first if self.running? # Wait for the shutdown to complete begin Timeout::timeout(20) do self.halt(options) status=self.running? unless status return end sleep 4 end rescue TimeoutError::Error => ex raise Veewee::Error,ex end end # before exporting the system needs to be shut down # otherwise the debug log will show - The specified virtual disk needs repair shell_exec("#{File.dirname(vmrun_cmd).shellescape}/ovftool/ovftool.bin #{debug} #{flags} #{vmx_file_path.shellescape} #{name}.ova") end end end end end
require 'tempfile' module Veewee module Provider module Vmfusion module BoxCommand # This function 'exports' the box based on the definition def export_ova(options) debug="--X:logToConsole=true --X:logLevel=\"verbose\"" debug="" flags="--compress=9" if File.exists?("#{name}.ova") if options["force"] env.logger.debug("#{name}.ova exists, but --force was provided") env.logger.debug("removing #{name}.ova first") FileUtils.rm("#{name}.ova") env.logger.debug("#{name}.ova removed") else raise Veewee::Error, "export file #{name}.ova already exists. Use --force option to overwrite." end end # Need to check binary first if self.running? # Wait for the shutdown to complete begin Timeout::timeout(20) do self.halt(options) status=self.running? unless status return end sleep 4 end rescue TimeoutError::Error => ex raise Veewee::Error,ex end end # before exporting the system needs to be shut down # otherwise the debug log will show - The specified virtual disk needs repair shell_exec("#{File.dirname(vmrun_cmd).shellescape}#{"/VMware OVF Tool/ovftool".shellescape} #{debug} #{flags} #{vmx_file_path.shellescape} #{name}.ova") end end end end end
Change the event check type for the AwaitEventHandler
require 'discordrb/events/generic' require 'discordrb/await' module Discordrb::Events # Event raised when an await is triggered class AwaitEvent attr_reader :await, :event delegate :key, :type, :attributes, to: :await def initialize(await, event, bot) @await = await @bot = bot end end # Event handler for AwaitEvent class AwaitEventHandler < EventHandler def matches?(event) # Check for the proper event type return false unless event.is_a? TypingEvent [ matches_all(@attributes[:key], event.key) { |a, e| a == e }, matches_all(@attributes[:type], event.type) { |a, e| a == e } ].reduce(true, &:&) end end end
require 'discordrb/events/generic' require 'discordrb/await' module Discordrb::Events # Event raised when an await is triggered class AwaitEvent attr_reader :await, :event delegate :key, :type, :attributes, to: :await def initialize(await, event, bot) @await = await @bot = bot end end # Event handler for AwaitEvent class AwaitEventHandler < EventHandler def matches?(event) # Check for the proper event type return false unless event.is_a? AwaitEvent [ matches_all(@attributes[:key], event.key) { |a, e| a == e }, matches_all(@attributes[:type], event.type) { |a, e| a == e } ].reduce(true, &:&) end end end
Use skippgpcheck instead of importing key (to the wrong keyring, besides). The default build user 'nobody' has no home directory, so cannot locally sign keys.
include_recipe 'pacman' package('perl') { action :install } package('expac') { action :install } package('yajl') { action :install } bash 'Importing key for cower' do code <<-EOH pacman-key --recv-key 1EB2638FF56C0C53 pacman-key --lsign 1EB2638FF56C0C53 EOH end pacman_aur('cower'){ action [:build, :install] } pacman_aur('pacaur'){ action [:build, :install] }
include_recipe 'pacman' package('perl') { action :install } package('expac') { action :install } package('yajl') { action :install } pacman_aur 'cower' do skippgpcheck true action [:build, :install] end pacman_aur('pacaur'){ action [:build, :install] }
Bump version to 0.1.1 and resolve rubocop
Gem::Specification.new do |s| s.name = 'singel' s.version = '0.1.0' s.date = Date.today.to_s s.platform = Gem::Platform::RUBY s.extra_rdoc_files = ['README.md', 'LICENSE'] s.summary = 'Unified system image creation using Packer' s.description = s.summary s.authors = ['Tim Smith'] s.email = 'tim@cozy.co' s.homepage = 'http://www.github.com/tas50/singel' s.license = 'Apache-2.0' s.required_ruby_version = '>= 1.9.3' s.add_dependency 'aws-sdk-core' s.add_development_dependency 'rake', '~> 10.0' s.add_development_dependency 'rubocop', '~> 0.28.0' s.files = `git ls-files -z`.split("\x0") s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) } s.require_paths = ['lib'] s.extra_rdoc_files = ['README.md'] s.rdoc_options = ['--line-numbers', '--inline-source', '--title', 'singel', '--main', 'README.md'] end
Gem::Specification.new do |s| s.name = 'singel' s.version = '0.1.1' s.date = Date.today.to_s s.platform = Gem::Platform::RUBY s.extra_rdoc_files = ['README.md', 'LICENSE'] s.summary = 'Unified system image creation using Packer' s.description = s.summary s.authors = ['Tim Smith'] s.email = 'tim@cozy.co' s.homepage = 'http://www.github.com/tas50/singel' s.license = 'Apache-2.0' s.required_ruby_version = '>= 1.9.3' s.add_dependency 'aws-sdk-core' s.add_development_dependency 'rake', '~> 10.0' s.add_development_dependency 'rubocop', '~> 0.28.0' s.files = `git ls-files -z`.split("\x0") s.executables = s.name s.require_paths = ['lib'] s.extra_rdoc_files = ['README.md'] s.rdoc_options = ['--line-numbers', '--inline-source', '--title', 'singel', '--main', 'README.md'] end
Add rspec to the gemspec.
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'archivable/version' Gem::Specification.new do |spec| spec.name = "archivable" spec.version = Archivable::VERSION spec.authors = ["TODO: Write your name"] spec.email = ["johnotander@gmail.com"] spec.summary = %q{TODO: Write a short summary. Required.} spec.description = %q{TODO: Write a longer description. Optional.} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.5" spec.add_development_dependency "rake" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'archivable/version' Gem::Specification.new do |spec| spec.name = "archivable" spec.version = Archivable::VERSION spec.authors = ["TODO: Write your name"] spec.email = ["johnotander@gmail.com"] spec.summary = %q{TODO: Write a short summary. Required.} spec.description = %q{TODO: Write a longer description. Optional.} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.5" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" end
Add a "new only" benchmark from JRUBY-2184.
=begin +----------+------+-----+---------+-----------------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(255) | YES | | NULL | | | description | text | YES | | NULL | | | created_at | datetime | YES | | NULL | | | updated_at | datetime | YES | | NULL | | +-------------+--------------+------+-----+---------+----------------+ =end ENV["RAILS_ENV"] = "production" require 'rubygems' require 'active_record' require 'benchmark' is_jruby = defined? RUBY_ENGINE && RUBY_ENGINE == "jruby" ActiveRecord::Base.establish_connection( :adapter => is_jruby ? "jdbcmysql" : "mysql", :host => "localhost", :username => "root", :database => "ar_bench" ) class Widget < ActiveRecord::Base; end TIMES = (ARGV[0] || 5).to_i Benchmark.bm(30) do |make| TIMES.times do make.report("Widget.new") do 100_000.times do Widget.new end end end end
Add passing specs for react_to method
require 'spec_helper' describe Disclosure do it "should be a module" do subject.should be_a Module end it "should have an engine" do Disclosure::Engine.superclass.should eq ::Rails::Engine end it "should be configurable directly" do Disclosure.configuration.owner_class = "Administrator" Disclosure.configuration.owner_class.should eq "Administrator" end it "should be configurable using a block" do Disclosure.configure do |config| config.owner_class = "Administrator" end Disclosure.configuration.owner_class.should eq "Administrator" end end
require 'spec_helper' describe Disclosure do it "should be a module" do subject.should be_a Module end it "should have an engine" do Disclosure::Engine.superclass.should eq ::Rails::Engine end it "should be configurable directly" do Disclosure.configuration.owner_class = "Administrator" Disclosure.configuration.owner_class.should eq "Administrator" end it "should be configurable using a block" do Disclosure.configure do |config| config.owner_class = "Administrator" end Disclosure.configuration.owner_class.should eq "Administrator" end describe "react_to!" do let(:model) { Disclosure::Issue.new } let(:rule) { Disclosure::Rule.new.tap { |r| r.action = 'closed' } } context "model is not reactable" do let(:model) { String.new } it "should not react" do Disclosure::Rule.any_instance.should_not_receive(:react!) subject.react_to!(model) end it "should return nil" do subject.react_to!(model).should be_nil end end it "should find matching rules" do Disclosure::Rule.any_instance.stub(:react!) Disclosure::Rule.should_receive(:where).with( :notifier_class => "Disclosure::Issue", :owner_id => 1 ).and_return([rule]) subject.react_to!(model) end it "should reject rules whose action does not match" do model.stub(:closed?).and_return(false) rule.should_not_receive :react! Disclosure::Rule.stub(:where).and_return([rule]) subject.react_to!(model) end it "should react to matching rules" do Disclosure::Rule.stub(:where).and_return([rule]) rule.should_receive(:react!).once() subject.react_to!(model) end end describe "subscription" do let(:model) { Disclosure::Issue.new } it "should be subscribed to the model event" do subject.should_receive(:react_to!).with(model) model.save end end end
Adjust DSL tests a bit
require 'minitest/autorun' require_relative '../lib/rdl.rb' class TestDsl < Minitest::Test class Pair def initialize(&blk) instance_eval(&blk) end def left(x) @left = x end def right(x) @right = x end def get [@left, @right] end end class Tree def initialize(val, &blk) @val = val instance_eval(&blk) end def left(x, &blk) if blk @left = Tree.new(x, &blk) else @left = x end end def right(x, &blk) if blk @right = Tree.new(x, &blk) else @right = x end end def get l = @left.instance_of?(Tree) ? @left.get : @left r = @right.instance_of?(Tree) ? @right.get : @right [@val, l, r] end end def test_pair p = Pair.new { left 3 right 4 } end def test_tree t = Tree.new(2) { left(3) right(4) { left(5) { left(6) right(7) } right(8) } } end end
require 'minitest/autorun' require_relative '../lib/rdl.rb' class TestDsl < Minitest::Test class Pair def entry(&blk) instance_eval(&blk) end def left(x) @left = x end def right(x) @right = x end def get [@left, @right] end end class Tree def entry(val, &blk) @val = val instance_eval(&blk) end def left(x, &blk) if blk @left = Tree.new.entry(x, &blk) else @left = x end end def right(x, &blk) if blk @right = Tree.new.entry(x, &blk) else @right = x end end def get l = @left.instance_of?(Tree) ? @left.get : @left r = @right.instance_of?(Tree) ? @right.get : @right [@val, l, r] end end def test_pair p = Pair.new.entry { left 3 right 4 } end def test_tree t = Tree.new.entry(2) { left(3) right(4) { left(5) { left(6) right(7) } right(8) } } end end
Rollback to bindfs.org to download source tarballs
module VagrantPlugins module Bindfs VERSION = "0.4.7" SOURCE_VERSION = "1.13.1" SOURCE_URL = "https://github.com/mpartel/bindfs/archive/#{SOURCE_VERSION}.tar.gz" end end
module VagrantPlugins module Bindfs VERSION = "0.4.7" SOURCE_VERSION = "1.13.1" SOURCE_URL = "http://bindfs.org/downloads/bindfs-#{SOURCE_VERSION}.tar.gz" end end
Clean up the link tests.
# frozen_string_literal: true $LOAD_PATH.unshift(__dir__) require 'helper' describe 'Link' do subject do filename = 'the.other.setup.yml' path = File.join(test_site.source_paths[:links], 'inspired', filename) UsesThis::Link.new(path) end describe 'when loading from a YAML file' do it 'correctly parses the contents' do source = read_yaml_fixture('link') subject.name.must_equal(source['name']) subject.description.must_equal(source['description']) subject.url.must_equal(source['url']) end end end
# frozen_string_literal: true $LOAD_PATH.unshift(__dir__) require 'helper' describe 'Link' do before do path = File.join( test_configuration['source_path'], 'links', 'inspired', 'the.other.setup.yml' ) @link = UsesThis::Link.new(path) end describe 'when loading from a YAML file' do it 'correctly parses the contents' do expected_output = YAML.safe_load(fixtures['link']) %w[name description url].each do |key| @link.send(key).must_equal(expected_output[key]) end end end end
Update Cask: Textadept 6.0 beta 3.
class Textadept < Cask url 'http://foicica.com/textadept/download/textadept_5.4.osx.zip' homepage 'http://foicica.com/textadept/' version '5.4' end
class Textadept < Cask url 'http://foicica.com/textadept/download/textadept_6.0_beta_3.osx.zip' homepage 'http://foicica.com/textadept/' version '6.0-beta-3' end
Update select common reply helper with hack to handle missing translations for chinese char sets
module AdminHelper def assigned_to(topic) unless topic.assigned_user.nil? t(:assigned_to, agent: topic.assigned_user.name, default: "assigned to #{topic.assigned_user.name}") else t(:unassigned, default: "Unassigned") end end def i18n_reply select = "<label class='control-label' for='post_reply_id'>#{t(:select_common, default: 'Insert Common Reply')}</label>" select += "<select name='post[reply_id]' class='form-control' id='post_reply_id'>" select += "<option value=''></option>" I18n.available_locales.each do |locale| Globalize.with_locale(locale) do select += "<optgroup label='#{I18n.translate("i18n_languages.#{locale}")}'>" Doc.replies.with_translations(locale).all.each do |doc| select += "<option value='#{doc.body}'>#{doc.title}</option>" end select += "</optgroup>" end end select += "</select>" # Return select select.html_safe end end
module AdminHelper def assigned_to(topic) unless topic.assigned_user.nil? t(:assigned_to, agent: topic.assigned_user.name, default: "assigned to #{topic.assigned_user.name}") else t(:unassigned, default: "Unassigned") end end def i18n_reply # Builds the nested selector for common replies select = "<label class='control-label' for='post_reply_id'>#{t(:select_common, default: 'Insert Common Reply')}</label>" select += "<select name='post[reply_id]' class='form-control' id='post_reply_id'>" select += "<option value=''></option>" I18n.available_locales.each do |locale| Globalize.with_locale(locale) do # TODO THIS IS A HACK because there appears to be no difference in language files for chinese simple and traditional # This could be changed to display the language names in english fairly easily # but in another language we are missing the translations if "#{locale}" == 'zh-cn' || "#{locale}" == 'zh-tw' select += "<optgroup label='#{I18n.translate("i18n_languages.zh")}'>" else select += "<optgroup label='#{I18n.translate("i18n_languages.#{locale}")}'>" end Doc.replies.with_translations(locale).all.each do |doc| select += "<option value='#{doc.body}'>#{doc.title}</option>" end select += "</optgroup>" end end select += "</select>" # Return select select.html_safe end end
Use cancancan instead of cancan
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "feeder/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "feeder" s.version = Feeder::VERSION s.authors = ["Sindre Moen"] s.email = ["sindre@hyper.no"] s.homepage = "http://github.com/hyperoslo/feeder" s.summary = "Provides simple feed functionality through an engine" s.description = <<DESC Feeder gives you a mountable engine that provides a route to a feed page in your Ruby on Rails application. DESC s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"] s.test_files = Dir["spec/**/*"] s.add_dependency "rails", "~> 4.0" s.add_dependency 'rails-observers' s.add_dependency 'kaminari' s.add_development_dependency "sqlite3" s.add_development_dependency "pry-rails" s.add_development_dependency "hirb-unicode" s.add_development_dependency "rspec-rails", '~> 2.x' s.add_development_dependency "capybara" s.add_development_dependency "factory_girl_rails" s.add_development_dependency "timecop" s.add_development_dependency "cancan" end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "feeder/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "feeder" s.version = Feeder::VERSION s.authors = ["Sindre Moen"] s.email = ["sindre@hyper.no"] s.homepage = "http://github.com/hyperoslo/feeder" s.summary = "Provides simple feed functionality through an engine" s.description = <<DESC Feeder gives you a mountable engine that provides a route to a feed page in your Ruby on Rails application. DESC s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"] s.test_files = Dir["spec/**/*"] s.add_dependency "rails", "~> 4.0" s.add_dependency 'rails-observers' s.add_dependency 'kaminari' s.add_development_dependency "sqlite3" s.add_development_dependency "pry-rails" s.add_development_dependency "hirb-unicode" s.add_development_dependency "rspec-rails", '~> 2.x' s.add_development_dependency "capybara" s.add_development_dependency "factory_girl_rails" s.add_development_dependency "timecop" s.add_development_dependency "cancancan" end
Fix homepage URL in gemspec.
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'net/socket/version' Gem::Specification.new do |spec| spec.name = "net-socket" spec.version = Net::Socket::VERSION spec.authors = ["Ellen Marie Dash"] spec.email = ["me@duckie.co"] spec.summary = %q{A better socket API.} spec.description = spec.summary spec.homepage = "https://github.com/heresy/net-socket" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.12" spec.add_development_dependency "rake", "~> 11.2" spec.add_development_dependency "rspec", "~> 3.5" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'net/socket/version' Gem::Specification.new do |spec| spec.name = "net-socket" spec.version = Net::Socket::VERSION spec.authors = ["Ellen Marie Dash"] spec.email = ["me@duckie.co"] spec.summary = %q{A better socket API.} spec.description = spec.summary spec.homepage = "https://github.com/ruby-heresy/net-socket" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.12" spec.add_development_dependency "rake", "~> 11.2" spec.add_development_dependency "rspec", "~> 3.5" end
Add cucumber as a development dependency.
# encoding: utf-8 $:.unshift File.expand_path('../lib', __FILE__) require 'dill/version' Gem::Specification.new do |s| s.name = "dill" s.version = Dill::VERSION s.authors = ["David Leal"] s.email = ["dleal@mojotech.com"] s.homepage = "https://github.com/mojotech/dill" s.summary = "A set of helpers to ease integration testing" s.description = "See https://github.com/mojotech/dill/README.md" s.license = "MIT" s.files = `git ls-files app lib`.split("\n") s.platform = Gem::Platform::RUBY s.require_paths = ['lib'] s.rubyforge_project = '[none]' s.add_dependency 'chronic' s.add_dependency 'capybara', '>= 2.0' s.add_development_dependency 'rspec-given', '~> 3.0.0' s.add_development_dependency 'sinatra' s.add_development_dependency 'capybara-webkit', '~> 1.0.0' s.add_development_dependency 'poltergeist', '~> 1.3.0' end
# encoding: utf-8 $:.unshift File.expand_path('../lib', __FILE__) require 'dill/version' Gem::Specification.new do |s| s.name = "dill" s.version = Dill::VERSION s.authors = ["David Leal"] s.email = ["dleal@mojotech.com"] s.homepage = "https://github.com/mojotech/dill" s.summary = "A set of helpers to ease integration testing" s.description = "See https://github.com/mojotech/dill/README.md" s.license = "MIT" s.files = `git ls-files app lib`.split("\n") s.platform = Gem::Platform::RUBY s.require_paths = ['lib'] s.rubyforge_project = '[none]' s.add_dependency 'chronic' s.add_dependency 'capybara', '>= 2.0' s.add_development_dependency 'rspec-given', '~> 3.0.0' s.add_development_dependency 'sinatra' s.add_development_dependency 'capybara-webkit', '~> 1.0.0' s.add_development_dependency 'poltergeist', '~> 1.3.0' s.add_development_dependency 'cucumber', '~> 1.3.0' end
Add migration to update submitted timestampss
class RemoveIsDoneFromReportUploadsAndUpdateSubmittedTimestamps < ActiveRecord::Migration def up ActiveRecord::Base.connection.execute( <<-SQL UPDATE trade_annual_report_uploads SET submitted_at = updated_at, submitted_by_id = updated_by_id WHERE is_done = true SQL ) remove_column :trade_annual_report_uploads, :is_done end def down add_column :trade_annual_report_uploads, :is_done, :boolean, default: false ActiveRecord::Base.connection.execute( <<-SQL UPDATE trade_annual_report_uploads SET is_done = true WHERE submitted_by_id IS NOT NULL SQL ) end end
Add test path to LOAD_PATH to fix load error
$:.unshift(File.dirname(__FILE__) + '/../../activesupport/lib') require 'test/unit' require 'rbconfig' require 'active_support/core_ext/kernel/reporting' require 'abstract_unit' class TestIsolated < ActiveSupport::TestCase ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) Dir["#{File.dirname(__FILE__)}/{abstract,controller,dispatch,template}/**/*_test.rb"].each do |file| define_method("test #{file}") do command = "#{ruby} -Ilib:test #{file}" result = silence_stderr { `#{command}` } assert_block("#{command}\n#{result}") { $?.to_i.zero? } end end end
$:.unshift(File.dirname(__FILE__)) $:.unshift(File.dirname(__FILE__) + '/../../activesupport/lib') require 'test/unit' require 'rbconfig' require 'active_support/core_ext/kernel/reporting' require 'abstract_unit' class TestIsolated < ActiveSupport::TestCase ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) Dir["#{File.dirname(__FILE__)}/{abstract,controller,dispatch,template}/**/*_test.rb"].each do |file| define_method("test #{file}") do command = "#{ruby} -Ilib:test #{file}" result = silence_stderr { `#{command}` } assert_block("#{command}\n#{result}") { $?.to_i.zero? } end end end
Add rspec to check the get method for Rover class
require 'spec_helper' describe MarsPhotos::Rover do let(:rover) { MarsPhotos::Rover.new("curiosity") } it "creates a curiosity rover" do expect(rover.name).to eq("curiosity") end end
require 'spec_helper' describe MarsPhotos::Rover do let(:rover) { MarsPhotos::Rover.new("curiosity") } it "creates a curiosity rover" do expect(rover.name).to eq("curiosity") end it "retrieves the photos for a rover when give sol" do sol = 1000 expect(rover.get(sol)).not_to be_nil end end
Bump podspec version to 1.0.1
Pod::Spec.new do |s| s.name = "HTAutocompleteTextField" s.version = "1.0.0" s.summary = "A subclass of UITextField that displays text completion suggestions while a user types. Perfect for suggestion email address domains." s.homepage = "https://github.com/hoteltonight/HTAutocompleteTextField" s.license = 'MIT' s.author = { "Jonathan Sibley" => "jon@hoteltonight.com" } s.source = { :git => "https://github.com/hoteltonight/HTAutocompleteTextField.git", :tag => "1.0.0" } s.platform = :ios s.source_files = 'HTAutocompleteTextField.{h,m}' s.requires_arc = true end
Pod::Spec.new do |s| s.name = "HTAutocompleteTextField" s.version = "1.0.1" s.summary = "A subclass of UITextField that displays text completion suggestions while a user types. Perfect for suggestion email address domains." s.homepage = "https://github.com/hoteltonight/HTAutocompleteTextField" s.license = 'MIT' s.author = { "Jonathan Sibley" => "jon@hoteltonight.com" } s.source = { :git => "https://github.com/hoteltonight/HTAutocompleteTextField.git", :tag => "1.0.1" } s.platform = :ios s.ios.deployment_target = '4.3' s.source_files = 'HTAutocompleteTextField.{h,m}' s.requires_arc = true end
Add basic test for Request.
require 'test_helper' module HtWax describe Request do describe 'initialize' do it 'can be initialized with an http method and a URI' do r = Request.new(:get, 'http://localhost/') r.request_method.must_equal :get r.uri.must_equal 'http://localhost/' end end end end
Add Authentication to User Model
class User < ActiveRecord::Base has_many :comments has_many :votes has_many :responses has_many :questions validates :name, presence: true validates_format_of :name, :with => (/([a-zA-Z]|\d){2,}/) #refactor out into a CONSTANT? validates :email, presence: true validates :email, uniqueness: true validates_format_of :email, :with => (/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i) validates :password, presence: true validates_format_of :password, :with => (/([a-zA-Z]|\d){2,}/) #refactor out into a CONSTANT? end
class User < ActiveRecord::Base has_secure_password has_many :comments has_many :votes has_many :responses has_many :questions validates :name, presence: true validates_format_of :name, :with => (/([a-zA-Z]|\d){2,}/) #refactor out into a CONSTANT? validates :email, presence: true validates :email, uniqueness: true validates_format_of :email, :with => (/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i) validates :password, presence: true validates_format_of :password, :with => (/([a-zA-Z]|\d){2,}/) #refactor out into a CONSTANT? end
Add tests for the Square class
require 'minitest/autorun' require 'r2d' describe Square do before do R2D::Window.create width: 640, height: 480 @square = Square.new(10, 20, 200) end it 'can have a size' do @square.size.must_equal 200 end it 'can edit the height' do @square.size = 400 @square.size.must_equal 400 end end
Use REPO_URL constant for gemspec homepage
$LOAD_PATH << File.expand_path('../lib', __FILE__) require 'overcommit/version' Gem::Specification.new do |s| s.name = 'overcommit' s.version = Overcommit::VERSION s.license = 'MIT' s.summary = 'Git hook manager' s.description = 'Utility to install, configure, and extend Git hooks' s.authors = ['Causes Engineering', 'Shane da Silva'] s.email = ['eng@causes.com', 'shane@causes.com'] s.homepage = 'http://github.com/causes/overcommit' s.post_install_message = 'Install hooks by running `overcommit --install` in your Git repository' s.require_paths = %w[lib] s.executables = ['overcommit'] s.files = Dir['bin/**/*'] + Dir['config/*.yml'] + Dir['lib/**/*.rb'] s.required_ruby_version = '>= 1.8.7' s.add_dependency 'wopen3' s.add_development_dependency 'rspec', '2.14.1' s.add_development_dependency 'image_optim', '0.10.2' end
$LOAD_PATH << File.expand_path('../lib', __FILE__) require 'overcommit/constants' require 'overcommit/version' Gem::Specification.new do |s| s.name = 'overcommit' s.version = Overcommit::VERSION s.license = 'MIT' s.summary = 'Git hook manager' s.description = 'Utility to install, configure, and extend Git hooks' s.authors = ['Causes Engineering', 'Shane da Silva'] s.email = ['eng@causes.com', 'shane@causes.com'] s.homepage = Overcommit::REPO_URL s.post_install_message = 'Install hooks by running `overcommit --install` in your Git repository' s.require_paths = %w[lib] s.executables = ['overcommit'] s.files = Dir['bin/**/*'] + Dir['config/*.yml'] + Dir['lib/**/*.rb'] s.required_ruby_version = '>= 1.8.7' s.add_dependency 'wopen3' s.add_development_dependency 'rspec', '2.14.1' s.add_development_dependency 'image_optim', '0.10.2' end
Use a worker pool in the example, so that it's really easy to scale up.
# Run like this: # # $ resqued example/minimal.rb before_fork do host = ENV['REDIS_HOST'] || 'localhost' port = ENV['REDIS_PORT'] || 6379 Resque.redis = Redis.new(:host => host, :port => port) end worker 'resqued-example-queue'
# Run like this: # # $ resqued example/minimal.rb before_fork do host = ENV['REDIS_HOST'] || 'localhost' port = ENV['REDIS_PORT'] || 6379 Resque.redis = Redis.new(:host => host, :port => port) end worker_pool 1 queue 'resqued-example-queue'
Change timeouts to account for sidekiq queue
module SmokeTest module Steps class BaseStep include Capybara::DSL attr_accessor :state def initialize(state) puts "Step:#{step_name}" @state = state end def validate! true end def complete_step fail NotImplementedError end protected def step_name self.class.name.split('::').last.gsub(/(?=[A-Z])/, ' ') end def with_retries(attempts: 5, initial_delay: 2, max_delay: 30) delay = initial_delay result = nil attempts.times do result = yield break if result puts "waiting #{delay}s .." sleep delay delay = [max_delay, delay * 2].min end result end end end end
module SmokeTest module Steps class BaseStep include Capybara::DSL attr_accessor :state def initialize(state) puts "Step:#{step_name}" @state = state end def validate! true end def complete_step fail NotImplementedError end protected def step_name self.class.name.split('::').last.gsub(/(?=[A-Z])/, ' ') end def with_retries(attempts: 10, initial_delay: 2, max_delay: 120) delay = initial_delay result = nil attempts.times do result = yield break if result puts "waiting #{delay}s .." sleep delay delay = [max_delay, delay * 2].min end result end end end end
Print file size for debugging
#!/usr/bin/env ruby result = `sass scss/color-claim.scss built.css` raise result unless $?.to_i == 0 raise "When compiled the module should output some CSS" unless File.exists?('built.css') puts "Regular compile worked successfully" result = `sass test/silent.scss build.silent.css --style compressed` raise result unless $?.to_i == 0 raise "When $use-silent-classes is set to true the module should not output any CSS" unless File.size('build.silent.css') == 0 puts "Silent sass compiled successfully"
#!/usr/bin/env ruby result = `sass scss/color-claim.scss built.css` raise result unless $?.to_i == 0 raise "When compiled the module should output some CSS" unless File.exists?('built.css') puts "Regular compile worked successfully" result = `sass test/silent.scss build.silent.css --style compressed` raise result unless $?.to_i == 0 raise File.size('build.silent.css') raise "When $_silent is set to true the module should not output any CSS" unless File.size('build.silent.css') == 0 puts "Silent sass compiled successfully"
Add geoip info and more
require 'useragent' module Meter module Rails class Middleware def initialize(app) @app = app end def call(env) request = Rack::Request.new(env) Meter::MDC.data['request_id'] = env['action_dispatch.request_id'] user_agent = UserAgent.parse(request.user_agent) Meter::MDC.tags['user_agent_name'] = user_agent.browser Meter::MDC.tags['user_agent_version'] = "#{user_agent.browser}_#{user_agent.version}" Meter::MDC.tags['user_agent_platform'] = user_agent.platform Meter::MDC.data['user_agent'] = user_agent.to_s @app.call(env) ensure Meter::MDC.clear! end end end end
require 'useragent' module Meter module Rails class Middleware def initialize(app) @app = app end def call(env) request = Rack::Request.new(env) Meter::MDC.data['request_id'] = env['action_dispatch.request_id'] Meter::MDC.data['pid'] = Process.pid Meter::MDC.data['ip'] = request.ip.presence || '?' store_user_agent_data(request) store_geoip_data(request) @app.call(env) ensure Meter::MDC.clear! end def store_user_agent_data(request) user_agent = UserAgent.parse(request.user_agent) Meter::MDC.tags['user_agent_name'] = user_agent.browser Meter::MDC.tags['user_agent_version'] = "#{user_agent.browser}_#{user_agent.version}" Meter::MDC.tags['user_agent_platform'] = user_agent.platform Meter::MDC.data['user_agent'] = user_agent.to_s end def store_geoip_data(request) return unless defined?(Locality) lookup = Locality::IP.new request.ip Meter::MDC.tags['geoip_city'] = lookup.city_name Meter::MDC.tags['geoip_country'] = lookup.country_name end end end end
Change column order in promise csv.
namespace :hdo do namespace :promises do task :csv => :environment do require 'csv' promises = Promise.joins(:categories) if ENV['CATEGORIES'] promises = promises.where('categories.name' => ENV['CATEGORIES'].split(',')) end if ENV['OUT'] out = File.open(ENV['OUT'], 'w') else out = STDOUT end CSV(out) do |csv| promises.each do |promise| csv << [promise.external_id, promise.body, promise.categories.map(&:name).join(',')] end end end end end
namespace :hdo do namespace :promises do task :csv => :environment do require 'csv' promises = Promise.joins(:categories) if ENV['CATEGORIES'] promises = promises.where('categories.name' => ENV['CATEGORIES'].split(',')) end if ENV['OUT'] out = File.open(ENV['OUT'], 'w') else out = STDOUT end CSV(out) do |csv| promises.each do |promise| csv << [promise.external_id, promise.categories.map(&:name).join(','), promise.body] end end end end end
Remove duplicate :instance_reader, change to :instance_accessor.
require 'require_relative' require_relative 'composed_of_enum/version' module ActiveRecord module ComposedOfEnum def composed_of_enum(part, options = {}) unless options.has_key?(:base) raise ArgumentError, 'must provide :base option' end unless options.has_key?(:enumeration) raise ArgumentError, 'must provide :enumeration option' end base = options[:base] enum_column = :"#{part}_cd" base.class_attribute( enum_column, :instance_reader => false, :instance_reader => false ) enumeration = options[:enumeration] enumeration.each_with_index do |enum, cd| enum.send(:"#{enum_column}=", cd) end validates( enum_column, :presence => true, :inclusion => 0...enumeration.size ) setter_method_name = :"#{part}=" if options.has_key?(:default) after_initialize do send(setter_method_name, options[:default]) unless send(part).present? end end define_method(setter_method_name) { |enum| self[enum_column] = enum.send(enum_column) } define_method(part) do enum_cd = self[enum_column] enum_cd.present? ? enumeration[enum_cd] : nil end end end end
require 'require_relative' require_relative 'composed_of_enum/version' module ActiveRecord module ComposedOfEnum def composed_of_enum(part, options = {}) unless options.has_key?(:base) raise ArgumentError, 'must provide :base option' end unless options.has_key?(:enumeration) raise ArgumentError, 'must provide :enumeration option' end base = options[:base] enum_column = :"#{part}_cd" base.class_attribute(enum_column, :instance_accessor => false) enumeration = options[:enumeration] enumeration.each_with_index do |enum, cd| enum.send(:"#{enum_column}=", cd) end validates( enum_column, :presence => true, :inclusion => 0...enumeration.size ) setter_method_name = :"#{part}=" if options.has_key?(:default) after_initialize do send(setter_method_name, options[:default]) unless send(part).present? end end define_method(setter_method_name) { |enum| self[enum_column] = enum.send(enum_column) } define_method(part) do enum_cd = self[enum_column] enum_cd.present? ? enumeration[enum_cd] : nil end end end end
Fix for Mysql Specific code
class Admin::RefinerySettingsController < Admin::BaseController crudify :refinery_setting, :title_attribute => :title, :order => "name ASC", :searchable => false before_filter :sanitise_params, :only => [:create, :update] after_filter :fire_setting_callback, :only => [:update] def edit @refinery_setting = RefinerySetting.find(params[:id]) render :layout => false if request.xhr? end def find_all_refinery_settings @refinery_settings = RefinerySetting.find :all, :order => "name ASC", :conditions => current_user.has_role?(:superuser) ? nil : ["restricted IS NOT ?", true] end def paginate_all_refinery_settings @refinery_settings = RefinerySetting.paginate :page => params[:page], :order => "name ASC", :conditions => current_user.has_role?(:superuser) ? nil : ["restricted IS NOT ?", true] end private # this fires before an update or create to remove any attempts to pass sensitive arguments. def sanitise_params params.delete(:callback_proc_as_string) params.delete(:scoping) end def fire_setting_callback begin @refinery_setting.callback_proc.call rescue logger.warn('Could not fire callback proc. Details:') logger.warn(@refinery_setting.inspect) logger.warn($!.message) logger.warn($!.backtrace) end unless @refinery_setting.callback_proc.nil? end end
class Admin::RefinerySettingsController < Admin::BaseController crudify :refinery_setting, :title_attribute => :title, :order => "name ASC", :searchable => false before_filter :sanitise_params, :only => [:create, :update] after_filter :fire_setting_callback, :only => [:update] def edit @refinery_setting = RefinerySetting.find(params[:id]) render :layout => false if request.xhr? end def find_all_refinery_settings @refinery_settings = RefinerySetting.find :all, :order => "name ASC", :conditions => current_user.has_role?(:superuser) ? nil : ["restricted <> ?", true] end def paginate_all_refinery_settings @refinery_settings = RefinerySetting.paginate :page => params[:page], :order => "name ASC", :conditions => current_user.has_role?(:superuser) ? nil : ["restricted <> ?", true] end private # this fires before an update or create to remove any attempts to pass sensitive arguments. def sanitise_params params.delete(:callback_proc_as_string) params.delete(:scoping) end def fire_setting_callback begin @refinery_setting.callback_proc.call rescue logger.warn('Could not fire callback proc. Details:') logger.warn(@refinery_setting.inspect) logger.warn($!.message) logger.warn($!.backtrace) end unless @refinery_setting.callback_proc.nil? end end
Add failing tests for spec
#!/usr/bin/env rspec require 'v8' require 'noms/command/xmlhttprequest' describe NOMS::Command::XMLHttpRequest do before(:all) do # I'm going to go with this class variable for now NOMS::Command::XMLHttpRequest.origin = 'http://localhost:8787/' end context 'from ruby' do before(:each) do @xhr = NOMS::Command::XMLHttpRequest.new end describe '#readyState' do it 'should be 0' do expect(@xhr.readyState).to eq 0 end end describe 'statuses' do it 'should be equal to the correct number' do expect(@xhr.OPENED).to eq 1 expect(@xhr.HEADERS_RECEIVED).to eq 2 expect(@xhr.LOADING).to eq 3 expect(@xhr.DONE).to eq 4 end end describe '#open' do # open, send, check readyState and responseText it 'should retrieve web content' do @xhr.open('GET', 'http://localhost:8787/files/data.json', false) @xhr.send() expect(@xhr.responseText).to match /^\[/ end it 'should raise an error on different-origin' do expect { @xhr.open('GET', 'http://localhost:8786/files/data.json', false) }.to raise_error NOMS::Command::Error end end describe '#setRequestHeader' do @xhr.setRequestHeader('Accept', 'text/plain') expect(@xhr.headers['Accept']).to eq 'text/plain' end describe '#onreadystatechange' do end describe '#abort' do end end context 'from javascript' do before(:each) do @v8 = V8::Context.new @v8[:XMLHttpRequest] = NOMS::Command::XMLHttpRequest @v8.eval 'var xhr = new XMLHttpRequest()' end describe '#open' do # open, send, check readyState and responseText it 'should retrieve web content' do @v8.eval 'xhr.open("GET", "http://localhost:8787/files/data.json", false)' @v8.eval 'xhr.send()' expect(@v8.eval 'xhr.readyState').to eq 4 expect(@v8.eval 'xhr.responseText').to match(/^\[/) end end describe '#setRequestHeader' do end describe '#onreadystatechange' do end describe '#abort' do end end end
Make store credit payment method back end only.
class ModifySpreeStoreCreditPaymentMethodToBeBackEndOnly < ActiveRecord::Migration def up payment_method = Spree::PaymentMethod.find_by(type: 'Spree::PaymentMethod::StoreCredit') return unless payment_method payment_method.display_on = 'back_end' payment_method.save! end def down payment_method = Spree::PaymentMethod.find_by(type: 'Spree::PaymentMethod::StoreCredit') return unless payment_method payment_method.display_on = nil payment_method.save! end end
Use libmagick9-dev for the dev libraries on Ubuntu 8.04 and 8.10
# # Cookbook Name:: imagemagick # Recipe:: rmagick # # 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. # include_recipe "imagemagick" case node[:platform] when "redhat", "centos", "fedora" package "ImageMagick-devel" when "debian", "ubuntu" package "libmagickwand-dev" end gem_package "rmagick"
# # Cookbook Name:: imagemagick # Recipe:: rmagick # # 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. # include_recipe "imagemagick" case node[:platform] when "redhat", "centos", "fedora" package "ImageMagick-devel" when "debian", "ubuntu" package value_for_platform( "ubuntu" => { "8.04" => "libmagick9-dev", "8.10" => "libmagick9-dev", }, "default" => { "default" => "libmagickwand-dev" } ) end gem_package "rmagick"
Use a global sequence for attachment ordering
FactoryGirl.define do factory :file_attachment do ignore do file { File.open(Rails.root.join('test', 'fixtures', 'greenpaper.pdf')) } end sequence(:title) { |index| "file-attachment-title-#{index}" } sequence(:ordering) after(:build) do |attachment, evaluator| attachment.attachment_data ||= build(:attachment_data, file: evaluator.file) end end factory :csv_attachment, parent: :file_attachment do ignore do file { File.open(Rails.root.join('test', 'fixtures', 'sample.csv')) } end end factory :html_attachment do sequence(:title) { |index| "html-attachment-title-#{index}" } sequence(:ordering) body 'Attachment body' end end
FactoryGirl.define do sequence(:attachment_ordering) factory :file_attachment do ignore do file { File.open(Rails.root.join('test', 'fixtures', 'greenpaper.pdf')) } end sequence(:title) { |index| "file-attachment-title-#{index}" } ordering { generate(:attachment_ordering) } after(:build) do |attachment, evaluator| attachment.attachment_data ||= build(:attachment_data, file: evaluator.file) end end factory :csv_attachment, parent: :file_attachment do ignore do file { File.open(Rails.root.join('test', 'fixtures', 'sample.csv')) } end end factory :html_attachment do sequence(:title) { |index| "html-attachment-title-#{index}" } ordering { generate(:attachment_ordering) } body 'Attachment body' end end
Refactor rename method param to signal it is unused (style).
# -*- encoding: utf-8 -*- module Emeril # Exception class raised when there is a metadata.rb parsing issue. # class MetadataParseError < StandardError ; end # A rather insane and questionable class to quickly consume a metadata.rb # file and return the cookbook name and version attributes. # # @see https://twitter.com/fnichol/status/281650077901144064 # @see https://gist.github.com/4343327 # @author Fletcher Nichol <fnichol@nichol.ca> # class MetadataChopper < Hash # Creates a new instances and loads in the contents of the metdata.rb # file. If you value your life, you may want to avoid reading the # implementation. # # @param metadata_file [String] path to a metadata.rb file # def initialize(metadata_file) eval(IO.read(metadata_file), nil, metadata_file) %w{name version}.map(&:to_sym).each do |attr| next unless self[attr].nil? raise MetadataParseError, "Missing attribute `#{attr}' must be set in #{metadata_file}" end end def method_missing(meth, *args, &block) self[meth] = args.first end end end
# -*- encoding: utf-8 -*- module Emeril # Exception class raised when there is a metadata.rb parsing issue. # class MetadataParseError < StandardError ; end # A rather insane and questionable class to quickly consume a metadata.rb # file and return the cookbook name and version attributes. # # @see https://twitter.com/fnichol/status/281650077901144064 # @see https://gist.github.com/4343327 # @author Fletcher Nichol <fnichol@nichol.ca> # class MetadataChopper < Hash # Creates a new instances and loads in the contents of the metdata.rb # file. If you value your life, you may want to avoid reading the # implementation. # # @param metadata_file [String] path to a metadata.rb file # def initialize(metadata_file) eval(IO.read(metadata_file), nil, metadata_file) %w{name version}.map(&:to_sym).each do |attr| next unless self[attr].nil? raise MetadataParseError, "Missing attribute `#{attr}' must be set in #{metadata_file}" end end def method_missing(meth, *args, &_block) self[meth] = args.first end end end
Make Inch not display purple anymore :heart:
require 'retryable_record' module Kernel # Retryable operations on an ActiveRecord +record+. # # == Example # # require 'retryable_record/import' # # RetryableRecord(user) do # user.username = "foo" # user.save! # end # # == Example using attempts # # require 'retryable_record/import' # # RetryableRecord(user, :attempts => 3) do # user.username = "foo" # user.save! # end # # See RetryableRecord#retry def RetryableRecord(record, opts = {}, &block) RetryableRecord.retry(record, opts, &block) end end
require 'retryable_record' # Extend Ruby's Kernel module module Kernel # Retryable operations on an ActiveRecord +record+. # # == Example # # require 'retryable_record/import' # # RetryableRecord(user) do # user.username = "foo" # user.save! # end # # == Example using attempts # # require 'retryable_record/import' # # RetryableRecord(user, :attempts => 3) do # user.username = "foo" # user.save! # end # # See RetryableRecord#retry def RetryableRecord(record, opts = {}, &block) RetryableRecord.retry(record, opts, &block) end end
Fix bug in picking up publication ID from email addresses
require 'fact_check_message_processor' # A class to pull messages from an email account and send relevant ones # to a processor. # # It presumes that the mail class has already been configured in an # initializer and is typically called from the mail_fetcher script class FactCheckEmailHandler attr_accessor :errors def initialize self.errors = [] end def is_relevant_message?(message) message.to.any? { |to| to.match(/factcheck\+#{Plek.current.environment}-(.+?)@alphagov.co.uk/) } end def process_message(message) if is_relevant_message?(message) return FactCheckMessageProcessor.process(message, $1) end return false rescue => e errors << "Failed to process message #{message.subject}: #{e.message}" return false end def process() Mail.all(:delete_after_find => true) do |message, imap, message_id| message.skip_deletion unless process_message(message) end end end
require 'fact_check_message_processor' # A class to pull messages from an email account and send relevant ones # to a processor. # # It presumes that the mail class has already been configured in an # initializer and is typically called from the mail_fetcher script class FactCheckEmailHandler attr_accessor :errors def initialize self.errors = [] end def process_message(message) if message.to.any? { |to| to.match(/factcheck\+#{Plek.current.environment}-(.+?)@alphagov.co.uk/) } return FactCheckMessageProcessor.process(message, $1) end return false rescue => e errors << "Failed to process message #{message.subject}: #{e.message}" return false end def process() Mail.all(:delete_after_find => true) do |message, imap, message_id| message.skip_deletion unless process_message(message) end end end
Fix namespace raise exception rabbit listener
# frozen_string_literal: true # :reek:TooManyStatements module RubyRabbitmqJanus module Rabbit module Listener # Base for listeners class Base < RubyRabbitmqJanus::Rabbit::BaseEvent # Define an publisher # # @param [String] rabbit Information connection to rabbitmq server def initialize(rabbit) super() @rabbit = rabbit.channel subscribe_queue rescue raise Errors::Rabbit::Listener::Initialize end # Listen a queue and return a body response def listen_events semaphore.wait response = nil lock.synchronize do response = responses.shift end yield response.event, response rescue raise Errors::Rabbit::Listener::ListenEvents end private attr_accessor :rabbit, :responses def binding @rabbit.direct('amq.direct') end def opts_subs { block: false, manual_ack: true, arguments: { 'x-priority': 2 } } end # Counts transmitted messages def log_message_id(propertie) message_id = propertie.message_id ::Log.info "[X] Message reading with ID #{message_id}" end def info_subscribe(info, prop, payload) ::Log.debug info ::Log.info \ "[X] Message reading ##{prop['correlation_id']}" ::Log.debug payload end end end end end require 'rrj/rabbit/listener/from' require 'rrj/rabbit/listener/from_admin' require 'rrj/rabbit/listener/janus_instance'
# frozen_string_literal: true # :reek:TooManyStatements module RubyRabbitmqJanus module Rabbit module Listener # Base for listeners class Base < RubyRabbitmqJanus::Rabbit::BaseEvent # Define an publisher # # @param [String] rabbit Information connection to rabbitmq server def initialize(rabbit) super() @rabbit = rabbit.channel subscribe_queue rescue raise Errors::Rabbit::Listener::Base::Initialize end # Listen a queue and return a body response def listen_events semaphore.wait response = nil lock.synchronize do response = responses.shift end yield response.event, response rescue raise Errors::Rabbit::Listener::Base::ListenEvents end private attr_accessor :rabbit, :responses def binding @rabbit.direct('amq.direct') end def opts_subs { block: false, manual_ack: true, arguments: { 'x-priority': 2 } } end # Counts transmitted messages def log_message_id(propertie) message_id = propertie.message_id ::Log.info "[X] Message reading with ID #{message_id}" end def info_subscribe(info, prop, payload) ::Log.debug info ::Log.info \ "[X] Message reading ##{prop['correlation_id']}" ::Log.debug payload end end end end end require 'rrj/rabbit/listener/from' require 'rrj/rabbit/listener/from_admin' require 'rrj/rabbit/listener/janus_instance'
Add cask for Google Music Manager.
class GoogleMusicManager < Cask url 'https://dl.google.com/dl/androidjumper/mac/718015/musicmanager.dmg' homepage 'https://music.google.com' version '1.0.71.8015' sha1 '1f695cb8b08606476a3a12acd86a0a2d36da81a5' link 'MusicManager.app' end
Allow using current versions of bundler, rake
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rack/github_webhooks/version' Gem::Specification.new do |spec| spec.name = 'rack-github_webhooks' spec.version = Rack::GithubWebhooks::VERSION spec.authors = ['Chris Mytton'] spec.email = ['chrismytton@gmail.com'] spec.summary = 'Rack middleware to check GitHub webhooks are authentic' spec.homepage = 'https://github.com/chrismytton/rack-github_webhook' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '~> 1.10' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'minitest' spec.add_development_dependency 'pry' spec.add_development_dependency 'rack-test' spec.add_development_dependency 'simplecov' end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rack/github_webhooks/version' Gem::Specification.new do |spec| spec.name = 'rack-github_webhooks' spec.version = Rack::GithubWebhooks::VERSION spec.authors = ['Chris Mytton'] spec.email = ['chrismytton@gmail.com'] spec.summary = 'Rack middleware to check GitHub webhooks are authentic' spec.homepage = 'https://github.com/chrismytton/rack-github_webhook' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '>= 1.10' spec.add_development_dependency 'rake' spec.add_development_dependency 'minitest' spec.add_development_dependency 'pry' spec.add_development_dependency 'rack-test' spec.add_development_dependency 'simplecov' end
Fix bugs in extra vars.
module Heaven # Top-level module for providers. module Provider # The capistrano provider. class Ansible < DefaultProvider def initialize(guid, payload) super @name = "ansible" end def ansible_root "#{checkout_directory}/ansible" end def execute return execute_and_log(["/usr/bin/true"]) if Rails.env.test? unless File.exist?(checkout_directory) log "Cloning #{repository_url} into #{checkout_directory}" execute_and_log(["git", "clone", clone_url, checkout_directory]) end Dir.chdir(checkout_directory) do log "Fetching the latest code" execute_and_log(%w{git fetch}) execute_and_log(["git", "reset", "--hard", sha]) ansible_hosts_file = "#{ansible_root}/hosts" ansible_site_file = "#{ansible_root}/site.yml" ansible_extra_vars = [ "heaven_deploy_sha=#{sha}", "ansible_ssh_private_key_file=#{working_directory}/.ssh/id_rsa" ].join(" ") deploy_string = ["ANSIBLE_HOST_KEY_CHECKING=false", "ansible-playbook", "-i", ansible_hosts_file, ansible_site_file, "--verbose", "--extra-vars", ansible_extra_vars] log "Executing ansible: #{deploy_string.join(" ")}" execute_and_log(deploy_string) end end end end end
module Heaven # Top-level module for providers. module Provider # The capistrano provider. class Ansible < DefaultProvider def initialize(guid, payload) super @name = "ansible" end def ansible_root "#{checkout_directory}/ansible" end def execute return execute_and_log(["/usr/bin/true"]) if Rails.env.test? unless File.exist?(checkout_directory) log "Cloning #{repository_url} into #{checkout_directory}" execute_and_log(["git", "clone", clone_url, checkout_directory]) end Dir.chdir(checkout_directory) do log "Fetching the latest code" execute_and_log(%w{git fetch}) execute_and_log(["git", "reset", "--hard", sha]) ansible_hosts_file = "#{ansible_root}/hosts" ansible_site_file = "#{ansible_root}/site.yml" ansible_extra_vars = [ "heaven_deploy_sha=#{sha}", "ansible_ssh_private_key_file=#{working_directory}/.ssh/id_rsa" ].join(" ") deploy_string = ["ANSIBLE_HOST_KEY_CHECKING=false", "ansible-playbook", "-i", ansible_hosts_file, ansible_site_file, "--verbose", "--extra-vars", "'#{ansible_extra_vars}'"] log "Executing ansible: #{deploy_string.join(" ")}" execute_and_log(deploy_string) end end end end end
Rename set_db_to_rsu to enable_rsu and set_db_to_toi to enable_toi.
require "galera_cluster_migrations/version" require 'active_support/concern' module GaleraClusterMigrations extend ActiveSupport::Concern require 'galera_cluster_migrations/railtie' if defined?(Rails) included do def set_db_to_rsu say "Setting wsrep_OSU_method to RSU" unless [:development, :test].include?(Rails.env) execute "SET GLOBAL wsrep_OSU_method=RSU" end end def with_rsu unless [:development, :test].include?(Rails.env) execute "SET GLOBAL wsrep_OSU_method=RSU" execute "SET GLOBAL wsrep_desync=ON" execute "SET wsrep_on=OFF" end yield unless [:development, :test].include?(Rails.env) execute "SET GLOBAL wsrep_desync=OFF" execute "SET GLOBAL wsrep_OSU_method=TOI" end end def set_db_to_toi say "Setting wsrep_OSU_method to TOI" unless [:development, :test].include?(Rails.env) execute "SET GLOBAL wsrep_OSU_method=TOI" end end end end
require "galera_cluster_migrations/version" require 'active_support/concern' module GaleraClusterMigrations extend ActiveSupport::Concern require 'galera_cluster_migrations/railtie' if defined?(Rails) included do def enable_rsu say "Setting wsrep_OSU_method to RSU" unless [:development, :test].include?(Rails.env) execute "SET GLOBAL wsrep_OSU_method=RSU" end end def with_rsu unless [:development, :test].include?(Rails.env) execute "SET GLOBAL wsrep_OSU_method=RSU" execute "SET GLOBAL wsrep_desync=ON" execute "SET wsrep_on=OFF" end yield unless [:development, :test].include?(Rails.env) execute "SET GLOBAL wsrep_desync=OFF" execute "SET GLOBAL wsrep_OSU_method=TOI" end end def enable_toi say "Setting wsrep_OSU_method to TOI" unless [:development, :test].include?(Rails.env) execute "SET GLOBAL wsrep_OSU_method=TOI" end end end end
Include legacy version for iDisplay.app
cask :v1 => 'idisplay' do version '2.3.10' sha256 '6d87e0566e2e2693d89c4fdb1cddcfed9db6316f6f7b2bada24104ea18b996ae' # shape.ag is the official download host per the vendor homepage url "http://www.shape.ag/freedownload/iDisplay/iDisplayFull_#{version.gsub('.', '_')}.dmg" name 'iDisplay' homepage 'http://getidisplay.com/' license :gratis app 'iDisplay.app' end
cask :v1 => 'idisplay' do if MacOS.release <= :leopard version '1.1.12' sha256 'ea0f9dd2c488762169c0bab2218ee628b6eff658a814dfca583e4563b99b7c6c' # shape.ag is the official download host per the vendor homepage url 'http://www.shape.ag/freedownload/iDisplay/iDisplay.dmg' else version '2.3.10' sha256 '6d87e0566e2e2693d89c4fdb1cddcfed9db6316f6f7b2bada24104ea18b996ae' # shape.ag is the official download host per the vendor homepage url "http://www.shape.ag/freedownload/iDisplay/iDisplayFull_#{version.gsub('.', '_')}.dmg" end name 'iDisplay' homepage 'http://getidisplay.com/' license :gratis app 'iDisplay.app' end
Fix box URL for precise64
# Use a Linux image vagrant_box 'precise64' do url 'http://files.vagrantup.com/precise32.box' end
# Use a Linux image vagrant_box 'precise64' do url 'http://files.vagrantup.com/precise64.box' end
Convert metadata result set to hash
class Repository include Tire::Model::Persistence include Tire::Model::Search include Tire::Model::Callbacks validates_presence_of :name, :type, :url, :datasets, :latitude, :longitude property :name property :type property :url property :latitude property :longitude property :datasets property :completeness property :weighted_completeness property :richness_of_information property :accuracy property :accessibility def metadata total = Tire.search('metadata', :search_type => 'count') do query { all } end.results.total name = @name Tire.search 'metadata' do query { string 'repository:' + name } size total end.results end def update_score(metric, score) self.send("#{metric.name}=", score) end def best_record(metric) sort_metric_scores(metric, 'desc').first end def worst_record(metric) sort_metric_scores(metric, 'asc').first end def sort_metric_scores(metric, sorting_order) name = @name search = Tire.search 'metadata' do query { string "repository:#{name}" } sort { by metric, sorting_order } end.results end end
class Repository include Tire::Model::Persistence include Tire::Model::Search include Tire::Model::Callbacks validates_presence_of :name, :type, :url, :datasets, :latitude, :longitude property :name property :type property :url property :latitude property :longitude property :datasets property :completeness property :weighted_completeness property :richness_of_information property :accuracy property :accessibility def metadata total = Tire.search('metadata', :search_type => 'count') do query { all } end.results.total name = @name Tire.search 'metadata' do query { string 'repository:' + name } size total end.results.map { |entry| entry.to_hash } end def update_score(metric, score) self.send("#{metric.name}=", score) end def best_record(metric) sort_metric_scores(metric, 'desc').first end def worst_record(metric) sort_metric_scores(metric, 'asc').first end def sort_metric_scores(metric, sorting_order) name = @name search = Tire.search 'metadata' do query { string "repository:#{name}" } sort { by metric, sorting_order } end.results end end
Update podspec, changed swift version to swift 5.0
Pod::Spec.new do |spec| spec.name = "PulsarKit" spec.version = "1.1.1" spec.summary = "PulsarKit is a simple and beautiful wrapper around the official UICollectionView API written in pure Swift" spec.description = <<-DESC PulsarKit is a simple and beautiful wrapper around the official UICollectionView API written in pure Swift. PulsarKit is a library that lets you populate and update collection views simply using your models. This framework is lightly inspire by Lighter view controllers and UITableViewSource and UICollectionViewSource in Xamarin Platform. DESC spec.homepage = "http://www.massimooliviero.net" spec.social_media_url = 'http://twitter.com/maxoly' spec.license = "MIT" spec.author = { "Massimo Oliviero" => "massimo.oliviero@gmail.com" } spec.ios.deployment_target = "10.0" spec.source = { :git => "https://github.com/maxoly/PulsarKit.git", :tag => "#{spec.version}" } spec.source_files = "PulsarKit", "PulsarKit/PulsarKit/**/*.{h,m,swift,c}" spec.swift_version = '4.2' end
Pod::Spec.new do |spec| spec.name = "PulsarKit" spec.version = "1.1.1" spec.summary = "PulsarKit is a simple and beautiful wrapper around the official UICollectionView API written in pure Swift" spec.description = <<-DESC PulsarKit is a simple and beautiful wrapper around the official UICollectionView API written in pure Swift. PulsarKit is a library that lets you populate and update collection views simply using your models. This framework is lightly inspire by Lighter view controllers and UITableViewSource and UICollectionViewSource in Xamarin Platform. DESC spec.homepage = "http://www.massimooliviero.net" spec.social_media_url = 'http://twitter.com/maxoly' spec.license = "MIT" spec.author = { "Massimo Oliviero" => "massimo.oliviero@gmail.com" } spec.ios.deployment_target = "10.0" spec.source = { :git => "https://github.com/maxoly/PulsarKit.git", :tag => "#{spec.version}" } spec.source_files = "PulsarKit", "PulsarKit/PulsarKit/**/*.{h,m,swift,c}" spec.swift_version = '5.0' end
Put asset.rb items on single line
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' # Add additional assets to the asset load path # Rails.application.config.assets.paths << Emoji.images_path # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # Rails.application.config.assets.precompile += %w( search.js ) Rails.application.config.assets.precompile += %w( animate.css ) Rails.application.config.assets.precompile += %w( style.css ) Rails.application.config.assets.precompile += %w( navbar.css )
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' # Add additional assets to the asset load path # Rails.application.config.assets.paths << Emoji.images_path # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # Rails.application.config.assets.precompile += %w( search.js ) Rails.application.config.assets.precompile += %w( animate.css style.css navbar.css )
Set up indices before tests and clean up after tests
require 'elasticsearch/extensions/test/cluster' RSpec.configure do |config| unless ENV['CI'] config.before(:suite) { start_elastic_cluster } config.after(:suite) { stop_elastic_cluster } end end def start_elastic_cluster ENV['TEST_CLUSTER_PORT'] = '9250' ENV['TEST_CLUSTER_NODES'] = '1' ENV['TEST_CLUSTER_NAME'] = 'spree_searchkick_test' ENV['ELASTICSEARCH_URL'] = "http://localhost:#{ENV['TEST_CLUSTER_PORT']}" return if Elasticsearch::Extensions::Test::Cluster.running? Elasticsearch::Extensions::Test::Cluster.start(timeout: 10) end def stop_elastic_cluster return unless Elasticsearch::Extensions::Test::Cluster.running? Elasticsearch::Extensions::Test::Cluster.stop end
require 'elasticsearch/extensions/test/cluster' RSpec.configure do |config| unless ENV['CI'] config.before(:suite) { start_elastic_cluster } config.after(:suite) { stop_elastic_cluster } end SEARCHABLE_MODELS = [Spree::Product].freeze # create indices for searchable models config.before do SEARCHABLE_MODELS.each do |model| model.reindex model.searchkick_index.refresh end end # delete indices for searchable models to keep clean state between tests config.after do SEARCHABLE_MODELS.each do |model| model.searchkick_index.delete end end end def start_elastic_cluster ENV['TEST_CLUSTER_PORT'] = '9250' ENV['TEST_CLUSTER_NODES'] = '1' ENV['TEST_CLUSTER_NAME'] = 'spree_searchkick_test' ENV['ELASTICSEARCH_URL'] = "http://localhost:#{ENV['TEST_CLUSTER_PORT']}" return if Elasticsearch::Extensions::Test::Cluster.running? Elasticsearch::Extensions::Test::Cluster.start(timeout: 10) end def stop_elastic_cluster return unless Elasticsearch::Extensions::Test::Cluster.running? Elasticsearch::Extensions::Test::Cluster.stop end
Install MenuMeters prefpane directly, no caveats
class Menumeters < Cask url 'http://www.ragingmenace.com/software/download/MenuMeters.dmg' homepage 'http://www.ragingmenace.com/software/menumeters/' version 'latest' no_checksum link 'MenuMeters Installer.app' def caveats; <<-EOS.undent You need to run #{destination_path/'MenuMeters Installer.app'} to actually install MenuMeters EOS end end
class Menumeters < Cask url 'http://www.ragingmenace.com/software/download/MenuMeters.dmg' homepage 'http://www.ragingmenace.com/software/menumeters/' version 'latest' no_checksum prefpane 'MenuMeters Installer.app/Contents/Resources/MenuMeters.prefPane' end
Configure factory girl to lint factories before test suite
RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods end
RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods config.before(:suite) do begin DatabaseCleaner.start FactoryGirl.lint ensure DatabaseCleaner.clean end end end
Fix route to get schema for Rails 4.1.2
JsonSchemaRails::Engine.routes.draw do resources :schemas, only: :show, path: '', id: /[\/a-zA-Z0-9_-]+/, defaults: { format: 'json' } end
JsonSchemaRails::Engine.routes.draw do get '*id(.:format)', to: 'schemas#show', as: :schema, id: /[\/a-zA-Z0-9_-]+/, defaults: { format: 'json' } end
Add a sanity test for contactotron. Override initialize on that adapter as we don't want it to take a parameter
require 'test_helper' require 'gds_api/contactotron' class ContactotronApiTest < MiniTest::Unit::TestCase def api GdsApi::Contactotron.new end def test_should_fetch_and_parse_JSON_into_ostruct uri = "http://contactotron.environment/contacts/1" stub_request(:get, uri). to_return(:status => 200, :body => '{"detail":"value"}') assert_equal OpenStruct, api.contact_for_uri(uri).class end end
Hide rack profiler by default
if Rails.env == 'development' require 'rack-mini-profiler' # initialization is skipped so trigger it Rack::MiniProfilerRails.initialize!(Rails.application) Rack::MiniProfiler.config.position = 'right' end
if Rails.env == 'development' require 'rack-mini-profiler' # initialization is skipped so trigger it Rack::MiniProfilerRails.initialize!(Rails.application) Rack::MiniProfiler.config.position = 'right' Rack::MiniProfiler.config.start_hidden = true end
Revert "Teach tilecache cookbook to return caches sorted (deterministic)"
# # Cookbook Name:: tilecache # Recipe:: default # # Copyright 2011, OpenStreetMap Foundation # # 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. # include_recipe "squid" expiry_time = 14 * 86400 tilecaches = search(:node, "roles:tilecache").reject { |n| Time.now - Time.at(n[:ohai_time]) > expiry_time }.sort_by { |n| n[:hostname] }.map do |n| { :name => n[:hostname], :interface => n.interfaces(:role => :external).first[:interface] } end squid_fragment "tilecache" do template "squid.conf.erb" variables :caches => tilecaches end
# # Cookbook Name:: tilecache # Recipe:: default # # Copyright 2011, OpenStreetMap Foundation # # 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. # include_recipe "squid" tilecaches = search(:node, "roles:tilecache") squid_fragment "tilecache" do template "squid.conf.erb" variables :caches => tilecaches end
Stop annoying me when Im changing fixtures for other tests first
require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../test_helper' class <%= class_name %>Test < Test::Unit::TestCase fixtures :<%= table_name %> # Replace this with your real tests. def test_truth assert_kind_of <%= class_name %>, <%= table_name %>(:first) end end
require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../test_helper' class <%= class_name %>Test < Test::Unit::TestCase fixtures :<%= table_name %> # Replace this with your real tests. def test_truth assert true end end
Fix column types on Issues table
class FixIssuesColumnTypes < ActiveRecord::Migration def up remove_column :issues, :bug_id add_column :issues, :bug_id, :integer change_column :issues, :cc, :text change_column :issues, :release_notes, :text change_column :issues, :resolution, :text end end
Package version is increased from 0.4.3.3 to 0.4.3.4
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'evt-log' s.version = '0.4.3.3' s.summary = 'Logging to STD IO with levels, tagging, and coloring' s.description = ' ' s.authors = ['The Eventide Project'] s.email = 'opensource@eventide-project.org' s.homepage = 'https://github.com/eventide-project/log' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.3.3' s.add_runtime_dependency 'evt-initializer' s.add_runtime_dependency 'evt-dependency' s.add_runtime_dependency 'evt-telemetry' s.add_runtime_dependency 'evt-clock' s.add_runtime_dependency 'terminal_colors' s.add_development_dependency 'test_bench' end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'evt-log' s.version = '0.4.3.4' s.summary = 'Logging to STD IO with levels, tagging, and coloring' s.description = ' ' s.authors = ['The Eventide Project'] s.email = 'opensource@eventide-project.org' s.homepage = 'https://github.com/eventide-project/log' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.3.3' s.add_runtime_dependency 'evt-initializer' s.add_runtime_dependency 'evt-dependency' s.add_runtime_dependency 'evt-telemetry' s.add_runtime_dependency 'evt-clock' s.add_runtime_dependency 'terminal_colors' s.add_development_dependency 'test_bench' end
Allow xls files created via spreadsheet gem
# # Ensure attachments are saved with URL-friendly names Paperclip.interpolates :safe_filename do |attachment, style| filename(attachment, style).gsub(/#/, '-') end
# # Ensure attachments are saved with URL-friendly names Paperclip.interpolates :safe_filename do |attachment, style| filename(attachment, style).gsub(/#/, '-') end # XLS files created by the spreadsheet gem have problems with their filetypes # https://github.com/zdavatz/spreadsheet/issues/97 Paperclip.options[:content_type_mappings] = { xls: "CDF V2 Document, No summary info" }
Update `Operator::MessagesController` so it works in later rails versions
module Operator class MessagesController < ActionController::Base ## # POST /operator/:queue # # Find all the matching `Processor`s and let them process the message in # `params[:message]`. # # If no `Processor` can be found, a 404 will be raised. # # If any of the `Processor`s raise an exception, a 500 error will be # raised and the processing wilt stop immediately def create processors = Processor.subscribers_for(params[:queue]) if processors.empty? render :status => 404, :nothing => true return end processors.each do |processor| processor.process(params[:message]) end render :status => 200, :nothing => true end end end
module Operator class MessagesController < ActionController::Base ## # POST /operator/:queue # # Find all the matching `Processor`s and let them process the message in # `params[:message]`. # # If no `Processor` can be found, a 404 will be raised. # # If any of the `Processor`s raise an exception, a 500 error will be # raised and the processing wilt stop immediately def create processors = Processor.subscribers_for(params[:queue]) if processors.empty? render :status => 404, :nothing => true return end processors.each do |processor| processor.process(params[:message]) end head :ok end end end
Use modulesync to manage meta files
require 'puppetlabs_spec_helper/module_spec_helper' RSpec.configure do |c| c.include PuppetlabsSpec::Files c.before :each do # Ensure that we don't accidentally cache facts and environment # between test cases. Facter::Util::Loader.any_instance.stubs(:load_all) Facter.clear Facter.clear_messages # Store any environment variables away to be restored later @old_env = {} ENV.each_key {|k| @old_env[k] = ENV[k]} if Gem::Version.new(`puppet --version`) >= Gem::Version.new('3.5') Puppet.settings[:strict_variables]=true end end c.after :each do PuppetlabsSpec::Files.cleanup end end require 'pathname' dir = Pathname.new(__FILE__).parent Puppet[:modulepath] = File.join(dir, 'fixtures', 'modules') # There's no real need to make this version dependent, but it helps find # regressions in Puppet # # 1. Workaround for issue #16277 where default settings aren't initialised from # a spec and so the libdir is never initialised (3.0.x) # 2. Workaround for 2.7.20 that now only loads types for the current node # environment (#13858) so Puppet[:modulepath] seems to get ignored # 3. Workaround for 3.5 where context hasn't been configured yet, # ticket https://tickets.puppetlabs.com/browse/MODULES-823 # ver = Gem::Version.new(Puppet.version.split('-').first) if Gem::Requirement.new("~> 2.7.20") =~ ver || Gem::Requirement.new("~> 3.0.0") =~ ver || Gem::Requirement.new("~> 3.5") =~ ver puts "augeasproviders: setting Puppet[:libdir] to work around broken type autoloading" # libdir is only a single dir, so it can only workaround loading of one external module Puppet[:libdir] = "#{Puppet[:modulepath]}/augeasproviders_core/lib" end
require 'puppetlabs_spec_helper/module_spec_helper' RSpec.configure do |c| c.include PuppetlabsSpec::Files c.before :each do # Ensure that we don't accidentally cache facts and environment # between test cases. Facter::Util::Loader.any_instance.stubs(:load_all) Facter.clear Facter.clear_messages # Store any environment variables away to be restored later @old_env = {} ENV.each_key {|k| @old_env[k] = ENV[k]} if Gem::Version.new(`puppet --version`) >= Gem::Version.new('3.5') Puppet.settings[:strict_variables]=true end end c.after :each do PuppetlabsSpec::Files.cleanup end end
Remove old skool hash rocket
require 'simplecov' require 'rspec' require 'rspec/its' require 'vcr' require 'jortt' SimpleCov.start if ENV['CI'] == 'true' require 'codecov' SimpleCov.formatter = SimpleCov::Formatter::Codecov end VCR.configure do |c| c.cassette_library_dir = "spec/fixtures/vcr_cassettes" c.hook_into :webmock c.configure_rspec_metadata! c.default_cassette_options = { :record => :once } c.before_record do |i| i.response.headers.delete('Set-Cookie') i.request.headers.delete('Authorization') end end RSpec.configure do |c| end ENV['JORTT_CLIENT_ID'] ||= 'client-id' ENV['JORTT_CLIENT_SECRET'] ||= 'client-secret'
require 'simplecov' require 'rspec' require 'rspec/its' require 'vcr' require 'jortt' SimpleCov.start if ENV['CI'] == 'true' require 'codecov' SimpleCov.formatter = SimpleCov::Formatter::Codecov end VCR.configure do |c| c.cassette_library_dir = "spec/fixtures/vcr_cassettes" c.hook_into :webmock c.configure_rspec_metadata! c.default_cassette_options = { record: :once } c.before_record do |i| i.response.headers.delete('Set-Cookie') i.request.headers.delete('Authorization') end end RSpec.configure do |c| end ENV['JORTT_CLIENT_ID'] ||= 'client-id' ENV['JORTT_CLIENT_SECRET'] ||= 'client-secret'
Use Airbrake.notify_sync instead of Airbrake.notify
require "route_consistency_checker" def report_errors(errors) Airbrake.notify( "Inconsistent routes", parameters: { errors: errors, } ) errors.each do |base_path, item_errors| puts "#{base_path} 😱" puts item_errors end end desc "Check the routes for consistency with the router-api" task :check_route_consistency, [:routes, :router_data] => [:environment] do |_, args| raise "Must pass routes.csv.gz file" unless args[:routes] raise "Must pass location to router-data" unless args[:router_data] routes = RouteDumpLoader.load(args[:routes]) router_data = RouterDataLoader.load(args[:router_data]) checker = RouteConsistencyChecker.new(routes, router_data) checker.check_content checker.check_routes errors = checker.errors report_errors(errors) if errors.any? end
require "route_consistency_checker" def report_errors(errors) Airbrake.notify_sync( "Inconsistent routes", parameters: { errors: errors, } ) errors.each do |base_path, item_errors| puts "#{base_path} 😱" puts item_errors end end desc "Check the routes for consistency with the router-api" task :check_route_consistency, [:routes, :router_data] => [:environment] do |_, args| raise "Must pass routes.csv.gz file" unless args[:routes] raise "Must pass location to router-data" unless args[:router_data] routes = RouteDumpLoader.load(args[:routes]) router_data = RouterDataLoader.load(args[:router_data]) checker = RouteConsistencyChecker.new(routes, router_data) checker.check_content checker.check_routes errors = checker.errors report_errors(errors) if errors.any? end
Add 'user_id=' to the log tag
Rails.configuration.log_tags = [ :request_id, -> (request) { session_key = (Rails.application.config.session_options || {})[:key] session_data = request.cookie_jar.encrypted[session_key] || {} # warden.user.user.key で User#id を取得 session_data.dig("warden.user.user.key", 0, 0) } ]
Rails.configuration.log_tags = [ :request_id, -> (request) { session_key = (Rails.application.config.session_options || {})[:key] session_data = request.cookie_jar.encrypted[session_key] || {} user_id = session_data.dig("warden.user.user.key", 0, 0) "user_id=#{user_id}" if user_id } ]
Enable O2 optimizations for Gambit Scheme
require 'formula' class GambitScheme <Formula url 'http://www.iro.umontreal.ca/~gambit/download/gambit/v4.5/source/gambc-v4_5_2.tgz' homepage 'http://dynamo.iro.umontreal.ca/~gambit/wiki/index.php/Main_Page' md5 '71bd4b5858f807c4a8ce6ce68737db16' def options [ ['--with-check', 'Execute "make check" before installing. Runs some basic scheme programs to ensure that gsi and gsc are working'], ['--enable-shared', 'Build Gambit Scheme runtime as shared library'] ] end def install # Gambit Scheme currently fails to build with llvm-gcc # (ld crashes during the build process) ENV.gcc_4_2 # Gambit Scheme will not build with heavy optimizations. Disable all # optimizations until safe values can be figured out. ENV.no_optimization configure_args = [ "--prefix=#{prefix}", "--disable-debug", # Recommended to improve the execution speed and compactness # of the generated executables. Increases compilation times. "--enable-single-host" ] configure_args << "--enable-shared" if ARGV.include? '--enable-shared' system "./configure", *configure_args system "make check" if ARGV.include? '--with-check' system "make install" end end
require 'formula' class GambitScheme <Formula url 'http://www.iro.umontreal.ca/~gambit/download/gambit/v4.5/source/gambc-v4_5_2.tgz' homepage 'http://dynamo.iro.umontreal.ca/~gambit/wiki/index.php/Main_Page' md5 '71bd4b5858f807c4a8ce6ce68737db16' def options [ ['--with-check', 'Execute "make check" before installing. Runs some basic scheme programs to ensure that gsi and gsc are working'], ['--enable-shared', 'Build Gambit Scheme runtime as shared library'] ] end def install # Gambit Scheme currently fails to build with llvm-gcc # (ld crashes during the build process) ENV.gcc_4_2 # Gambit Scheme doesn't like full optimizations ENV.O2 configure_args = [ "--prefix=#{prefix}", "--disable-debug", # Recommended to improve the execution speed and compactness # of the generated executables. Increases compilation times. "--enable-single-host" ] configure_args << "--enable-shared" if ARGV.include? '--enable-shared' system "./configure", *configure_args system "make check" if ARGV.include? '--with-check' system "make install" end end
Update the SHA256 checksum in the Homebrew cask for the v1.5.0 binary.
cask 'awsaml' do version '1.5.0' sha256 '3f3aa01510627eafead8a205dda2423b3f5c8b36afd4dfc777cdb5781b30fe6b' url "https://github.com/rapid7/awsaml/releases/download/v#{version}/awsaml-v#{version}-darwin-x64.zip" appcast 'https://github.com/rapid7/awsaml/releases.atom', checkpoint: '3d2a662d80c619406bac6682158d8b89320b9d5359863cfbeddd574b00019e9a' name 'awsaml' homepage 'https://github.com/rapid7/awsaml' license :mit app 'Awsaml.app' end
cask 'awsaml' do version '1.5.0' sha256 'fd1d22780e47dd13ba2507c9a4661aa259d77e606fb9527a680342414dc6a2aa' url "https://github.com/rapid7/awsaml/releases/download/v#{version}/awsaml-v#{version}-darwin-x64.zip" appcast 'https://github.com/rapid7/awsaml/releases.atom', checkpoint: '3d2a662d80c619406bac6682158d8b89320b9d5359863cfbeddd574b00019e9a' name 'awsaml' homepage 'https://github.com/rapid7/awsaml' license :mit app 'Awsaml.app' end
Use the local properties datastream to avoid a deprecation warning
class Collection < ActiveFedora::Base include Hydra::Collection include CurationConcern::CollectionModel include Hydra::Collections::Collectible def can_be_member_of_collection?(collection) collection == self ? false : true end end
class Collection < ActiveFedora::Base include Hydra::Collection # override the default Hydra properties so we don't get a prefix deprecation warning. has_metadata "properties", type: Worthwhile::PropertiesDatastream include CurationConcern::CollectionModel include Hydra::Collections::Collectible def can_be_member_of_collection?(collection) collection == self ? false : true end end
Remove description method from Comment linter
module SCSSLint # Checks for uses of renderable comments (/* ... */) class Linter::Comment < Linter include LinterRegistry def visit_comment(node) add_lint(node) unless node.invisible? end def description 'Use // comments everywhere' end end end
module SCSSLint # Checks for uses of renderable comments (/* ... */) class Linter::Comment < Linter include LinterRegistry def visit_comment(node) add_lint(node, 'Use `//` comments everywhere') unless node.invisible? end end end