Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix a json rendering error (the easy way)
class SearchController < ApplicationController def index return if params[:q].blank? @query = params[:q].strip @result = {games: [Game.find_by(shortname: @query)]} if @result[:games][0].present? @result[:runs] = @result[:games][0].runs else @result = { users: User.search(@query), games: Game.search(@query) } @result[:runs] = Run.joins(:category).where(categories: {game_id: @result[:games]}).page(params[:page]) end respond_to do |format| format.json { render json: @result } format.html { render :index } end end end
class SearchController < ApplicationController def index return if params[:q].blank? @query = params[:q].strip @result = {games: [Game.find_by(shortname: @query)]} if @result[:games][0].present? @result[:runs] = @result[:games][0].runs else @result = { users: User.search(@query), games: Game.search(@query) } @result[:runs] = Run.joins(:category).where(categories: {game_id: @result[:games]}).page(params[:page]) end end end
Reset ImmediateExecutor to original state.
require_relative 'executor' module Concurrent class ImmediateExecutor include Executor def post(*args, &task) raise ArgumentError.new('no block given') unless block_given? task.call(*args) return true end end end
module Concurrent class ImmediateExecutor def post(*args, &task) raise ArgumentError.new('no block given') unless block_given? task.call(*args) return true end def <<(task) post(&task) self end end end
Fix the respond_to? def on Company
require 'arid_cache' class User < ActiveRecord::Base has_many :companies, :foreign_key => :owner_id has_many :empty_user_relations # This must always return an empty list send(Rails.rails3? ? :scope : :named_scope, :companies, :joins => :companies) send(Rails.rails3? ? :scope : :named_scope, :successful, :joins => :companies, :conditions => 'companies.employees > 50', :group => 'users.id') def big_companies companies.find :all, :conditions => [ 'employees > 20' ] end def pet_names ['Fuzzy', 'Peachy'] end def method_missing(method, *args) if method == :is_high? true else super end end def respond_to?(method) if method == :respond_not_overridden true else super end end end
require 'arid_cache' class User < ActiveRecord::Base has_many :companies, :foreign_key => :owner_id has_many :empty_user_relations # This must always return an empty list send(Rails.rails3? ? :scope : :named_scope, :companies, :joins => :companies) send(Rails.rails3? ? :scope : :named_scope, :successful, :joins => :companies, :conditions => 'companies.employees > 50', :group => 'users.id') def big_companies companies.find :all, :conditions => [ 'employees > 20' ] end def pet_names ['Fuzzy', 'Peachy'] end def method_missing(method, *args) if method == :is_high? true else super end end def respond_to?(method, include_private=false) if method == :respond_not_overridden true else super end end end
Add rdoc generation to gem and bump version slightly
Gem::Specification.new do |s| s.name = "rb232" s.version = "0.2.0" s.date = "2008-08-19" s.summary = "A simple serial port library for Ruby" s.email = "james@floppy.org.uk" s.homepage = "http://github.com/Floppy/rb232" s.has_rdoc = false s.authors = ["James Smith"] s.files = ["README", "COPYING", "extconf.rb"] s.files += ['src/port.c', 'src/port.h', 'src/rb232.c', 'src/utility.c', 'src/utility.h'] s.files += ['lib/rb232/text_protocol.rb'] s.files += ['examples/listen.rb'] s.extensions << 'extconf.rb' end
Gem::Specification.new do |s| s.name = "rb232" s.version = "0.2.1" s.date = "2008-08-20" s.summary = "A simple serial port library for Ruby" s.email = "james@floppy.org.uk" s.homepage = "http://github.com/Floppy/rb232" s.has_rdoc = true s.authors = ["James Smith"] s.files = ["README", "COPYING", "extconf.rb"] s.files += ['src/port.c', 'src/port.h', 'src/rb232.c', 'src/utility.c', 'src/utility.h'] s.files += ['lib/rb232/text_protocol.rb'] s.files += ['examples/listen.rb'] s.extensions << 'extconf.rb' end
Send the same data to rummager as content-store
class SearchPayloadPresenter attr_reader :registerable_edition delegate :slug, :title, :description, :indexable_content, :public_timestamp, :artefact, :format, to: :registerable_edition def initialize(registerable_edition) @registerable_edition = registerable_edition end def self.present(registerable_edition) new(registerable_edition).present end def present { content_id: artefact.content_id, rendering_app: "publisher", publishing_app: "publisher", format: format.underscore, title: title, description: description, indexable_content: indexable_content, link: "/#{slug}", public_timestamp: public_timestamp, content_store_document_type: artefact.kind, } end end
class SearchPayloadPresenter attr_reader :registerable_edition delegate :slug, :title, :description, :indexable_content, :public_timestamp, :artefact, :format, to: :registerable_edition def initialize(registerable_edition) @registerable_edition = registerable_edition end def self.present(registerable_edition) new(registerable_edition).present end def present { content_id: artefact.content_id, rendering_app: publishing_api_payload.fetch(:rendering_app), publishing_app: publishing_api_payload.fetch(:publishing_app), format: format.underscore, title: title, description: description, indexable_content: indexable_content, link: "/#{slug}", public_timestamp: public_timestamp, content_store_document_type: publishing_api_payload.fetch(:document_type), } end def publishing_api_payload @publishing_api_payload ||= begin presenter = EditionPresenterFactory.get_presenter(registerable_edition) presenter.render_for_publishing_api end end end
Add test for model updating
require 'test_helper' class RailsOps::Operation::Model::UpdateTest < ActiveSupport::TestCase include TestHelper BASIC_OP = Class.new(RailsOps::Operation::Model::Update) do model Group end def test_basic g = Group.create op = BASIC_OP.new(id: g.id) assert_equal g.id, op.model.id assert op.model.class < Group end def test_parent_op g = Group.create op = BASIC_OP.new(id: g.id) assert_equal op, op.model.parent_op end end
Disable event file watcher in dummy Rails app.
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false config.eager_load = true # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle caching. if Rails.root.join('tmp', 'caching-dev.txt').exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker end
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false config.eager_load = true # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle caching. if Rails.root.join('tmp', 'caching-dev.txt').exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. # config.file_watcher = ActiveSupport::EventedFileUpdateChecker end
Use thread local for storing connection pool
require "monitor" module SSHKit module Backend class ConnectionPool attr_accessor :idle_timeout def initialize self.idle_timeout = 30 @connections = {} @monitor = Monitor.new end def create_or_reuse_connection(*new_connection_args, &block) # Optimization: completely bypass the pool if idle_timeout is zero. return yield(*new_connection_args) if idle_timeout == 0 key = new_connection_args.to_s entry = find_and_reject_invalid(key) { |e| e.expired? || e.closed? } if entry.nil? entry = store_entry(key, yield(*new_connection_args)) end entry.expires_at = Time.now + idle_timeout if idle_timeout entry.connection end private def find_and_reject_invalid(key, &block) synchronize do entry = @connections[key] invalid = entry && yield(entry) @connections.delete(entry) if invalid invalid ? nil : entry end end def store_entry(key, connection) synchronize do @connections[key] = Entry.new(connection) end end def synchronize(&block) @monitor.synchronize(&block) end Entry = Struct.new(:connection) do attr_accessor :expires_at def expired? expires_at && Time.now > expires_at end def closed? connection.respond_to?(:closed?) && connection.closed? end end end end end
require "monitor" module SSHKit module Backend class ConnectionPool attr_accessor :idle_timeout def initialize self.idle_timeout = 30 @monitor = Monitor.new end def create_or_reuse_connection(*new_connection_args, &block) # Optimization: completely bypass the pool if idle_timeout is zero. return yield(*new_connection_args) if idle_timeout == 0 key = new_connection_args.to_s entry = find_and_reject_invalid(key) { |e| e.expired? || e.closed? } if entry.nil? entry = store_entry(key, yield(*new_connection_args)) end entry.expires_at = Time.now + idle_timeout if idle_timeout entry.connection end private def connections Thread.current[:sshkit_pool] ||= {} end def find_and_reject_invalid(key, &block) synchronize do entry = connections[key] invalid = entry && yield(entry) connections.delete(entry) if invalid invalid ? nil : entry end end def store_entry(key, connection) synchronize do connections[key] = Entry.new(connection) end end def synchronize(&block) @monitor.synchronize(&block) end Entry = Struct.new(:connection) do attr_accessor :expires_at def expired? expires_at && Time.now > expires_at end def closed? connection.respond_to?(:closed?) && connection.closed? end end end end end
Rename cookie to break sessions
# Be sure to restart your server when you modify this file. Dashboard::Application.config.session_store :cookie_store, key: '_dashboard_session', :httponly => false, domain: :all
# Be sure to restart your server when you modify this file. Dashboard::Application.config.session_store :cookie_store, key: '_learn_session', :httponly => false, domain: :all
Convert depends into a recommends
name 'logstash' maintainer 'Peter Donald' maintainer_email 'peter@realityforge.org' license 'Apache 2.0' description 'Installs/Configures logstash in agent mode' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.0.1' depends 'java' depends 'authbind'
name 'logstash' maintainer 'Peter Donald' maintainer_email 'peter@realityforge.org' license 'Apache 2.0' description 'Installs/Configures logstash in agent mode' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.0.1' depends 'java' recommends 'authbind'
Add test for project collections
require 'spec_helper' describe KeenCli::CLI do it 'prints help by default' do _, options = KeenCli::CLI.start expect(_).to be_empty end it 'prints version info if -v is used' do _, options = KeenCli::CLI.start(%w[-v]) expect(_).to match /version/ end describe 'project:describe' do it 'gets the project' do _, options = KeenCli::CLI.start(%w[project:describe]) expect(_).to match /\/3.0\/projects\/#{Keen.project_id}\/events/ end end end
require 'spec_helper' describe KeenCli::CLI do it 'prints help by default' do _, options = KeenCli::CLI.start expect(_).to be_empty end it 'prints version info if -v is used' do _, options = KeenCli::CLI.start(%w[-v]) expect(_).to match /version/ end describe 'project:describe' do it 'gets the project' do _, options = KeenCli::CLI.start(%w[project:describe]) expect(_).to match /\/3.0\/projects\/#{Keen.project_id}\/events/ end end describe 'project:collections' do it 'prints the project\'s collections' do _, options = KeenCli::CLI.start(%w[project:collections]) expect(_["properties"]["keen.timestamp"]).to eq 'datetime' end end end
Update wording of test to be more specific to what it does
require 'spec_helper' describe Asset do describe "creating an asset" do it "should be valid given a file" do a = Asset.new(:file => load_fixture_file("asset.png")) a.should be_valid end it "should not be valid without a file" do a = Asset.new(:file => nil) a.should_not be_valid end it "should be created" do CarrierWave::Mount::Mounter.any_instance.expects(:store!) a = Asset.new(:file => load_fixture_file("asset.png")) a.save a.should be_persisted end end end
require "spec_helper" describe Asset do describe "creating an asset" do it "should be valid given a file" do a = Asset.new(:file => load_fixture_file("asset.png")) a.should be_valid end it "should not be valid without a file" do a = Asset.new(:file => nil) a.should_not be_valid end it "should be persisted" do CarrierWave::Mount::Mounter.any_instance.expects(:store!) a = Asset.new(:file => load_fixture_file("asset.png")) a.save a.should be_persisted end end end
Support different regions for the same language
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :mobile_filter_header before_action :set_locale def mobile_filter_header @mobile = true end def mobile_filter_header @mobile = true end def set_locale I18n.locale = http_accept_language.compatible_language_from(I18n.available_locales) end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :mobile_filter_header before_action :set_locale def mobile_filter_header @mobile = true end def mobile_filter_header @mobile = true end def set_locale I18n.locale = http_accept_language.language_region_compatible_from(I18n.available_locales) end end
Add encrypt and decrypt method to application controller
# frozen_string_literal: true class ApplicationController < ActionController::Base protect_from_forgery with: :null_session end
# frozen_string_literal: true class ApplicationController < ActionController::Base protect_from_forgery with: :null_session def encrypt_by_secret_key(value) crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base) crypt.encrypt_and_sign(value) end def decrypt_by_secret_key(value) crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base) crypt.decrypt_and_verify(value) end end
Call reload rather than passing true, underyling api changed
class SourceDetailPresenter < SourcePresenter def as_json(opts = {}) super.merge( { abstract: source.abstract, source_suggestions: source.source_suggestions.map { |ss| SourceSuggestionBrowseRowPresenter.new(ss) }, author_list: author_list, asco_presenter: source.asco_presenter, author_string: source.author_string, } ) end private def author_list source.authors_sources(1).reject { |as| as.fore_name.blank? && as.last_name.blank? }.map do |as| { fore_name: as.fore_name, last_name: as.last_name, position: as.author_position, } end end end
class SourceDetailPresenter < SourcePresenter def as_json(opts = {}) super.merge( { abstract: source.abstract, source_suggestions: source.source_suggestions.map { |ss| SourceSuggestionBrowseRowPresenter.new(ss) }, author_list: author_list, asco_presenter: source.asco_presenter, author_string: source.author_string, } ) end private def author_list source.authors_sources.reload.reject { |as| as.fore_name.blank? && as.last_name.blank? }.map do |as| { fore_name: as.fore_name, last_name: as.last_name, position: as.author_position, } end end end
Add some other stuff to the gemspec
Gem::Specification.new do |s| s.name = "bus-o-matic" s.version = "0.0.2" s.authors = ["Matt Cone"] s.email = ["matt@macinstruct.com"] s.summary = %q{A wrapper for the Pittsburgh Port Authority TrueTime Bus API} s.description = %q{A wrapper for the Pittsburgh Port Authority TrueTime Bus API} s.homepage = "https://github.com/mattcone/bus-o-matic" s.license = "MIT" spec.add_runtime_dependency "httparty" spec.add_runtime_dependency "hashie" end
Gem::Specification.new do |s| s.name = "bus-o-matic" s.version = "0.0.3" s.authors = ["Matt Cone"] s.email = ["matt@macinstruct.com"] s.summary = %q{A wrapper for the Pittsburgh Port Authority TrueTime Bus API} s.description = %q{A wrapper for the Pittsburgh Port Authority TrueTime Bus API} s.homepage = "https://github.com/mattcone/bus-o-matic" s.license = "MIT" s.platform = Gem::Platform::RUBY s.require_paths = ['lib'] s.files = Dir.glob("**/*").reject { |x| File.directory?(x) } s.add_dependency "httparty", '~> 0.10.2' s.add_dependency "hashie", '~> 2.0' end
Allow (partial) blank values for near scope
# frozen_string_literal: true class Api::V2::CanteensController < Api::BaseController respond_to :json has_scope :near, using: %i[lat lng dist place] do |_controller, scope, value| place = if value[3] value[3].to_s else [value[0].to_f, value[1].to_f] end if place scope.reorder("").near( place, value[2] ? value[2].to_f : 10, units: :km, order_by_without_select: :distance ) else scope end end has_scope :ids do |_controller, scope, value| ids = value.split(",").map(&:to_i).select(&:positive?).uniq scope.where(id: ids) end has_scope :hasCoordinates do |_controller, scope, value| if value != "false" && value != "0" && value scope.where("latitude IS NOT NULL and longitude IS NOT NULL") else scope.where("latitude IS NULL and longitude IS NULL") end end def find_collection apply_scopes Canteen.active.order(:id) end def find_resource canteen = super if canteen.replaced? canteen.replaced_by else canteen end end end
# frozen_string_literal: true class Api::V2::CanteensController < Api::BaseController respond_to :json has_scope :near, using: %i[lat lng dist place], allow_blank: true do |_controller, scope, value| place = if value[3] value[3].to_s else [value[0].to_f, value[1].to_f] end if place scope.reorder("").near( place, value[2] ? value[2].to_f : 10, units: :km, order_by_without_select: :distance ) else scope end end has_scope :ids do |_controller, scope, value| ids = value.split(",").map(&:to_i).select(&:positive?).uniq scope.where(id: ids) end has_scope :hasCoordinates do |_controller, scope, value| if value != "false" && value != "0" && value scope.where("latitude IS NOT NULL and longitude IS NOT NULL") else scope.where("latitude IS NULL and longitude IS NULL") end end def find_collection apply_scopes Canteen.active.order(:id) end def find_resource canteen = super if canteen.replaced? canteen.replaced_by else canteen end end end
Add earth_date method to Photo class
module ExploreMars class Photo attr_reader :src, :sol, :camera def initialize(src, sol, camera) @src = src @sol = sol @camera = camera end def to_s @src end end end
module ExploreMars class Photo attr_reader :src, :sol, :camera LANDING_DATE = DateTime.new(2012,8,6,5,17,57) SOL_IN_SECONDS = 88775.244 def initialize(src, sol, camera) @src = src @sol = sol @camera = camera end def to_s @src end def earth_date date = LANDING_DATE + (@sol.to_i * SOL_IN_SECONDS).seconds date.strftime("%b %e, %Y") end end end
Configure in app.after_configuration and expose internal sprockets_app
require 'middleman-core' require 'middleman/jasmine/jasmine_sprockets_proxy' module Middleman module Jasmine class << self def registered(app, options_hash={}, &block) @options = OpenStruct.new(default_options.merge(options_hash)) yield @options if block_given? app.map(@options.jasmine_url) { run ::JasmineSprocketsProxy.new } jasmine_asset_folders.each do |item| app.map("/#{item}") { run ::JasmineSprocketsProxy.new(item) } end end private def jasmine_asset_folders [ "__jasmine__", "__boot__", "__spec__", @options.fixtures_dir ] end def default_options { jasmine_url: "/jasmine", fixtures_dir: "spec/javascripts/fixtures" } end alias :included :registered end end end
require 'middleman-core' require 'middleman/jasmine/jasmine_sprockets_proxy' module Middleman module Jasmine class << self def registered(app, options_hash={}, &block) app.send :include, InstanceMethods options = OpenStruct.new(default_options.merge(options_hash)) yield options if block_given? app.map(options.jasmine_url) { run ::JasmineSprocketsProxy.new } jasmine_asset_folders(options.fixtures_dir).each do |item| app.map("/#{item}") { run ::JasmineSprocketsProxy.new(item) } end app.after_configuration do ::JasmineSprocketsProxy.configure(sprockets) end end private def jasmine_asset_folders(fixtures_dir) [ "__jasmine__", "__boot__", "__spec__", fixtures_dir ] end def default_options { jasmine_url: "/jasmine", fixtures_dir: "spec/javascripts/fixtures" } end alias :included :registered end module InstanceMethods def jasmine_sprockets ::JasmineSprocketsProxy.sprockets_app end end end end
Use latest fog version to avoid dependency problems.
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'vagrant-openstack-plugin/version' Gem::Specification.new do |gem| gem.name = "vagrant-openstack-plugin" gem.version = VagrantPlugins::OpenStack::VERSION gem.authors = ["Mitchell Hashimoto", "Thomas Kadauke"] gem.email = ["mitchell@hashicorp.com", "t.kadauke@cloudbau.de"] gem.description = "Enables Vagrant to manage machines in OpenStack Cloud." gem.summary = "Enables Vagrant to manage machines in OpenStack Cloud." gem.homepage = "http://www.vagrantup.com" gem.add_runtime_dependency "fog", ">= 1.10.1" gem.add_development_dependency "rake" gem.add_development_dependency "rspec", "~> 2.13.0" 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.require_paths = ["lib"] end
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'vagrant-openstack-plugin/version' Gem::Specification.new do |gem| gem.name = "vagrant-openstack-plugin" gem.version = VagrantPlugins::OpenStack::VERSION gem.authors = ["Mitchell Hashimoto", "Thomas Kadauke"] gem.email = ["mitchell@hashicorp.com", "t.kadauke@cloudbau.de"] gem.description = "Enables Vagrant to manage machines in OpenStack Cloud." gem.summary = "Enables Vagrant to manage machines in OpenStack Cloud." gem.homepage = "http://www.vagrantup.com" gem.add_runtime_dependency "fog", ">= 1.10.1" gem.add_development_dependency "rake" gem.add_development_dependency "rspec", "~> 2.13.0" 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.require_paths = ["lib"] end
Use the Bundler::LockfileParser to parse the lockfile.
module SevenScaleDeploy module BundlerSupport def bundler_dependencies(options = {}) root = options.delete(:root) # WARNING: This is highly Bundler 0.9 -specific YAML::load_file(File.join(root, 'Gemfile.lock'))['specs'].each do |spec| gem_name = spec.keys.first dependent_recipe = "#{gem_name.gsub(/-/, '_')}_gem_dependencies".to_sym if method_defined?(dependent_recipe) recipe(dependent_recipe, options) end end end end end
module SevenScaleDeploy module BundlerSupport def bundler_dependencies(options = {}) root = options.delete(:root) require 'bundler' Bundler::LockfileParser.new(File.read(File.join(root, 'Gemfile.lock'))).specs.each do |spec| gem_name = spec.name dependent_recipe = "#{gem_name.gsub(/-/, '_')}_gem_dependencies".to_sym if method_defined?(dependent_recipe) recipe(dependent_recipe, options) end end end end end
Modify test to provide params in proper format
require 'test_helper' class DownloadControllerTest < ActionController::TestCase # RubyZip has a seemingly convenient Zip::ZipFile.open_buffer method - too bad it's totally borked # Various internal methods want the String passed in to have a path, monkey patching that in didn't work either # I would report a bug/pull request on it, but looks like they're in the middle of a pretty major re-write # Plus it doesn't like passing a Tempfile, since it's not a direct instance of IO (it uses DelegateClass) def zip_from_response( response ) Tempfile.open( 'testzip.zip', :encoding=>'binary' ) do | tf | tf.write response.body tf.flush File.open( tf.path ) do | zip_file | Zip::File.open( zip_file ) do | zf | yield zf end end end end it "downloads text" do get :bulk_download, :args=>[ doc.id.to_s, 'document_text'] assert_response :success zip_from_response( response ) do | zf | assert_equal doc.combined_page_text, zf.read( "#{doc.slug}.txt" ) end end it "sends the viewer" do get :bulk_download, :args=>[ doc.id.to_s, 'document_viewer'] assert_response :success zip_from_response( response ) do | zf | assert_match "<title>#{doc.title}</title>", zf.read( "#{doc.slug}.html" ) end end end
require 'test_helper' class DownloadControllerTest < ActionController::TestCase # RubyZip has a seemingly convenient Zip::ZipFile.open_buffer method - too bad it's totally borked # Various internal methods want the String passed in to have a path, monkey patching that in didn't work either # I would report a bug/pull request on it, but looks like they're in the middle of a pretty major re-write # Plus it doesn't like passing a Tempfile, since it's not a direct instance of IO (it uses DelegateClass) def zip_from_response( response ) Tempfile.open( 'testzip.zip', :encoding=>'binary' ) do | tf | tf.write response.body tf.flush File.open( tf.path ) do | zip_file | Zip::File.open( zip_file ) do | zf | yield zf end end end end it "downloads text" do get :bulk_download, :args=>"#{doc.id}/document_text" assert_response :success zip_from_response( response ) do | zf | assert_equal doc.combined_page_text, zf.read( "#{doc.slug}.txt" ) end end it "sends the viewer" do get :bulk_download, :args=>"#{doc.id}/document_viewer" assert_response :success zip_from_response( response ) do | zf | assert_match "<title>#{doc.title}</title>", zf.read( "#{doc.slug}.html" ) end end end
Add zip cookbook lwrp dependency
name 'wel-osx-apps' maintainer 'Wide Eye Labs' maintainer_email 'chris@wideeyelabs.com' license 'MIT' description 'Installs/Configures wel-osx-apps' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.0' supports 'mac_os_x' depends 'dmg'
name 'wel-osx-apps' maintainer 'Wide Eye Labs' maintainer_email 'chris@wideeyelabs.com' license 'MIT' description 'Installs/Configures wel-osx-apps' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.0' supports 'mac_os_x' depends 'dmg' depends 'zip'
Add ActiveRecord and ActiveSupport to gemspec
# -*- encoding: utf-8 -*- require File.expand_path('../lib/whiny_validation/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Brian Morearty"] gem.email = ["brian@morearty.org"] gem.description = %q{When an ActiveRecord model won't save because it's invalid, this gem writes the validation error messages to the log.} gem.summary = %q{Write ActiveRecord validation error messages to the log} gem.homepage = "" 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 = "whiny_validation" gem.require_paths = ["lib"] gem.version = WhinyValidation::VERSION gem.add_development_dependency 'rake' end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/whiny_validation/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Brian Morearty"] gem.email = ["brian@morearty.org"] gem.description = %q{When an ActiveRecord model won't save because it's invalid, this gem writes the validation error messages to the log.} gem.summary = %q{Write ActiveRecord validation error messages to the log} gem.homepage = "" 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 = "whiny_validation" gem.require_paths = ["lib"] gem.version = WhinyValidation::VERSION gem.add_dependency 'activesupport' gem.add_dependency 'activerecord' gem.add_development_dependency 'rake' end
Check for a service name referenced but not loaded from services.yml, and raise a meaningful exception.
class ServiceList private_class_method :new @@services = nil def self.get(name) @@services = YAML.load_file(RAILS_ROOT+"/config/services.yml") unless @@services require 'service_adaptors/'+@@services[name]["type"].underscore return Kernel.const_get(@@services[name]["type"]).new(@@services[name].merge({"id"=>name})) end end
class ServiceList private_class_method :new @@services = nil def self.get(name) @@services = YAML.load_file(RAILS_ROOT+"/config/services.yml") unless @@services if (@@services[name].nil?) raise NameError.new("No such service named #{name} has been loaded. Check config/services.yml", name) end require 'service_adaptors/'+@@services[name]["type"].underscore className = @@services[name]["type"] classConst = Kernel.const_get(className)\ return classConst.new(@@services[name].merge({"id"=>name})) end end
Set currently active channels on restart
# encoding: utf-8 module Plugins class CheckDCTV include Cinch::Plugin listen_to :check_dctv def initialize(*args) super end def listen(m) channels = get_current_channels channels.each do |channel| output = "Ch. #{channel['channel']} - #{channel['friendlyalias']}" output += " - Live" if is_live(channel) output += " - Upcoming" if is_upcoming(channel) @bot.log(output) end end private def get_current_channels response = Net::HTTP.get_response(URI.parse('http://diamondclub.tv/api/channelsv2.php?v=3')) return JSON.parse(response.body)['assignedchannels'] end end end
# encoding: utf-8 module Plugins class CheckDCTV include Cinch::Plugin listen_to :check_dctv def initialize(*args) super # Set announced arrays so as to not re-announce what's already on @live_channels = Array.new @soon_channels = Array.new get_current_channels.each do |channel| @live_channels << channel if is_live channel @soon_channels << channel if is_upcoming channel end end def listen(m) channels = get_current_channels channels.each do |channel| output = "Ch. #{channel['channel']} - #{channel['friendlyalias']}" output += " - Live" if is_live(channel) output += " - Upcoming" if is_upcoming(channel) @bot.log(output) end end private def get_current_channels response = Net::HTTP.get_response(URI.parse('http://diamondclub.tv/api/channelsv2.php?v=3')) return JSON.parse(response.body)['assignedchannels'] end def is_live(channel) return channel['nowonline'] == 'yes' && !channel['yt_upcoming'] end def is_upcoming(channel) return channel['nowonline'] == 'no' && channel['yt_upcoming'] end end end
Fix gemspec path to README.rb
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "formalwear/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "formalwear" s.version = Formalwear::VERSION s.authors = ["Zac Wasielewski"] s.email = ["zac@wasielewski.org"] s.homepage = "https://github.com/zacwasielewski/formalwear" s.summary = "Rails FormBuilder extension for generating Bootstrap markup" s.description = "Formalwear dresses up your Ruby on Rails forms with Bootstrap-compatible markup." s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 3.2.3" s.add_development_dependency "sqlite3" end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "formalwear/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "formalwear" s.version = Formalwear::VERSION s.authors = ["Zac Wasielewski"] s.email = ["zac@wasielewski.org"] s.homepage = "https://github.com/zacwasielewski/formalwear" s.summary = "Rails FormBuilder extension for generating Bootstrap markup" s.description = "Formalwear dresses up your Ruby on Rails forms with Bootstrap-compatible markup." s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rb"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 3.2.3" s.add_development_dependency "sqlite3" end
Update order of called recipes
# # Cookbook Name:: cookbook-ngxmgdbpy # Recipe:: default # # Author:: Juan Manuel Lopez # # 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 "cookbook-core" include_recipe "cookbook-ngxmgdbphp::php" include_recipe "cookbook-ngxmgdbphp::nginx" include_recipe "cookbook-ngxmgdbphp::mongodb"
# # Cookbook Name:: cookbook-ngxmgdbpy # Recipe:: default # # Author:: Juan Manuel Lopez # # 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 "cookbook-core" include_recipe "cookbook-ngxmgdbphp::mongodb" include_recipe "cookbook-ngxmgdbphp::php" include_recipe "cookbook-ngxmgdbphp::nginx"
Add ability to save multiple addresses on new org to manipulator and change not empty to present
module Users module OrganizationManipulator extend ActiveSupport::Concern def can_create_organization? super_admin? end def can_update_organization? admin? end def can_update_organization_at?(organization) admin_at?(organization) end def can_update_organization_name? super_admin? end def can_update_organization_county? super_admin? end def create_organization(params) raise PermissionError unless can_create_organization? org_params = params.require(:organization) Organization.create! org_params.permit(:name, :address, :county, :phone_number, :email) end def update_organization(params) transaction do org = Organization.find(params[:id]) raise PermissionError unless can_update_organization_at?(org) org_params = params.require(:organization) org_params[:addresses_attributes].select! { |_, h| !h[:address].empty? } permitted_params = [:phone_number, :email, addresses_attributes: [:address, :id, :_destroy]] permitted_params << :county if can_update_organization_county? permitted_params << :name if can_update_organization_name? org.update! org_params.permit(permitted_params) end end end end
module Users module OrganizationManipulator extend ActiveSupport::Concern def can_create_organization? super_admin? end def can_update_organization? admin? end def can_update_organization_at?(organization) admin_at?(organization) end def can_update_organization_name? super_admin? end def can_update_organization_county? super_admin? end def create_organization(params) raise PermissionError unless can_create_organization? org_params = params.require(:organization) org_params[:addresses_attributes].select! { |_, h| h[:address].present? } Organization.create! org_params.permit(:name, :phone_number, :email, addresses_attributes: [:address, :id]) end def update_organization(params) transaction do org = Organization.find(params[:id]) raise PermissionError unless can_update_organization_at?(org) org_params = params.require(:organization) org_params[:addresses_attributes].select! { |_, h| h[:address].present? } permitted_params = [:phone_number, :email, addresses_attributes: [:address, :id, :_destroy]] permitted_params << :county if can_update_organization_county? permitted_params << :name if can_update_organization_name? org.update! org_params.permit(permitted_params) end end end end
Append .o to all object file names.
require 'udis86/ud' module Helpers FILES_DIR = File.expand_path(File.join(File.dirname(__FILE__),'files')) def ud_file(name) UD.open(File.join(FILES_DIR,name.to_s)) end end
require 'udis86/ud' module Helpers FILES_DIR = File.expand_path(File.join(File.dirname(__FILE__),'files')) def ud_file(name) UD.open(File.join(FILES_DIR,"#{name}.o")) end end
Add a spec for gathering error messages
require 'dry/validation/contract' RSpec.describe Dry::Validation::Contract, '#call' do subject(:contract) do Class.new(Dry::Validation::Contract) do params do required(:email).filled(:string) required(:age).filled(:integer) optional(:login).maybe(:string, :filled?) optional(:password).maybe(:string, min_size?: 10) optional(:password_confirmation).maybe(:string) end rule(:password) do if params[:login] && !params[:password] failure("is required") end end rule(:age) do if params[:age] < 18 failure("must be greater or equal 18") end end end.new end it "applies rule to input processed by the schema" do result = contract.(email: "john@doe.org", age: 19) expect(result.errors).to eql({}) end it "returns rule errors" do result = contract.(email: "john@doe.org", login: "jane", age: 19) expect(result.errors).to eql(password: ["is required"]) end it "doesn't execute rules when basic checks failed" do result = contract.(email: "john@doe.org", age: "not-an-integer") expect(result.errors).to eql(age: ["must be an integer"]) end end
require 'dry/validation/contract' RSpec.describe Dry::Validation::Contract, '#call' do subject(:contract) do Class.new(Dry::Validation::Contract) do params do required(:email).filled(:string) required(:age).filled(:integer) optional(:login).maybe(:string, :filled?) optional(:password).maybe(:string, min_size?: 10) optional(:password_confirmation).maybe(:string) end rule(:password) do if params[:login] && !params[:password] failure("is required") end end rule(:age) do if params[:age] < 18 failure("must be greater or equal 18") end end rule(:age) do if params[:age] < 0 failure("must be greater than 0") end end end.new end it "applies rule to input processed by the schema" do result = contract.(email: "john@doe.org", age: 19) expect(result.errors).to eql({}) end it "returns rule errors" do result = contract.(email: "john@doe.org", login: "jane", age: 19) expect(result.errors).to eql(password: ["is required"]) end it "doesn't execute rules when basic checks failed" do result = contract.(email: "john@doe.org", age: "not-an-integer") expect(result.errors).to eql(age: ["must be an integer"]) end it "gathers errors from multiple rules for the same key" do result = contract.(email: 'john@doe.org', age: -1) expect(result.errors).to eql(age: ["must be greater or equal 18", "must be greater than 0"]) end end
Change back to actual path
class TrackingDetailsController < ApplicationController active_tab "tracking_details" def new @tracking_detail = TrackingDetail.new end def create @tracking_detail = TrackingDetail.new shipment_params if @tracking_detail.save flash[:success] = "TrackingDetail created!" redirect_to @tracking_detail else flash[:error] = "There was an error saving this shipment." render "new" end end def update @tracking_detail = TrackingDetail.find(params[:id]) update_shipment_status! @tracking_detail.save redirect_to edit_order_path(@tracking_detail.order) end def destroy shipment = TrackingDetail.find(params[:id]) shipment.destroy flash[:success] = "Tracking number #{shipment.tracking_number} for order #{shipment.order_id} deleted!" redirect_to :back end private def update_shipment_status! return if params[:status].blank? @tracking_detail.delivery_date = Time.zone.now if params[:status] == "delivered" end def shipment_params params.require(:shipment).permit(:shipping_carrier, :tracking_number) end end
class TrackingDetailsController < ApplicationController active_tab "tracking_details" def new @tracking_detail = TrackingDetail.new end def create @tracking_detail = TrackingDetail.new shipment_params if @tracking_detail.save flash[:success] = "TrackingDetail created!" redirect_to @tracking_detail else flash[:error] = "There was an error saving this shipment." render "new" end end def update @tracking_detail = TrackingDetail.find(params[:id]) update_shipment_status! @tracking_detail.save redirect_to edit_order_path(@tracking_detail.order) end def destroy shipment = TrackingDetail.find(params[:id]) shipment.destroy flash[:success] = "Tracking number #{shipment.tracking_number} for order #{shipment.order_id} deleted!" redirect_to edit_order_path(shipment.order) end private def update_shipment_status! return if params[:status].blank? @tracking_detail.delivery_date = Time.zone.now if params[:status] == "delivered" end def shipment_params params.require(:shipment).permit(:shipping_carrier, :tracking_number) end end
Reduce size of the gem by only including the necessary files via gemspec
# -*- encoding: utf-8 -*- $LOAD_PATH.push File.expand_path('../lib', __FILE__) require 'pronto/flay/version' Gem::Specification.new do |s| s.name = 'pronto-flay' s.version = Pronto::FlayVersion::VERSION s.platform = Gem::Platform::RUBY s.author = 'Mindaugas Mozūras' s.email = 'mindaugas.mozuras@gmail.com' s.homepage = 'http://github.org/mmozuras/pronto-flay' s.summary = 'Pronto runner for Flay, structural similarities analyzer' s.required_rubygems_version = '>= 1.3.6' s.license = 'MIT' s.files = Dir.glob('{lib}/**/*') + %w(LICENSE README.md) s.test_files = `git ls-files -- {spec}/*`.split("\n") s.require_paths = ['lib'] s.add_dependency 'pronto', '~> 0.4.0' s.add_dependency 'flay', '~> 2.6.0' s.add_development_dependency 'rake', '~> 10.3' s.add_development_dependency 'rspec', '~> 3.0' s.add_development_dependency 'rspec-its', '~> 1.0' end
# -*- encoding: utf-8 -*- # $LOAD_PATH.push File.expand_path('../lib', __FILE__) require 'pronto/flay/version' Gem::Specification.new do |s| s.name = 'pronto-flay' s.version = Pronto::FlayVersion::VERSION s.platform = Gem::Platform::RUBY s.author = 'Mindaugas Mozūras' s.email = 'mindaugas.mozuras@gmail.com' s.homepage = 'http://github.org/mmozuras/pronto-flay' s.summary = 'Pronto runner for Flay, structural similarities analyzer' s.licenses = ['MIT'] s.required_ruby_version = '>= 1.9.3' s.rubygems_version = '1.8.23' s.files = `git ls-files`.split($RS).reject do |file| file =~ %r{^(?: spec/.* |Gemfile |Rakefile |\.rspec |\.gitignore |\.rubocop.yml |\.travis.yml )$}x end s.test_files = [] s.extra_rdoc_files = ['LICENSE', 'README.md'] s.require_paths = ['lib'] s.add_dependency 'pronto', '~> 0.4.0' s.add_dependency 'flay', '~> 2.6.0' s.add_development_dependency 'rake', '~> 10.3' s.add_development_dependency 'rspec', '~> 3.0' s.add_development_dependency 'rspec-its', '~> 1.0' end
Add test for adjust_country_name method
# frozen_string_literal: false require 'spec_helper' RSpec.describe Portal::Country, type: :model do # TODO: auto-generated describe '.csv_filemame' do it 'csv_filemame' do result = described_class.csv_filemame expect(result).not_to be_nil end end # TODO: auto-generated describe '.from_csv_file' do it 'from_csv_file' do result = described_class.from_csv_file expect(result).not_to be_nil end end # TODO: auto-generated describe '.remap_keys' do it 'remap_keys' do in_hash = {} result = described_class.remap_keys(in_hash) expect(result).not_to be_nil end end # TODO: auto-generated describe '.field_name_map' do it 'field_name_map' do result = described_class.field_name_map expect(result).not_to be_nil end end describe '.from_hash' do it 'from_hash' do in_hash = {:name => "Utopia"} result = described_class.from_hash(in_hash) expect(result).not_to be_nil end end end
# frozen_string_literal: false require 'spec_helper' RSpec.describe Portal::Country, type: :model do # TODO: auto-generated describe '.csv_filemame' do it 'csv_filemame' do result = described_class.csv_filemame expect(result).not_to be_nil end end # TODO: auto-generated describe '.from_csv_file' do it 'from_csv_file' do result = described_class.from_csv_file expect(result).not_to be_nil end end # TODO: auto-generated describe '.remap_keys' do it 'remap_keys' do in_hash = {} result = described_class.remap_keys(in_hash) expect(result).not_to be_nil end end # TODO: auto-generated describe '.field_name_map' do it 'field_name_map' do result = described_class.field_name_map expect(result).not_to be_nil end end describe '.from_hash' do it 'from_hash' do in_hash = {:name => "Utopia"} result = described_class.from_hash(in_hash) expect(result).not_to be_nil end end describe '.adjust_country_name' do it 'adjust_country_name' do name = 'US' name = name.gsub(/^US$/, "United States") expect(name).not_to be_nil end end end
Add of dependencies to diffy and jrubyfx
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "jruby_visualizer/version" files = `git ls-files -- lib/* spec/* sample/*`.split("\n") Gem::Specification.new do |s| s.name = 'jruby_visualizer' s.version = JRubyVisualizer::VERSION s.platform = Gem::Platform::RUBY s.authors = ['Maximilian Konzack', 'Thomas E. Enebo'] s.email = ['maximilian.konzack@gmail.com', 'tom.enebo@gmail.com'] s.homepage = 'http://github.com/jruby/jruby-visualizer' s.summary = %q{A Gem for visualizing JRuby compiler artifacts} s.description = %q{A Gem for visualizing JRuby compiler artifacts} s.executables << 'jruby_visualizer' s.rubyforge_project = "jruby_visualizer" s.files = files s.test_files = `git ls-files -- spec/*`.split("\n") s.require_paths = ["lib"] s.has_rdoc = true end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "jruby_visualizer/version" files = `git ls-files -- lib/* spec/* sample/*`.split("\n") Gem::Specification.new do |s| s.name = 'jruby_visualizer' s.version = JRubyVisualizer::VERSION s.platform = Gem::Platform::RUBY s.authors = ['Maximilian Konzack', 'Thomas E. Enebo'] s.email = ['maximilian.konzack@gmail.com', 'tom.enebo@gmail.com'] s.homepage = 'http://github.com/jruby/jruby-visualizer' s.summary = %q{A Gem for visualizing JRuby compiler artifacts} s.description = %q{A Gem for visualizing JRuby compiler artifacts} s.executables << 'jruby_visualizer' s.add_dependency 'jrubyfx' s.add_dependency 'diffy' s.rubyforge_project = "jruby_visualizer" s.files = files s.test_files = `git ls-files -- spec/*`.split("\n") s.require_paths = ["lib"] s.has_rdoc = true end
Fix podspec validation (Use osx instead of mac)
Pod::Spec.new do |s| s.name = "UAAppReviewManager" s.version = "0.1.1" s.summary = "UAAppReviewManager is AppIRater all grown up. For iOS and OS X." s.description = <<-DESC UAAppReviewManager is AppIRater all grown up. It allows you to use it on iOS and Mac targets, allows affiliate links and it rewritten from the ground up for the modern app. DESC s.homepage = "https://github.com/UrbanApps/UAAppReviewManager" s.author = { "Matt Coneybeare" => "coneybeare@urbanapps.com" } s.license = 'MIT' s.ios.deployment_target = '5.1' s.osx.deployment_target = '10.7' s.requires_arc = true s.frameworks = 'CFNetwork', 'SystemConfiguration' s.weak_frameworks = 'StoreKit' s.source = { :git => "https://github.com/UrbanApps/UAAppReviewManager.git", :tag => s.version.to_s } s.source_files = "UAAppReviewManager.{h,m}" s.ios.resource_bundles = { 'UAAppReviewManager-iOS' => ['Localization/*.lproj'] } s.mac.resource_bundles = { 'UAAppReviewManager-OSX' => ['Localization/*.lproj'] } end
Pod::Spec.new do |s| s.name = "UAAppReviewManager" s.version = "0.1.1" s.summary = "UAAppReviewManager is AppIRater all grown up. For iOS and OS X." s.description = <<-DESC UAAppReviewManager is AppIRater all grown up. It allows you to use it on iOS and Mac targets, allows affiliate links and it rewritten from the ground up for the modern app. DESC s.homepage = "https://github.com/UrbanApps/UAAppReviewManager" s.author = { "Matt Coneybeare" => "coneybeare@urbanapps.com" } s.license = 'MIT' s.ios.deployment_target = '5.1' s.osx.deployment_target = '10.7' s.requires_arc = true s.frameworks = 'CFNetwork', 'SystemConfiguration' s.weak_frameworks = 'StoreKit' s.source = { :git => "https://github.com/UrbanApps/UAAppReviewManager.git", :tag => s.version.to_s } s.source_files = "UAAppReviewManager.{h,m}" s.ios.resource_bundles = { 'UAAppReviewManager-iOS' => ['Localization/*.lproj'] } s.osx.resource_bundles = { 'UAAppReviewManager-OSX' => ['Localization/*.lproj'] } end
Make `LoadInterlockAwareMonitor` work in Ruby 2.7
# frozen_string_literal: true require "monitor" module ActiveSupport module Concurrency # A monitor that will permit dependency loading while blocked waiting for # the lock. class LoadInterlockAwareMonitor < Monitor # Enters an exclusive section, but allows dependency loading while blocked def mon_enter mon_try_enter || ActiveSupport::Dependencies.interlock.permit_concurrent_loads { super } end end end end
# frozen_string_literal: true require "monitor" module ActiveSupport module Concurrency # A monitor that will permit dependency loading while blocked waiting for # the lock. class LoadInterlockAwareMonitor < Monitor EXCEPTION_NEVER = { Exception => :never }.freeze EXCEPTION_IMMEDIATE = { Exception => :immediate }.freeze private_constant :EXCEPTION_NEVER, :EXCEPTION_IMMEDIATE # Enters an exclusive section, but allows dependency loading while blocked def mon_enter mon_try_enter || ActiveSupport::Dependencies.interlock.permit_concurrent_loads { super } end def synchronize Thread.handle_interrupt(EXCEPTION_NEVER) do mon_enter begin Thread.handle_interrupt(EXCEPTION_IMMEDIATE) do yield end ensure mon_exit end end end end end end
Remove version for development dependencies
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'background_worker/version' Gem::Specification.new do |spec| spec.name = 'background_worker' spec.version = BackgroundWorker::VERSION spec.authors = ['Michael Noack', 'Adam Davies', 'Alessandro Berardi'] spec.email = ['development@travellink.com.au', 'adzdavies@gmail.com', 'berardialessandro@gmail.com'] spec.summary = %q{Background worker abstraction with status updates} spec.description = %q{See README for full details} spec.homepage = 'http://github.com/sealink/background_worker' 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.7' spec.add_development_dependency 'rake', '~> 10.0' end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'background_worker/version' Gem::Specification.new do |spec| spec.name = 'background_worker' spec.version = BackgroundWorker::VERSION spec.authors = ['Michael Noack', 'Adam Davies', 'Alessandro Berardi'] spec.email = ['development@travellink.com.au', 'adzdavies@gmail.com', 'berardialessandro@gmail.com'] spec.summary = %q{Background worker abstraction with status updates} spec.description = %q{See README for full details} spec.homepage = 'http://github.com/sealink/background_worker' 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' spec.add_development_dependency 'rake' end
Package version increased from 0.2.0.0 to 0.2.0.1
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'messaging' s.version = '0.2.0.0' s.summary = 'Messaging primitives for Eventide' s.description = ' ' s.authors = ['The Eventide Project'] s.email = 'opensource@eventide-project.org' s.homepage = 'https://github.com/eventide-project/messaging' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.2.3' s.add_runtime_dependency 'event_source' s.add_development_dependency 'test_bench' end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'messaging' s.version = '0.2.0.1' s.summary = 'Messaging primitives for Eventide' s.description = ' ' s.authors = ['The Eventide Project'] s.email = 'opensource@eventide-project.org' s.homepage = 'https://github.com/eventide-project/messaging' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.2.3' s.add_runtime_dependency 'event_source' s.add_development_dependency 'test_bench' end
Set htmlonly to true for cookie.
class UserSession < Authlogic::Session::Base # only session related configuration goes here, see documentation for sub modules of Authlogic::Session # other config goes in acts_as block logout_on_timeout(true) allow_http_basic_auth(false) # We handle our own basic auth def to_key new_record? ? nil : [ self.send(self.class.primary_key) ] end end
class UserSession < Authlogic::Session::Base # only session related configuration goes here, see documentation for sub modules of Authlogic::Session # other config goes in acts_as block logout_on_timeout(true) allow_http_basic_auth(false) # We handle our own basic auth httponly(true) def to_key new_record? ? nil : [ self.send(self.class.primary_key) ] end end
Add an argument to Reminisce::save
require "remindice/version" require "thor" module Remindice TASK_FILENAME = File.expand_path("~/.reamindice_tasks") class << self def tasks @@tasks.clone end def save file = File.open(TASK_FILENAME, "w") tasks.each do |i| file.puts i end end end class Commands < Thor @@tasks = if File.exists?(Remindice::TASK_FILENAME); File.readlines(Remindice::TASK_FILENAME) else [] end end end
require "remindice/version" require "thor" module Remindice TASK_FILENAME = File.expand_path("~/.reamindice_tasks") class << self def tasks @@tasks.clone end def save(tasks) file = File.open(TASK_FILENAME, "w") tasks.each do |i| file.puts i end end end class Commands < Thor @@tasks = if File.exists?(Remindice::TASK_FILENAME); File.readlines(Remindice::TASK_FILENAME) else [] end end end
Add after_build hook during after_commit hook
require 'middleman-core' require 'map' module Middleman module S3Sync class << self def registered(app, options_hash = {}, &block) options = Options.new yield options if block_given? @@options = options app.send :include, Helpers app.after_configuration do |config| options.build_dir ||= build_dir end app.after_build do |builder| ::Middleman::S3Sync.sync if options.after_build end end alias :included :registered def s3_sync_options @@options end module Helpers def s3_sync_options ::Middleman::S3Sync.s3_sync_options end def default_caching_policy(policy = {}) s3_sync_options.add_caching_policy(:default, policy) end def caching_policy(content_type, policy = {}) s3_sync_options.add_caching_policy(content_type, policy) end end end end end
require 'middleman-core' require 'map' module Middleman module S3Sync class << self def registered(app, options_hash = {}, &block) options = Options.new yield options if block_given? @@options = options app.send :include, Helpers app.after_configuration do |config| # Define the after_build step after during configuration so # that it's pushed to the end of the callback chain app.after_build do |builder| ::Middleman::S3Sync.sync if options.after_build end options.build_dir ||= build_dir end end alias :included :registered def s3_sync_options @@options end module Helpers def s3_sync_options ::Middleman::S3Sync.s3_sync_options end def default_caching_policy(policy = {}) s3_sync_options.add_caching_policy(:default, policy) end def caching_policy(content_type, policy = {}) s3_sync_options.add_caching_policy(content_type, policy) end end end end end
Add stubs required by the main application
# Configure Rails Envinronment ENV["RAILS_ENV"] = "test" require File.expand_path("../dummy/config/environment.rb", __FILE__) require 'rspec/rails' require 'factories' ENGINE_RAILS_ROOT=File.join(File.dirname(__FILE__), '../') # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[File.join(ENGINE_RAILS_ROOT, "spec/support/**/*.rb")].each {|f| require f } RSpec.configure do |config| config.include RSpec::Rails::ControllerExampleGroup, file_path: %r(spec/controllers) config.use_transactional_fixtures = true end
# Configure Rails Envinronment ENV["RAILS_ENV"] = "test" require File.expand_path("../dummy/config/environment.rb", __FILE__) require 'rspec/rails' require 'factories' ENGINE_RAILS_ROOT=File.join(File.dirname(__FILE__), '../') # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[File.join(ENGINE_RAILS_ROOT, "spec/support/**/*.rb")].each {|f| require f } RSpec.configure do |config| config.include RSpec::Rails::ControllerExampleGroup, file_path: %r(spec/controllers) config.use_transactional_fixtures = true # Stubs required from the main application config.before(:each) do double(::UserObserver) allow_any_instance_of(UserObserver).to receive(:after_create) allow_any_instance_of(UserObserver).to receive(:after_save) end end
Make requires rely on load path being setup correctly
require 'buildr' require File.expand_path(File.dirname(__FILE__) + '/buildr/ipojo/version') require File.expand_path(File.dirname(__FILE__) + '/buildr/ipojo/core') require File.expand_path(File.dirname(__FILE__) + '/buildr/ipojo/project_extension')
require 'buildr' require 'buildr/ipojo/version' require 'buildr/ipojo/config' require 'buildr/ipojo/core' require 'buildr/ipojo/project_extension'
Refactor method stubs a bit.
module MGit class Command @@commands = {} @@aliases = {} def self.execute(name, args) cmd = self.create(name) arity_min, arity_max = cmd.arity raise TooFewArgumentsError.new(cmd) if arity_min && args.size < arity_min raise TooManyArgumentsError.new(cmd) if arity_max && args.size > arity_max cmd.execute(args) end def self.register_command(cmd) @@commands[cmd] = self end def self.register_alias(cmd) @@aliases[cmd] = self end def self.list '[' + @@commands.keys.join(', ') + ']' end def self.instance_each @@commands.each do |_, klass| yield klass.new end end def arity raise ImplementationError.new("Command #{self.class.name} doesn't implement the arity method.") end def usage raise ImplementationError.new("Command #{self.class.name} doesn't implement the usage method.") end def help raise ImplementationError.new("Command #{self.class.name} doesn't implement the help method.") end def description raise ImplementationError.new("Command #{self.class.name} doesn't implement the description method.") end private def self.create(cmd) cmd = cmd.downcase.to_sym klass = @@commands[cmd] || @@aliases[cmd] if klass klass.new else raise UnknownCommandError.new(cmd) end end end end
module MGit class Command @@commands = {} @@aliases = {} def self.execute(name, args) cmd = self.create(name) arity_min, arity_max = cmd.arity raise TooFewArgumentsError.new(cmd) if arity_min && args.size < arity_min raise TooManyArgumentsError.new(cmd) if arity_max && args.size > arity_max cmd.execute(args) end def self.register_command(cmd) @@commands[cmd] = self end def self.register_alias(cmd) @@aliases[cmd] = self end def self.list '[' + @@commands.keys.join(', ') + ']' end def self.instance_each @@commands.each do |_, klass| yield klass.new end end [:arity, :usage, :help, :description].each do |meth| define_method(meth) do raise ImplementationError.new("Command #{self.class.name} doesn't implement the #{meth.to_s} method.") end end private def self.create(cmd) cmd = cmd.downcase.to_sym klass = @@commands[cmd] || @@aliases[cmd] if klass klass.new else raise UnknownCommandError.new(cmd) end end end end
Add retry on exception to mattermost login
# frozen_string_literal: true module QA context 'Manage', :orchestrated, :mattermost do describe 'Mattermost login' do it 'user logs into Mattermost using GitLab OAuth' do Runtime::Browser.visit(:gitlab, Page::Main::Login) Page::Main::Login.perform(&:sign_in_using_credentials) Runtime::Browser.visit(:mattermost, Page::Mattermost::Login) Page::Mattermost::Login.perform(&:sign_in_using_oauth) Page::Mattermost::Main.perform do |page| expect(page).to have_content(/(Welcome to: Mattermost|Logout GitLab Mattermost)/) end end end end end
# frozen_string_literal: true module QA context 'Manage', :orchestrated, :mattermost do describe 'Mattermost login' do it 'user logs into Mattermost using GitLab OAuth' do Runtime::Browser.visit(:gitlab, Page::Main::Login) Page::Main::Login.perform(&:sign_in_using_credentials) Support::Retrier.retry_on_exception do Runtime::Browser.visit(:mattermost, Page::Mattermost::Login) Page::Mattermost::Login.perform(&:sign_in_using_oauth) Page::Mattermost::Main.perform do |page| expect(page).to have_content(/(Welcome to: Mattermost|Logout GitLab Mattermost)/) end end end end end end
Change activerecord dependency to handle new flavors of rails 7
$LOAD_PATH.push File.expand_path('../lib', __FILE__) # Maintain your gem's version: require 'pg_ltree/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = 'pg_ltree' s.version = PgLtree::VERSION s.authors = ['Andrei Panamarenka'] s.email = ['andrei.panamarenka@gmail.com'] s.homepage = 'https://github.com/sjke/pg_ltree' s.summary = 'Organise ActiveRecord model into a tree structure with PostgreSQL LTree' s.description = 'Organise ActiveRecord model into a tree structure with PostgreSQL LTree' s.license = 'MIT' s.required_ruby_version = '>= 2.0.0' s.files = Dir['{app,config,db,lib}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.rdoc'] s.test_files = Dir['test/**/*'] s.add_dependency 'activerecord', '>= 5.2', '<= 7.0' s.add_dependency 'pg', '>= 0.17.0', '< 2' s.add_development_dependency 'bundler' s.add_development_dependency 'rake' s.add_development_dependency 'pry' s.add_development_dependency 'yard' s.add_development_dependency 'minitest' s.add_development_dependency 'appraisal' end
$LOAD_PATH.push File.expand_path('../lib', __FILE__) # Maintain your gem's version: require 'pg_ltree/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = 'pg_ltree' s.version = PgLtree::VERSION s.authors = ['Andrei Panamarenka'] s.email = ['andrei.panamarenka@gmail.com'] s.homepage = 'https://github.com/sjke/pg_ltree' s.summary = 'Organise ActiveRecord model into a tree structure with PostgreSQL LTree' s.description = 'Organise ActiveRecord model into a tree structure with PostgreSQL LTree' s.license = 'MIT' s.required_ruby_version = '>= 2.0.0' s.files = Dir['{app,config,db,lib}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.rdoc'] s.test_files = Dir['test/**/*'] s.add_dependency 'activerecord', '>= 5.2', '< 8.0' s.add_dependency 'pg', '>= 0.17.0', '< 2' s.add_development_dependency 'bundler' s.add_development_dependency 'rake' s.add_development_dependency 'pry' s.add_development_dependency 'yard' s.add_development_dependency 'minitest' s.add_development_dependency 'appraisal' end
Remove scope that shouldn't be there
module KnowledgeBase::Concerns::Models::Category extend ActiveSupport::Concern included do extend FriendlyId publishable on: :published_at friendly_id :title, use: :slugged belongs_to :category has_many :category_article_associations, -> { order 'position ASC' } has_many :articles, through: :category_article_associations accepts_nested_attributes_for :category_article_associations, allow_destroy: true scope :root, -> { where parent_id: nil } scope :published, -> { where published: true } def to_s title end end end
module KnowledgeBase::Concerns::Models::Category extend ActiveSupport::Concern included do extend FriendlyId publishable on: :published_at friendly_id :title, use: :slugged belongs_to :category has_many :category_article_associations, -> { order 'position ASC' } has_many :articles, through: :category_article_associations accepts_nested_attributes_for :category_article_associations, allow_destroy: true scope :root, -> { where parent_id: nil } def to_s title end end end
Prepare git repository by copying fixture files
unless ENV['ANCHOR_TASK'] require 'coveralls' Coveralls.wear! end $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'ttnt' require 'minitest/autorun' module TTNT class TestCase < Minitest::Test FIZZBUZZ_FIXTURE_DIR = File.expand_path('../fixtures/repositories/fizzbuzz', __FILE__).freeze def before_setup super prepare_git_repository end def after_teardown FileUtils.remove_entry_secure(@tmpdir) super end private def prepare_git_repository @tmpdir = Dir.mktmpdir('ttnt_repo') FileUtils.cp_r(FIZZBUZZ_FIXTURE_DIR, @tmpdir) @repodir = "#{@tmpdir}/fizzbuzz" Dir.chdir(@repodir) do FileUtils.rm('.git') File.rename('.gitted', '.git') if File.exist?(".gitted") end @repo = Rugged::Repository.new(@repodir) end end end
unless ENV['ANCHOR_TASK'] require 'coveralls' Coveralls.wear! end $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'ttnt' require 'rugged' require 'minitest/autorun' module TTNT class TestCase < Minitest::Test FIXTURE_DIR = File.expand_path('../fixtures', __FILE__).freeze def before_setup super prepare_git_repository end def after_teardown FileUtils.remove_entry_secure(@tmpdir) super end private def prepare_git_repository @tmpdir = Dir.mktmpdir('ttnt_repository') @repo = Rugged::Repository.init_at(@tmpdir) copy_fixture('Rakefile', "#{@tmpdir}/Rakefile") copy_fixture('fizzbuzz.rb', "#{@tmpdir}/lib/fizzbuzz.rb") copy_fixture('fizz_test.rb', "#{@tmpdir}/test/fizz_test.rb") copy_fixture('buzz_test.rb', "#{@tmpdir}/test/buzz_test.rb") end def copy_fixture(src, dest) unless File.directory?(File.dirname(dest)) FileUtils.mkdir_p(File.dirname(dest)) end FileUtils.cp("#{FIXTURE_DIR}/#{src}", dest) end end end
Check for a .git directory
require 'fileutils' pulled, skipped, failed = [], [], [] root = ARGF.argv[0] raise ArgumentError.new("Please pass a root directoy!") if root.nil? Dir.foreach(root) do |directory| if File.directory?(directory) puts "Pulling: #{directory}" FileUtils.cd(directory) `git pull` `git remote prune origin` FileUtils.cd(root) unless $?.success? failed << directory else pulled << directory end else skipped << directory end end puts "Pulled\t#{pulled.inspect}" puts "Skipped\t#{skipped.inspect}" puts "Failed\t#{failed.inspect}"
require 'fileutils' pulled, skipped, failed = [], [], [] root = ARGF.argv[0] raise ArgumentError.new("Please pass a root directoy!") if root.nil? Dir.foreach(root) do |directory| if File.directory?(directory) FileUtils.cd(directory) if File.directory?('.git') puts "Pulling: #{directory}" `git pull` `git remote prune origin` end FileUtils.cd(root) unless $?.success? failed << directory else pulled << directory end else skipped << directory end end puts "Pulled\t#{pulled.inspect}" puts "Skipped\t#{skipped.inspect}" puts "Failed\t#{failed.inspect}"
Use Hash[] instead of `to_h` for Ruby 2.0 support
require 'roo/excelx/extractor' module Roo class Excelx class Images < Excelx::Extractor # Returns: Hash { id1: extracted_file_name1 }, # Example: { "rId1"=>"roo_media_image1.png", # "rId2"=>"roo_media_image2.png", # "rId3"=>"roo_media_image3.png" } def list @images ||= extract_images_names end private def extract_images_names return {} unless doc_exists? doc.xpath('/Relationships/Relationship').map do |rel| [rel['Id'], "roo" + rel['Target'].gsub(/\.\.\/|\//, '_')] end.to_h end end end end
require 'roo/excelx/extractor' module Roo class Excelx class Images < Excelx::Extractor # Returns: Hash { id1: extracted_file_name1 }, # Example: { "rId1"=>"roo_media_image1.png", # "rId2"=>"roo_media_image2.png", # "rId3"=>"roo_media_image3.png" } def list @images ||= extract_images_names end private def extract_images_names return {} unless doc_exists? Hash[doc.xpath('/Relationships/Relationship').map do |rel| [rel['Id'], "roo" + rel['Target'].gsub(/\.\.\/|\//, '_')] end] end end end end
Fix typo in destinations_path in requests test
require 'rails_helper' RSpec.describe "Destinations", :type => :request do describe "GET /destinations" do it "works! (now write some real specs)" do get destinations_index_path expect(response).to have_http_status(200) end end end
require 'rails_helper' RSpec.describe "Destinations", :type => :request do describe "GET /destinations" do it "works! (now write some real specs)" do get destinations_path expect(response).to have_http_status(200) end end end
Allow Ettu to be configured
module Ettu class Railtie < Rails::Railtie initializer 'install' do require 'ettu' ActiveSupport.on_load :action_controller do ActionController::Base.send :include, FreshWhen end end end end
module Ettu class Railtie < Rails::Railtie config.ettu = ActiveSupport::OrderedOptions.new initializer 'load' do |app| unless app.config.ettu.disabled require 'ettu' ActiveSupport.on_load :action_controller do ActionController::Base.send :include, FreshWhen end if app.config.ettu.development_hack class BlackHole < Hash def []=(k, v); end end module ::ActionView class Digestor @@cache = BlackHole.new end end end end end end end
Add a GTK GUI with some general clean ups
class Freeplay::GUI ############################################################################## WINDOW_TITLE = 'Freeplay Game' ############################################################################## COLORS_NORMAL = { :black => Gdk::Color.parse("#000000"), :white => Gdk::Color.parse("#ffffff"), } ############################################################################## def initialize (board, &quit) @board = board @counts = {white: 1, black: 1} @grid = Array.new(@board.size) {Array.new(@board.size, nil)} @window = create_window(&quit) @window.show_all end ############################################################################## def update Gtk::main_iteration while Gtk::events_pending? end ############################################################################## def move (player, x, y) opponent = player == :black ? :white : :black x, y = @board.send(:transform, x, y) cell = @grid[x][y] cell[:label].text = @counts[player].to_s cell[:box].modify_bg(Gtk::STATE_NORMAL, COLORS_NORMAL[player]) cell[:label].modify_fg(Gtk::STATE_NORMAL, COLORS_NORMAL[opponent]) @counts[player] += 1 end ############################################################################## private ############################################################################## def create_window (&quit) window = Gtk::Window.new window.border_width = 10 window.set_size_request(400, -1) window.title = WINDOW_TITLE window.signal_connect("delete_event", &quit) window.signal_connect("destroy", &quit) window.add(create_table) window end ############################################################################## # Create a table that contains Gtk::EventBox objects, which contain # Gtk::Label objects. The labels will show the order in which moves # were made, and the event boxes will show the color of the stone in # that box. def create_table table = Gtk::Table.new(@board.size, @board.size, true) t_options = Gtk::EXPAND | Gtk::FILL @board.size.times do |x| @board.size.times do |y| @grid[x][y] = {:box => Gtk::EventBox.new, :label => Gtk::Label.new("")} @grid[x][y][:box].add(@grid[x][y][:label]) table.attach(@grid[x][y][:box], x, x+1, y, y+1, t_options, t_options, 0, 0) end end table end end
Disable jacoco as jenkins no longer uses it and the bytecode processing framework can not handle the size of some of our classes
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'buildr_plus/projects/_common' require 'buildr/jacoco' BuildrPlus::FeatureManager.activate_features([:spotbugs, :pmd, :checkstyle, :java, :testng, :ejb, :jaxrs])
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'buildr_plus/projects/_common' BuildrPlus::FeatureManager.activate_features([:spotbugs, :pmd, :checkstyle, :java, :testng, :ejb, :jaxrs])
Add UIKit as a required framework.
Pod::Spec.new do |s| s.name = "EPSUIFactory" s.version = "1.0.1" s.summary = "A class that provides factory methods for UIKit control set up in common ways." s.homepage = "https://github.com/ElectricPeelSoftware/EPSUIFactory" s.license = 'MIT' s.author = { "Peter Stuart" => "peter@electricpeelsoftware.com" } s.source = { :git => "https://github.com/ElectricPeelSoftware/EPSUIFactory.git", :tag => s.version.to_s } s.platform = :ios, '7.0' s.ios.deployment_target = '7.0' s.requires_arc = true s.source_files = 'Classes' s.public_header_files = 'Classes/*.h' end
Pod::Spec.new do |s| s.name = "EPSUIFactory" s.version = "1.0.2" s.summary = "A class that provides factory methods for UIKit control set up in common ways." s.homepage = "https://github.com/ElectricPeelSoftware/EPSUIFactory" s.license = 'MIT' s.author = { "Peter Stuart" => "peter@electricpeelsoftware.com" } s.source = { :git => "https://github.com/ElectricPeelSoftware/EPSUIFactory.git", :tag => s.version.to_s } s.platform = :ios, '7.0' s.ios.deployment_target = '7.0' s.requires_arc = true s.source_files = 'Classes' s.framework = 'UIKit' s.public_header_files = 'Classes/*.h' end
Fix same silly grammatical mistake elsewhere
require 'spec_helper' describe Ack do let(:external_uid) {'post:$l0ngAndFiNeUId4U'} describe "create_or_update_score" do it "creates an score if none exists" do score = Score.create(:external_uid => external_uid) Ack.create!(:score=>score, :identity => 123, :value => 1) ack = Ack.find_by_score_id(score.id) ack.should_not eq nil ack.value.should eq 1 ack.score.should_not eq nil end it "updates a score if such exists" do score = Score.create!(:external_uid => external_uid) Ack.create!(:score => score, :identity => 123, :value => 1) ack = Ack.find_by_score_id(score.id) ack.should_not eq nil ack.value.should eq 1 ack.score.should_not eq nil ack.score.should eq score end it "updates a score if an ack is destroyed" do score = Score.create(:external_uid => external_uid) ack = Ack.create!(:score => score, :identity => 123, :value => 1) ack.score.total_positive.should eq 1 ack.destroy score = Score.find_by_external_uid external_uid score.total_positive.should eq 0 end end end
require 'spec_helper' describe Ack do let(:external_uid) {'post:$l0ngAndFiNeUId4U'} describe "create_or_update_score" do it "creates a score if none exists" do score = Score.create(:external_uid => external_uid) Ack.create!(:score=>score, :identity => 123, :value => 1) ack = Ack.find_by_score_id(score.id) ack.should_not eq nil ack.value.should eq 1 ack.score.should_not eq nil end it "updates a score if such exists" do score = Score.create!(:external_uid => external_uid) Ack.create!(:score => score, :identity => 123, :value => 1) ack = Ack.find_by_score_id(score.id) ack.should_not eq nil ack.value.should eq 1 ack.score.should_not eq nil ack.score.should eq score end it "updates a score if an ack is destroyed" do score = Score.create(:external_uid => external_uid) ack = Ack.create!(:score => score, :identity => 123, :value => 1) ack.score.total_positive.should eq 1 ack.destroy score = Score.find_by_external_uid external_uid score.total_positive.should eq 0 end end end
Fix RbConfig warning in ruby-head
# Detect the platform we're running on so we can tweak behaviour # in various places. require 'rbconfig' module Cucumber unless defined?(Cucumber::VERSION) VERSION = '0.9.0' BINARY = File.expand_path(File.dirname(__FILE__) + '/../../bin/cucumber') LIBDIR = File.expand_path(File.dirname(__FILE__) + '/../../lib') JRUBY = defined?(JRUBY_VERSION) IRONRUBY = defined?(RUBY_ENGINE) && RUBY_ENGINE == "ironruby" WINDOWS = Config::CONFIG['host_os'] =~ /mswin|mingw/ OS_X = Config::CONFIG['host_os'] =~ /darwin/ WINDOWS_MRI = WINDOWS && !JRUBY && !IRONRUBY RAILS = defined?(Rails) RUBY_BINARY = File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name']) RUBY_1_9 = RUBY_VERSION =~ /^1\.9/ RUBY_1_8_7 = RUBY_VERSION =~ /^1\.8\.7/ class << self attr_accessor :use_full_backtrace def file_mode(m) #:nodoc: RUBY_1_9 ? "#{m}:UTF-8" : m end end self.use_full_backtrace = false end end
# Detect the platform we're running on so we can tweak behaviour # in various places. require 'rbconfig' module Cucumber unless defined?(Cucumber::VERSION) VERSION = '0.9.0' BINARY = File.expand_path(File.dirname(__FILE__) + '/../../bin/cucumber') LIBDIR = File.expand_path(File.dirname(__FILE__) + '/../../lib') JRUBY = defined?(JRUBY_VERSION) IRONRUBY = defined?(RUBY_ENGINE) && RUBY_ENGINE == "ironruby" WINDOWS = RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ OS_X = RbConfig::CONFIG['host_os'] =~ /darwin/ WINDOWS_MRI = WINDOWS && !JRUBY && !IRONRUBY RAILS = defined?(Rails) RUBY_BINARY = File.join(RbConfig::CONFIG['bindir'], RbConfig::CONFIG['ruby_install_name']) RUBY_1_9 = RUBY_VERSION =~ /^1\.9/ RUBY_1_8_7 = RUBY_VERSION =~ /^1\.8\.7/ class << self attr_accessor :use_full_backtrace def file_mode(m) #:nodoc: RUBY_1_9 ? "#{m}:UTF-8" : m end end self.use_full_backtrace = false end end
Set bind address and port for sinatra.
require 'sinatra' require 'json' require_relative 'geo' # NOTE: you must have redis running on localhost w/o a password. def businesses unless @businesses @businesses = Geo::Businesses.new(Geo::Businesses.redis_hash) data_string = File.read('spec/offers_poi.tsv') Geo::LoadBusinesses.load_businesses(@businesses, data_string) end @businesses end get '/version' do Geo::VERSION end get '/businesses.json' do latitude = Float(params[:latitude] || 33.1243208) longitude = Float(params[:longitude] || -117.32582479999996) distance_from_location = Geo::GeoLocation.new(latitude: latitude, longitude: longitude) json = businesses.to_hash(distance_from_location) content_type :json { location: [latitude, longitude], businesses: json }.to_json end
require 'sinatra' require 'json' require_relative 'geo' # NOTE: you must have redis running on localhost w/o a password. def businesses unless @businesses @businesses = Geo::Businesses.new(Geo::Businesses.redis_hash) data_string = File.read('spec/offers_poi.tsv') Geo::LoadBusinesses.load_businesses(@businesses, data_string) end @businesses end set :bind, '0.0.0.0' set :port, 8080 get '/version' do Geo::VERSION end get '/businesses.json' do latitude = Float(params[:latitude] || 33.1243208) longitude = Float(params[:longitude] || -117.32582479999996) distance_from_location = Geo::GeoLocation.new(latitude: latitude, longitude: longitude) json = businesses.to_hash(distance_from_location) content_type :json { location: [latitude, longitude], businesses: json }.to_json end
Move torrent trimming to the rest of the tasks' schedule, 1d can easily be missed by falling asleep.
require 'feed_fetcher' scheduler = Rufus::Scheduler.start_new scheduler.every "20m" do FeedFetcher.fetch_and_save_torrents_from_tpb FeedFetcher.fetch_and_save_torrents_from_demonoid Torrent.process_artists Artist.fetch_similar_artists SimilarArtist.link_with_known_artists end scheduler.every "1m" do ProfileJob.process_all end scheduler.every "1d" do Torrent.trim end
require 'feed_fetcher' scheduler = Rufus::Scheduler.start_new scheduler.every "20m" do FeedFetcher.fetch_and_save_torrents_from_tpb FeedFetcher.fetch_and_save_torrents_from_demonoid Torrent.process_artists Artist.fetch_similar_artists SimilarArtist.link_with_known_artists Torrent.trim end scheduler.every "1m" do ProfileJob.process_all end
Validate presence of name, email and uniqueness of email
class Member < ActiveRecord::Base has_many :events has_many :organizations has_one :user end
class Member < ActiveRecord::Base has_many :events has_many :organizations has_one :user validates :name, :email, presence: true validates :email, uniqueness: true end
Test for writing to file.
describe "get_position" do before :all do @robot = ToyRobot::Robot.new @robot.place(2, 3, 'EAST') end it "gets X,Y and F of robot" do expect(@robot.get_position).to eq "2,3,EAST" end # it "writes to stdout" do # # end # it "writes to file if specified" do # # end end
describe "Report" do before :all do @robot = ToyRobot::Robot.new @robot.place(2, 3, 'EAST') end it "gets X,Y and F of robot" do expect(@robot.get_position).to eq "2,3,EAST" end # it "writes to stdout" do # # end it "writes to file if specified" do @robot.output = File.open('test_out.txt', 'w') @robot.report @robot.output.close output = File.open('test_out.txt', 'r').read expect(output).to eq "Output: 2,3,EAST\n" system('rm test_out.txt') end end
Add coveralls to unit spec coverage
# encoding: utf-8 # SimpleCov MUST be started before require 'dm-mapper' # if ENV['COVERAGE'] require 'simplecov' SimpleCov.start do command_name 'spec:unit' add_filter "spec" add_filter "config" add_filter "lib/data_mapper/support" add_group "Finalizer", "lib/data_mapper/finalizer" add_group "Mapper", "lib/data_mapper/mapper" add_group "Relation", "lib/data_mapper/relation" add_group "Relationship", "lib/data_mapper/relationship" add_group "Attribute", "lib/data_mapper/attribute" end end require 'shared_helper' # requires dm-mapper
# encoding: utf-8 # SimpleCov MUST be started before require 'dm-mapper' # if ENV['COVERAGE'] == 'true' require 'simplecov' require 'coveralls' SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter ] SimpleCov.start do command_name 'spec:unit' add_filter 'config' add_filter 'lib/data_mapper/support' add_filter 'spec' add_group 'Finalizer', 'lib/data_mapper/finalizer' add_group 'Mapper', 'lib/data_mapper/mapper' add_group 'Relation', 'lib/data_mapper/relation' add_group 'Relationship', 'lib/data_mapper/relationship' add_group 'Attribute', 'lib/data_mapper/attribute' minimum_coverage 98.21 end end require 'shared_helper' # requires dm-mapper
Use google-api to obtain access_token
class ReferralsController < ApplicationController before_filter :authenticate, :only => [:edit] caches_action :index, :layout => false def index username = ElfWeb::Application.config.gdata_username password = ElfWeb::Application.config.gdata_password key = "1Gm8DnaUyDXaD7oQ_NodOBIawHZrRfPWjgEND6CsUJLk" session = GoogleDrive.login(username, password) ws = session.spreadsheet_by_key(key).worksheets[0] @referrals = [] for row in 2..ws.num_rows @referrals << { :service => ws[row,1], :company => ws[row,2], :contact => ws[row,3], :phone => ws[row,4], :referred_date => ws[row,5], :referred_by => ws[row,6] } end end def edit @editUrl = "https://docs.google.com/spreadsheets/d/1Gm8DnaUyDXaD7oQ_NodOBIawHZrRfPWjgEND6CsUJLk/edit?usp=sharing" expire_action :action => :index redirect_to @editUrl end end
class ReferralsController < ApplicationController before_filter :authenticate, :only => [:edit] caches_action :index, :layout => false def index key = "1Gm8DnaUyDXaD7oQ_NodOBIawHZrRfPWjgEND6CsUJLk" client = Google::APIClient.new auth = client.authorization auth.client_id = ENV["GOOGLE_API_CLIENT_ID"] auth.client_secret = ENV["GOOGLE_API_CLIENT_SECRET"] auth.scope = [ "https://www.googleapis.com/auth/drive", "https://spreadsheets.google.com/feeds/" ] auth.refresh_token = ENV["GOOGLE_API_REFRESH_TOKEN"] auth.fetch_access_token! session = GoogleDrive.login_with_oauth(auth.access_token) ws = session.spreadsheet_by_key(key).worksheets[0] @referrals = [] for row in 2..ws.num_rows @referrals << { :service => ws[row,1], :company => ws[row,2], :contact => ws[row,3], :phone => ws[row,4], :referred_date => ws[row,5], :referred_by => ws[row,6] } end end def edit @editUrl = "https://docs.google.com/spreadsheets/d/1Gm8DnaUyDXaD7oQ_NodOBIawHZrRfPWjgEND6CsUJLk/edit?usp=sharing" expire_action :action => :index redirect_to @editUrl end end
Set invalid flags for checking validation in test case
module WeatherReporter module UserInput RSpec.describe Validator do let(:validator_class) { WeatherReporter::UserInput::Validator } describe '#pair_flag_argument' do it 'gets pair of array with flag and argument' do flag_argument = validator_class.new(%w{-city kathmandu -day 10}).pair_flag_argument expect(flag_argument).to(eq([['-city', 'kathmandu'], ['-day', '10']])) end end describe '#validate_input' do it 'throws exception for invalid input' do validate_input = validator_class.new(%w{-city kathmandu -d 10}) expect do raise validate_input.validate_input end.to(raise_error.with_message('Please enter a valid flag')) end end end end end
module WeatherReporter module UserInput RSpec.describe Validator do let(:validator_class) { WeatherReporter::UserInput::Validator } describe '#pair_flag_argument' do it 'gets pair of array with flag and argument' do flag_argument = validator_class.new(%w{-city kathmandu -day 10}).pair_flag_argument expect(flag_argument).to(eq([['-city', 'kathmandu'], ['-day', '10']])) end end describe '#validate_input' do it 'throws exception for invalid input' do validate_input = validator_class.new(%w{-c kathmandu -d 10}) expect do raise validate_input.validate_input end.to(raise_error.with_message('Please enter a valid flag')) end end end end end
Add changelog metadata link to gemspec
# rubocop:disable Style/ExpandPathArguments lib = File.expand_path('../lib', __FILE__) # rubocop:enable Style/ExpandPathArguments $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'retryable/version' Gem::Specification.new do |spec| spec.name = 'retryable' spec.version = Retryable::Version spec.authors = ['Nikita Fedyashev', 'Carlo Zottmann', 'Chu Yeow'] spec.email = ['nfedyashev@gmail.com'] spec.summary = 'Retrying code blocks in Ruby' spec.description = spec.summary spec.homepage = 'http://github.com/nfedyashev/retryable' spec.licenses = ['MIT'] spec.require_paths = ['lib'] spec.files = Dir['{config,lib,spec}/**/*', '*.md', '*.gemspec', 'Gemfile', 'Rakefile'] spec.test_files = spec.files.grep(%r{^spec/}) spec.required_ruby_version = Gem::Requirement.new('>= 1.9.3') spec.required_rubygems_version = Gem::Requirement.new('>= 1.3.6') spec.add_development_dependency 'bundler', '~> 1.0' end
# rubocop:disable Style/ExpandPathArguments lib = File.expand_path('../lib', __FILE__) # rubocop:enable Style/ExpandPathArguments $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'retryable/version' Gem::Specification.new do |spec| spec.name = 'retryable' spec.version = Retryable::Version spec.authors = ['Nikita Fedyashev', 'Carlo Zottmann', 'Chu Yeow'] spec.email = ['nfedyashev@gmail.com'] spec.summary = 'Retrying code blocks in Ruby' spec.description = spec.summary spec.homepage = 'http://github.com/nfedyashev/retryable' spec.metadata = { 'changelog_uri' => 'https://github.com/nfedyashev/retryable/blob/master/CHANGELOG.md', 'source_code_uri' => 'https://github.com/nfedyashev/retryable/tree/master' } spec.licenses = ['MIT'] spec.require_paths = ['lib'] spec.files = Dir['{config,lib,spec}/**/*', '*.md', '*.gemspec', 'Gemfile', 'Rakefile'] spec.test_files = spec.files.grep(%r{^spec/}) spec.required_ruby_version = Gem::Requirement.new('>= 1.9.3') spec.required_rubygems_version = Gem::Requirement.new('>= 1.3.6') spec.add_development_dependency 'bundler', '~> 1.0' end
Change Virtus coercion type for input_data_types
module TwentyfourSevenOffice module Services class ApiOperation include Virtus.model attribute :client, Savon::Client, required: true attribute :name, Symbol, required: true attribute :input_data_types, Hash[Symbol => Class] attribute :session_id, TwentyfourSevenOffice::DataTypes::SessionId def call(input_hash) opts = {} add_inputs(opts, input_hash) add_session_cookie(opts) response = client.call(name, opts) result = response.body["#{name}_response".to_sym]["#{name}_result".to_sym] transform_result(result) rescue Savon::SOAPFault => e raise TwentyfourSevenOffice::Errors::APIError.wrap(e, session_id: session_id, input: input) end private def add_inputs(opts, input_hash) if input_hash opts[:message] = InputTransformer.transform_input(input_data_types, input_hash) end end def add_session_cookie(opts) if session_id opts[:cookies] = [session_id.to_cookie] end end def transform_result(result) ResultTransformer.transform_result(result) end end end end
module TwentyfourSevenOffice module Services class ApiOperation include Virtus.model attribute :client, Savon::Client, required: true attribute :name, Symbol, required: true attribute :input_data_types, Hash[Symbol => Object] attribute :session_id, TwentyfourSevenOffice::DataTypes::SessionId def call(input_hash) opts = {} add_inputs(opts, input_hash) add_session_cookie(opts) response = client.call(name, opts) result = response.body["#{name}_response".to_sym]["#{name}_result".to_sym] transform_result(result) rescue Savon::SOAPFault => e raise TwentyfourSevenOffice::Errors::APIError.wrap(e, session_id: session_id, input: input) end private def add_inputs(opts, input_hash) if input_hash opts[:message] = InputTransformer.transform_input(input_data_types, input_hash) end end def add_session_cookie(opts) if session_id opts[:cookies] = [session_id.to_cookie] end end def transform_result(result) ResultTransformer.transform_result(result) end end end end
Handle Timeout::Error exceptions which are caught by ActiveRecord.
module ActiveRecord module ConnectionAdapters class AbstractAdapter protected alias_method :old_log, :log def log(sql, name) if block_given? old_log(sql, name) do yield end else old_log(sql, name) end rescue ActiveRecord::StatementInvalid => ex if ex.message =~ /^OSM::APITimeoutError: / raise OSM::APITimeoutError.new else raise end end end end end
module ActiveRecord module ConnectionAdapters class AbstractAdapter protected alias_method :old_log, :log def log(sql, name) if block_given? old_log(sql, name) do yield end else old_log(sql, name) end rescue ActiveRecord::StatementInvalid => ex if ex.message =~ /^OSM::APITimeoutError: / raise OSM::APITimeoutError.new elsif ex.message =~ /^Timeout::Error: / raise Timeout::Error.new else raise end end end end end
Switch to modifying the protected attributes
Spree::Taxon.class_eval do attr_accessible :header has_attached_file :header, styles: { normal: '1000x' }, default_style: :normal, default_url: '/assets/default_taxon.png' end
Spree::PermittedAttributes.taxon_attributes << :header Spree::Taxon.class_eval do has_attached_file :header, styles: { normal: '1000x' }, default_style: :normal, default_url: '/assets/default_taxon.png' end
Fix retrieval of hostname fact based on network.
# Copyright 2016 Red Hat, Inc. # All Rights Reserved. # # 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. [ 'external', 'internalapi', 'storage', 'storagemgmt', 'tenant', 'management', ].each do |network| Facter.add('fqdn_' + network) do setcode do external_hostname_parts = [ Facter.value(:hostname), network, Facter.value(:domain), ].reject { |part| part.empty? } external_hostname_parts.join(".") end end end
# Copyright 2016 Red Hat, Inc. # All Rights Reserved. # # 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. [ 'external', 'internalapi', 'storage', 'storagemgmt', 'tenant', 'management', ].each do |network| Facter.add('fqdn_' + network) do setcode do external_hostname_parts = [ Facter.value(:hostname), network, Facter.value(:domain), ].reject { |part| part.nil? || part.empty? } external_hostname_parts.join(".") end end end
Remove comments after port definition
module VhdlDoctest class DUT def self.parse(path) entity, ports, cases = DoctestParser.new(path).parse new(entity, ports, cases) end attr_accessor :entity, :ports, :cases def initialize(entity, ports, cases) @entity, @ports, @cases = entity, ports, cases end def test_file TestFile.new(@entity, @ports, @cases) end class DoctestParser def initialize(path) @vhdl = File.read(path) end def parse entity = @vhdl.match(/entity\s+(.*)\s+is/)[1] ports = extract_ports cases = TestParser.new(@vhdl).parse(ports) [entity, ports, cases] end def extract_ports return @ports if @ports @ports = [] definitions = @vhdl.match(/entity.*is\s+port\s*\((.*?)\);\s*end/m)[1] definitions.split("\n").each do |l| names, attributes = l.strip.gsub(/;$/, '').split(":") next unless attributes destination, type = attributes.strip.split(' ', 2) names.split(',').each do |name| @ports << Port.new(name.strip, destination.to_sym, VhdlDoctest::Types.parse(type)) end end @ports end end end end
module VhdlDoctest class DUT def self.parse(path) entity, ports, cases = DoctestParser.new(path).parse new(entity, ports, cases) end attr_accessor :entity, :ports, :cases def initialize(entity, ports, cases) @entity, @ports, @cases = entity, ports, cases end def test_file TestFile.new(@entity, @ports, @cases) end class DoctestParser def initialize(path) @vhdl = File.read(path) end def parse entity = @vhdl.match(/entity\s+(.*)\s+is/)[1] ports = extract_ports cases = TestParser.new(@vhdl).parse(ports) [entity, ports, cases] end # this assumes one-line one-port def extract_ports return @ports if @ports @ports = [] definitions = @vhdl.match(/entity.*is\s+port\s*\((.*?)\);\s*end/m)[1] definitions.split("\n").each do |l| names, attributes = l.strip.gsub(/;.*$/, '').split(":") next unless attributes destination, type = attributes.strip.split(' ', 2) names.split(',').each do |name| @ports << Port.new(name.strip, destination.to_sym, VhdlDoctest::Types.parse(type)) end end @ports end end end end
Add email to devise sign up params
class ApplicationController < ActionController::Base include Exceptions before_action :set_locale after_filter :set_csrf_cookie rescue_from Exceptions::Forbidden, with: :rescue_from_forbidden def set_locale I18n.locale = params[:locale] || I18n.default_locale end def default_url_options(options={}) { locale: I18n.locale } end def after_sign_in_path_for(resource) campaigns_path end def get_translations(entry, scope) t(entry, scope: scope) end def input_types I18n.t("activerecord.options.input_types").map { |key, value| { label: value, input_type: key } } end def export_i18n_messages SimplesIdeias::I18n.export! if Rails.env.development? end def default_serializer_options { root: false } end protected def set_csrf_cookie if protect_against_forgery? cookies['XSRF-TOKEN'] = form_authenticity_token end end def restrict_access authenticate_or_request_with_http_token do |token, options| ApiKey.exists?(access_token: token) end end def rescue_from_forbidden render 'errors/403', layout: 'application', status: 403 end end
class ApplicationController < ActionController::Base include Exceptions before_action :set_locale before_action :configure_permitted_parameters, if: :devise_controller? after_filter :set_csrf_cookie rescue_from Exceptions::Forbidden, with: :rescue_from_forbidden def set_locale I18n.locale = params[:locale] || I18n.default_locale end def default_url_options(options={}) { locale: I18n.locale } end def after_sign_in_path_for(resource) campaigns_path end def get_translations(entry, scope) t(entry, scope: scope) end def input_types I18n.t("activerecord.options.input_types").map { |key, value| { label: value, input_type: key } } end def export_i18n_messages SimplesIdeias::I18n.export! if Rails.env.development? end def default_serializer_options { root: false } end protected def set_csrf_cookie if protect_against_forgery? cookies['XSRF-TOKEN'] = form_authenticity_token end end def restrict_access authenticate_or_request_with_http_token do |token, options| ApiKey.exists?(access_token: token) end end def rescue_from_forbidden render 'errors/403', layout: 'application', status: 403 end def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_up) << :email devise_parameter_sanitizer.for(:account_update) << :email end end
Remove comments form app controller
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception end
Make teaspoon configuration more reliable
ENV['RAILS_ENV'] = 'test' ENV["LIB_NAME"] = 'solidus_backend' require 'spree_backend' require 'teaspoon' require 'teaspoon-mocha' unless defined?(DummyApp) require 'spree/testing_support/dummy_app' DummyApp.setup( gem_root: File.expand_path('../../', __FILE__), lib_name: 'solidus_backend' ) end Teaspoon.configure do |config| config.mount_at = "/teaspoon" config.root = Spree::Backend::Engine.root config.asset_paths = ["spec/javascripts", "spec/javascripts/stylesheets"] config.fixture_paths = ["spec/javascripts/fixtures"] config.suite do |suite| suite.use_framework :mocha, "2.3.3" suite.matcher = "{spec/javascripts,app/assets}/**/*_spec.{js,js.coffee,coffee}" suite.helper = "spec_helper" suite.boot_partial = "/boot" suite.expand_assets = true end end
ENV['RAILS_ENV'] = 'test' # Similar to setup described in # https://github.com/jejacks0n/teaspoon/wiki/Micro-Applications if defined?(DummyApp) require 'teaspoon-mocha' Teaspoon.configure do |config| config.mount_at = "/teaspoon" config.root = Spree::Backend::Engine.root config.asset_paths = ["spec/javascripts", "spec/javascripts/stylesheets"] config.fixture_paths = ["spec/javascripts/fixtures"] config.suite do |suite| suite.use_framework :mocha, "2.3.3" suite.matcher = "{spec/javascripts,app/assets}/**/*_spec.{js,js.coffee,coffee}" suite.helper = "spec_helper" suite.boot_partial = "/boot" suite.expand_assets = true end end else require 'solidus_backend' require 'teaspoon' require 'spree/testing_support/dummy_app' DummyApp.setup( gem_root: File.expand_path('../../', __FILE__), lib_name: 'solidus_backend' ) end
Load events to queue for reprocessing
#!/usr/bin/env ruby # # Copyright 2012 Georgios Gousios <gousiosg@gmail.com> # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials # provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. require 'rubygems' require 'yaml' require 'amqp' require 'eventmachine' require 'github-analysis' require 'json' require 'mongo' GH = GithubAnalysis.new # Graceful exit Signal.trap('INT') { AMQP.stop { EM.stop } } Signal.trap('TERM') { AMQP.stop { EM.stop } } events = GH.events_col counter = 0 AMQP.start(:host => GH.settings['amqp']['host'], :port => GH.settings['amqp']['port'], :username => GH.settings['amqp']['username'], :password => GH.settings['amqp']['password']) do |connection| channel = AMQP::Channel.new(connection) exchange = channel.topic(GH.settings['amqp']['exchange'], :durable => true, :auto_delete => false) events.find('{"type": "PushEvent"}').each do |e| msg = e.to_json key = "evt.%s" % e['type'] exchange.publish msg, :persistent => true, :routing_key => key counter += 1 end AMQP.stop end puts "Loaded #{counter} events" # vim: set sta sts=2 shiftwidth=2 sw=2 et ai :
Fix email in variables of template resource; add in password.
# Cookbook Name:: right_api_client # Recipe:: configure_users # # Copyright 2013, Chris Fordham # # 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. # currently users share the same credentials for the use case of root using the same rightscale account node['right_api_client']['configure_users'].each { |user| user user do home "/home/#{user}" end directory "/home/#{user}/.rightscale" do recursive true end template "/home/#{user}/.rightscale/right_api_client.yml" do source "right_api_client.yml.erb" mode 0400 owner user variables({ :account_id => node['right_api_client']['rightscale']['account_id'], :email => user, :api_version => node['right_api_client']['rightscale']['api_version'], :api_url => node['right_api_client']['rightscale']['api_url'] }) end }
# Cookbook Name:: right_api_client # Recipe:: configure_users # # Copyright 2013, Chris Fordham # # 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. # currently users share the same credentials for the use case of root using the same rightscale account node['right_api_client']['configure_users'].each { |user| user user do home "/home/#{user}" end directory "/home/#{user}/.rightscale" do recursive true end template "/home/#{user}/.rightscale/right_api_client.yml" do source "right_api_client.yml.erb" mode 0400 owner user variables({ :account_id => node['right_api_client']['rightscale']['account_id'], :email => node['right_api_client']['rightscale']['user'], :password => node['right_api_client']['rightscale']['password'], :api_version => node['right_api_client']['rightscale']['api_version'], :api_url => node['right_api_client']['rightscale']['api_url'] }) end }
Add meta data about our gem
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'KaratSleuth/version' Gem::Specification.new do |spec| spec.name = "KaratSleuth" spec.version = KaratSleuth::VERSION spec.authors = ["Evan Purkhiser"] spec.email = ["evanpurkhiser@gmail.com"] spec.description = %q{TODO: Write a gem description} spec.summary = %q{TODO: Write a gem summary} spec.homepage = "" 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_development_dependency "bundler", "~> 1.3" 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 'KaratSleuth/version' Gem::Specification.new do |spec| spec.name = "KaratSleuth" spec.version = KaratSleuth::VERSION spec.authors = ["Evan Purkhiser", "Heather Michaud", "Timmothy Mott"] spec.email = ["evanpurkhiser@gmail.com", "hmm34@zips.uakron.edu", "mayaswrath@gmail.com"] spec.description = "A simplistic spam heuristics tool for our AI course - Fall 2013" spec.summary = "A gem that learns from a training set of email data and can then detect spam" spec.homepage = "https://github.com/EvanPurkhiser/CS-Karat-Sleuth" 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_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" end
Copy Podspec file to this repository for reference
Pod::Spec.new do |s| s.name = 'OBShapedButton' s.version = '1.0.2' s.license = 'MIT' s.summary = 'A UIButton subclass that works with non-rectangular button shapes.' s.homepage = 'https://github.com/ole/OBShapedButton' s.author = { 'Ole Begemann' => 'ole@oleb.net' } s.source = { :git => 'https://github.com/ole/OBShapedButton.git', :tag => '1.0.2' } s.description = 'Instances of OBShapedButton respond to touches only in areas where the image that is assigned to the button for UIControlStateNormal is non-transparent.' s.platform = :ios s.source_files = 'OBShapedButton/**/*.{h,m}', 'UIImage+ColorAtPixel/**/*.{h,m}' s.requires_arc = true end
Convert messy set of ifs to case.
require 'gir_ffi/builder_helper' module GirFFI module InfoExt module ITypeInfo include BuilderHelper def layout_specification_type ffitype = GirFFI::Builder.itypeinfo_to_ffitype self if ffitype.kind_of?(Class) and const_defined_for ffitype, :Struct ffitype = ffitype.const_get :Struct end if ffitype == :bool ffitype = :int end if ffitype == :array subtype = param_type(0).layout_specification_type ffitype = [subtype, array_fixed_size] end ffitype end end end end GObjectIntrospection::ITypeInfo.send :include, GirFFI::InfoExt::ITypeInfo
require 'gir_ffi/builder_helper' module GirFFI module InfoExt module ITypeInfo include BuilderHelper def layout_specification_type ffitype = GirFFI::Builder.itypeinfo_to_ffitype self case ffitype when Class ffitype.const_get :Struct when :bool :int when :array subtype = param_type(0).layout_specification_type [subtype, array_fixed_size] else ffitype end end end end end GObjectIntrospection::ITypeInfo.send :include, GirFFI::InfoExt::ITypeInfo
Add CLI noodlin create test
require_relative 'spec_helper' describe 'Noodle' do it "should echo hi in shell" do hostname = SecureRandom.uuid noodlin = "create -s mars -i host -p hr -P prod #{hostname}.example.com" assert_output(stdout="\n"){puts %x{bin/noodlin #{noodlin}}} end end
Add missing test for reflect_on_recommendable
require 'spec_helper' class User include Recommendable end class Movie; end describe Recommendable do it 'defines a list of recommendables' do expect(User._recommendables).to eq({}) end describe '.recommended' do it 'raises a NameError if the recommendable has no associated class' do expect { User.recommended(:books) }.to raise_error end it 'creates an Association for the recommended class' do User.recommended(:movies) expect(User._recommendables[:movies]).to be_instance_of(Recommendable::Association) end end after do User._recommendables.clear end end
require 'spec_helper' class User include Recommendable end class Movie; end describe Recommendable do it 'defines a list of recommendables' do expect(User._recommendables).to eq({}) end describe '.recommended' do before { User.recommended(:movies) } it 'raises a NameError if the recommendable has no associated class' do expect { User.recommended(:books) }.to raise_error end it 'creates an Association for the recommended class' do expect(User._recommendables[:movies]).to be_instance_of( Recommendable::Association ) end it 'allows accesing an association' do expect(User.reflect_on_recommendable(:movies)).to eq( User._recommendables[:movies] ) end end after do User._recommendables.clear end end
Set not validated attributes to nil
# Read about factories at http://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :user do provider "twitter" uid "1234" email "foo@bar.com" name "foo" avatar_url "" end end
# Read about factories at http://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :user do provider "twitter" uid "1234" email nil name "foo" avatar_url nil end end
Add sqlite3 recipe to install build dependencies
# This recipe is only used until the opscode sqlite cookbook gains capabilities # similar to the mysql and postgresql cookbooks, i.e. a client and ruby recipe. execute "apt-get update" do ignore_failure true action :nothing end.run_action(:run) if node['platform_family'] == "debian" node.set['build_essential']['compiletime'] = true include_recipe "build-essential" include_recipe "sqlite" header_package = value_for_platform_family( ["redhat", "suse", "fedora" ] => { "default" => "sqlite-devel" }, ["debian"] => { "default" => "libsqlite3-dev" }, 'default' => "libsqlite3-dev" ) package header_package do action :nothing end.run_action(:install) chef_gem "sqlite3"
Use a template file for title for flexibility
require 'erb' require_relative 'template_processor' module Compiler class LiquidProcessor < TemplateProcessor @@yield_hash = { after_header: "{% include layouts/_after_header.html %}", body_classes: "{% include layouts/_body_classes.html %}", body_end: "{% include layouts/_body.html %}", content: "{{ content }}", cookie_message: "{% include layouts/_cookie_message.html %}", footer_support_links: "{% include layouts/_footer_support_links.html %}", footer_top: "{% include layouts/_footer_top.html %}", head: "{% include layouts/_head.html %}", header_class: "{% if page.header_class %}{{ page.header_class }}{% endif %}", inside_header: "{% include layouts/_inside_header.html %}", page_title: "{% if page.title %}{{ page.title }}{% endif %}", proposition_header: "{% include layouts/_proposition_header.html %}" } def handle_yield(section = :layout) @@yield_hash[section] end def asset_path(file, options={}) return file if @is_stylesheet case File.extname(file) when '.css' "{{ site.govuk_template_assets }}/stylesheets/#{file}" when '.js' "{{ site.govuk_template_assets }}/javascripts/#{file}" else "{{ site.govuk_template_assets }}/images/#{file}" end end def content_for?(*args) @@yield_hash.include? args[0] end end end
require 'erb' require_relative 'template_processor' module Compiler class LiquidProcessor < TemplateProcessor @@yield_hash = { after_header: "{% include layouts/_after_header.html %}", body_classes: "{% include layouts/_body_classes.html %}", body_end: "{% include layouts/_body.html %}", content: "{{ content }}", cookie_message: "{% include layouts/_cookie_message.html %}", footer_support_links: "{% include layouts/_footer_support_links.html %}", footer_top: "{% include layouts/_footer_top.html %}", head: "{% include layouts/_head.html %}", header_class: "{% if page.header_class %}{{ page.header_class }}{% endif %}", inside_header: "{% include layouts/_inside_header.html %}", page_title: "{% include layouts/_page_title.html %}", proposition_header: "{% include layouts/_proposition_header.html %}" } def handle_yield(section = :layout) @@yield_hash[section] end def asset_path(file, options={}) return file if @is_stylesheet case File.extname(file) when '.css' "{{ site.govuk_template_assets }}/stylesheets/#{file}" when '.js' "{{ site.govuk_template_assets }}/javascripts/#{file}" else "{{ site.govuk_template_assets }}/images/#{file}" end end def content_for?(*args) @@yield_hash.include? args[0] end end end
Convert JSON data to required and available slots vs time
#!/usr/bin/env ruby require 'json' require 'csv' require 'optparse' options = {input: nil, output: "data.csv"} OptionParser.new do |opts| opts.banner = "Usage: example.rb [options]" opts.on("-i", "--input input", "Input file") do |input| options[:input] = input end opts.on("-o", "--output output", "Output file") do |output| options[:output] = output end end.parse! file = File.read(options[:input]) data = JSON.parse(file) CSV.open(options[:output], "w") do |csv| csv << %w(time required_slots available_slots) time = 0 data.each do |o, _| csv << [time, o["requiredSlots"], o["availableSlots"]] time += 10 end end
Add stock media query lookup
module PictureTag module Instructions # PictureTag configuration class Config < Instruction def source PictureTag::Parsers::Configuration.new end end # Tag parameters class Params < Instruction def source PictureTag::Parsers::TagParser.new PictureTag.raw_params end end # Currently selected preset class Preset < Instruction def source PictureTag::Parsers::Preset.new PictureTag.params.preset_name end end # Handles non-image arguments to liquid tag and preset. class HtmlAttributes < Instruction def source PictureTag::Parsers::HTMLAttributeSet.new PictureTag.params.leftovers end end # TODO: rename to MediaQueries # Returns user-defined media queries. class MediaPresets < Instruction def source PictureTag.site.data.dig('picture', 'media_queries') || {} end end end end
module PictureTag module Instructions # PictureTag configuration class Config < Instruction def source PictureTag::Parsers::Configuration.new end end # Tag parameters class Params < Instruction def source PictureTag::Parsers::TagParser.new PictureTag.raw_params end end # Currently selected preset class Preset < Instruction def source PictureTag::Parsers::Preset.new PictureTag.params.preset_name end end # Handles non-image arguments to liquid tag and preset. class HtmlAttributes < Instruction def source PictureTag::Parsers::HTMLAttributeSet.new PictureTag.params.leftovers end end # TODO: rename to MediaQueries # Returns user-defined media queries. class MediaPresets < Instruction def source STOCK_MEDIA_QUERIES.merge( PictureTag.site.data.dig('picture', 'media_queries') || {} ) end end end end
Refactor proxy method into delcarative rails proxy method
class Player < ActiveRecord::Base belongs_to :user belongs_to :game has_many :actions validates :user, presence: true validates :game, presence: true def nickname user.nickname end def pickups actions.pickup end def plays actions.play end def pickup!(card) actions.create!(effect: Action::PICKUP, card: card) end def play!(card) actions.create!(effect: Action::PLAY, card: card) end end
class Player < ActiveRecord::Base belongs_to :user belongs_to :game has_many :actions validates :user, presence: true validates :game, presence: true delegate :nickname, to: :user def pickups actions.pickup end def plays actions.play end def pickup!(card) actions.create!(effect: Action::PICKUP, card: card) end def play!(card) actions.create!(effect: Action::PLAY, card: card) end end
Add commander as a dependency.
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'addlicense/version' Gem::Specification.new do |spec| spec.name = "addlicense" spec.version = Addlicense::VERSION spec.authors = ["Zach Latta"] spec.email = ["zchlatta@gmail.com"] spec.description = %q{The easiest way to add licenses to your projects.} spec.summary = %q{addlicense is the easiest way to add licenses to your projects.} spec.homepage = "" 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_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" spec.add_development_dependency "rspec", "~> 2.14.1" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'addlicense/version' Gem::Specification.new do |spec| spec.name = "addlicense" spec.version = Addlicense::VERSION spec.authors = ["Zach Latta"] spec.email = ["zchlatta@gmail.com"] spec.description = %q{The easiest way to add licenses to your projects.} spec.summary = %q{addlicense is the easiest way to add licenses to your projects.} spec.homepage = "" 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_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" spec.add_development_dependency "rspec", "~> 2.14.1" spec.add_dependency "commander", "~> 4.1.4" end
Add benchmarks for :full_matrix strategy
require "benchmark" require "string_metric" require "text" Benchmark.bmbm(7) do |x| x.report("Recursive implementation") do (1..100).each do |i| StringMetric::Levenshtein.distance("kitten", "sitting") end end x.report("Text::Levenshtein implementation") do (1..100).each do |i| Text::Levenshtein.distance("kitten", "sitting") end end end
require "benchmark" require "string_metric" require "text" Benchmark.bmbm(7) do |x| x.report("Recursive implementation") do (1..100).each do |i| StringMetric::Levenshtein.distance("kitten", "sitting", strategy: :recursive) end end x.report("Full Matrix implementation") do (1..100).each do |i| StringMetric::Levenshtein.distance("kitten", "sitting", strategy: :full_matrix) end end x.report("Text::Levenshtein implementation") do (1..100).each do |i| Text::Levenshtein.distance("kitten", "sitting") end end end
Convert admin controller tests to request type
# frozen_string_literal: true require 'rails_helper' describe AdminController do let(:admin) { create(:admin) } let(:user) { create(:user) } describe '#index' do it 'renders for admins' do allow(controller).to receive(:current_user).and_return(admin) get :index expect(response.status).to eq(200) end it 'redirects for non-admins' do allow(controller).to receive(:current_user).and_return(user) get :index expect(response).to redirect_to(root_path) end end end
# frozen_string_literal: true require 'rails_helper' describe AdminController, type: :request do let(:admin) { create(:admin) } let(:user) { create(:user) } describe '#index' do it 'renders for admins' do allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) get '/admin' expect(response.status).to eq(200) end it 'redirects for non-admins' do allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user) get '/admin' expect(response).to redirect_to(root_path) end end end
Revert "(PDB-4232) Pin apt module to 6.2.1 when installing puppetDB"
matching_puppetdb_platform = puppetdb_supported_platforms.select { |r| r =~ master.platform } skip_test unless matching_puppetdb_platform.length > 0 test_name 'PuppetDB setup' sitepp = '/etc/puppetlabs/code/environments/production/manifests/site.pp' teardown do on(master, "rm -f #{sitepp}") end step 'Install Puppet Release Repo' do install_puppetlabs_release_repo_on(master, 'puppet5') end step 'Install latest working version of apt module' do # Version 6.3.0 of the apt module broke the puppetdb module. # Until that is fix, pin the apt module to the previous version. # See PDB-4232. on(master, puppet('module install puppetlabs-apt --version 6.2.1')) end step 'Install PuppetDB module' do on(master, puppet('module install puppetlabs-puppetdb')) end if master.platform.variant == 'debian' master.install_package('apt-transport-https') end step 'Configure PuppetDB via site.pp' do create_remote_file(master, sitepp, <<SITEPP) node default { class { 'puppetdb': manage_firewall => false, } class { 'puppetdb::master::config': manage_report_processor => true, enable_reports => true, } } SITEPP on(master, "chmod 644 #{sitepp}") with_puppet_running_on(master, {}) do on(master, puppet_agent("--test --server #{master}"), :acceptable_exit_codes => [0,2]) end end
matching_puppetdb_platform = puppetdb_supported_platforms.select { |r| r =~ master.platform } skip_test unless matching_puppetdb_platform.length > 0 test_name 'PuppetDB setup' sitepp = '/etc/puppetlabs/code/environments/production/manifests/site.pp' teardown do on(master, "rm -f #{sitepp}") end step 'Install Puppet Release Repo' do install_puppetlabs_release_repo_on(master, 'puppet5') end step 'Install PuppetDB module' do on(master, puppet('module install puppetlabs-puppetdb')) end if master.platform.variant == 'debian' master.install_package('apt-transport-https') end step 'Configure PuppetDB via site.pp' do create_remote_file(master, sitepp, <<SITEPP) node default { class { 'puppetdb': manage_firewall => false, } class { 'puppetdb::master::config': manage_report_processor => true, enable_reports => true, } } SITEPP on(master, "chmod 644 #{sitepp}") with_puppet_running_on(master, {}) do on(master, puppet_agent("--test --server #{master}"), :acceptable_exit_codes => [0,2]) end end
Update stack spec to not use cedar-14
require_relative "../spec_helper" describe "Stack Changes" do xit "should reinstall gems on stack change" do app = Hatchet::Runner.new('default_ruby', stack: "heroku-16").setup! app.deploy do |app, heroku| app.update_stack("cedar-14") run!('git commit --allow-empty -m "cedar-14 migrate"') app.push! puts app.output expect(app.output).to match("Installing rack 1.5.0") expect(app.output).to match("Changing stack") end end it "should not reinstall gems if the stack did not change" do app = Hatchet::Runner.new('default_ruby', stack: "cedar-14").setup! app.deploy do |app, heroku| app.update_stack("cedar-14") run!(%Q{git commit --allow-empty -m "cedar migrate"}) app.push! puts app.output expect(app.output).to match("Using rack 1.5.0") end end end
require_relative "../spec_helper" describe "Stack Changes" do xit "should reinstall gems on stack change" do app = Hatchet::Runner.new('default_ruby', stack: "heroku-18").setup! app.deploy do |app, heroku| app.update_stack("heroku-16") run!('git commit --allow-empty -m "heroku-16 migrate"') app.push! puts app.output expect(app.output).to match("Installing rack 1.5.0") expect(app.output).to match("Changing stack") end end it "should not reinstall gems if the stack did not change" do app = Hatchet::Runner.new('default_ruby', stack: "heroku-16").setup! app.deploy do |app, heroku| app.update_stack("heroku-16") run!(%Q{git commit --allow-empty -m "cedar migrate"}) app.push! puts app.output expect(app.output).to match("Using rack 1.5.0") end end end
Hide styleguide route in production
class StyleguideGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) def create_controller copy_file 'styleguide_controller.rb', 'app/controllers/styleguide_controller.rb' copy_file 'styleguide.html.erb', 'app/views/layouts/styleguide.html.erb' empty_directory 'app/views/styleguide' copy_file 'index.html.erb', 'app/views/styleguide/index.html.erb' copy_file 'show.html.erb', 'app/views/styleguide/show.html.erb' end def supply_basic_guide copy_file '_elements.html.erb', 'app/views/styleguide/_elements.html.erb' end def create_routes route "match 'styleguide' => 'styleguide#index'" route "match 'styleguide/:name' => 'styleguide#show'" end end
class StyleguideGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) def create_controller copy_file 'styleguide_controller.rb', 'app/controllers/styleguide_controller.rb' copy_file 'styleguide.html.erb', 'app/views/layouts/styleguide.html.erb' empty_directory 'app/views/styleguide' copy_file 'index.html.erb', 'app/views/styleguide/index.html.erb' copy_file 'show.html.erb', 'app/views/styleguide/show.html.erb' end def supply_basic_guide copy_file '_elements.html.erb', 'app/views/styleguide/_elements.html.erb' end def create_routes route "match 'styleguide' => 'styleguide#index' if Rails.env.development?" route "match 'styleguide/:name' => 'styleguide#show' if Rails.env.development?" end end
Fix podspec for version 1.0
Pod::Spec.new do |s| s.name = 'TTOpenInAppActivity' s.version = '1.0' s.license = 'MIT' s.summary = 'TTOpenInAppActivity is a UIActivity subclass that provides an "Open In ..." action to a UIActivityViewController.' s.description = <<-DESC TTOpenInAppActivity is a UIActivity subclass that provides an "Open In ..." action to a UIActivityViewController. TTOpenInAppActivity uses an UIDocumentInteractionController to present all Apps than can handle the document specified by the activity item. Supported item types are NSURL instances that point to local files and UIImage instances. DESC s.homepage = 'https://github.com/honkmaster/TTOpenInAppActivity' s.authors = { 'Tobias Tiemerding' => 'http://www.tiemerding.com' } s.source = { :git => 'https://github.com/tomco/TTOpenInAppActivity.git', :commit => '65b8fb0cbafe92073a883f8706b0d725fcd58d01' } s.source_files = 'TTOpenInAppActivity/*.{h,m}' s.resources = 'TTOpenInAppActivity/*.png' s.frameworks = 'UIKit', 'MobileCoreServices' s.requires_arc = true s.platform = :ios, '6.0' end
Pod::Spec.new do |s| s.name = 'TTOpenInAppActivity' s.version = '1.0' s.license = { :type => 'MIT', :file => 'README.md' } s.summary = 'TTOpenInAppActivity is a UIActivity subclass that provides an "Open In ..." action to a UIActivityViewController.' s.description = <<-DESC TTOpenInAppActivity is a UIActivity subclass that provides an "Open In ..." action to a UIActivityViewController. TTOpenInAppActivity uses an UIDocumentInteractionController to present all Apps than can handle the document specified by the activity item. Supported item types are NSURL instances that point to local files and UIImage instances. DESC s.homepage = 'https://github.com/honkmaster/TTOpenInAppActivity' s.authors = { 'Tobias Tiemerding' => 'http://www.tiemerding.com' } s.source = { :git => 'https://github.com/honkmaster/TTOpenInAppActivity.git', :tag => '1.0' } s.source_files = 'TTOpenInAppActivity/*.{h,m}' s.resources = 'TTOpenInAppActivity/*.png' s.frameworks = 'UIKit', 'MobileCoreServices' s.requires_arc = true s.platform = :ios, '6.0' end
Fix the projects directory to be ~/Projects
# This file will be loaded by config/basic early in a Boxen run. Use # it to provide any custom code or behavior your Boxen setup requires. # Change the prefix boxen is installed to. # ENV['BOXEN_HOME'] = '/opt/boxen' # Change the repo boxen will use. ENV['BOXEN_REPO_NAME'] = 'roomorama/roomorama-boxen' # Boxen binary packaging # ENV["BOXEN_S3_ACCESS_KEY"] = '' # ENV["BOXEN_S3_SECRET_KEY"] = '' # ENV["BOXEN_S3_BUCKET"] = '' # Auto-report issues on failed runs # ENV["BOXEN_ISSUES_ENABLED"] = 'yes' # Submit audit data to an arbitrary HTTP endpoint # ENV["BOXEN_WEB_HOOK_URL"] = 'https://some-uri.com/boxen'
# This file will be loaded by config/basic early in a Boxen run. Use # it to provide any custom code or behavior your Boxen setup requires. # Change the prefix boxen is installed to. # ENV['BOXEN_HOME'] = '/opt/boxen' # Change the repo boxen will use. ENV['BOXEN_REPO_NAME'] = 'roomorama/roomorama-boxen' # Change the location of the projects ENV['BOXEN_SRC_DIR'] = "/Users/#{user}/Projects" # Boxen binary packaging # ENV["BOXEN_S3_ACCESS_KEY"] = '' # ENV["BOXEN_S3_SECRET_KEY"] = '' # ENV["BOXEN_S3_BUCKET"] = '' # Auto-report issues on failed runs # ENV["BOXEN_ISSUES_ENABLED"] = 'yes' # Submit audit data to an arbitrary HTTP endpoint # ENV["BOXEN_WEB_HOOK_URL"] = 'https://some-uri.com/boxen'
Add code to capture token required error
class LtiLaunchesController < ApplicationController include Concerns::CanvasSupport include Concerns::LtiSupport layout "client" skip_before_action :verify_authenticity_token before_action :do_lti def index @canvas_api = canvas_api @canvas_auth_required = @canvas_api.blank? set_lti_launch_values @lti_launch = ClientSetting.find(params[:id]) if params[:id].present? end end
class LtiLaunchesController < ApplicationController include Concerns::CanvasSupport include Concerns::LtiSupport layout "client" skip_before_action :verify_authenticity_token before_action :do_lti def index begin @canvas_api = canvas_api @canvas_auth_required = @canvas_api.blank? rescue CanvasApiTokenRequired @canvas_auth_required = true end set_lti_launch_values @lti_launch = ClientSetting.find(params[:id]) if params[:id].present? end end
Add imagemagick as a requirement in the gemspec
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'icon_generator/version' Gem::Specification.new do |spec| spec.name = "icon_generator" spec.version = IconGenerator::VERSION spec.authors = ["Adam Bowen"] spec.email = ["adambowen@group360.com"] spec.description = %q{Generates Apple Touch Icons or a favicon given a square image.} spec.summary = %q{Make apple-touch-icons and favicon.ico files} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.executables = ["icon_generator"] spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" spec.add_development_dependency "thor", "0.18.1" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'icon_generator/version' Gem::Specification.new do |spec| spec.name = "icon_generator" spec.version = IconGenerator::VERSION spec.authors = ["Adam Bowen"] spec.email = ["adambowen@group360.com"] spec.description = %q{Generates Apple Touch Icons or a favicon given a square image.} spec.summary = %q{Make apple-touch-icons and favicon.ico files} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.executables = ["icon_generator"] spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" spec.add_development_dependency "thor", "0.18.1" spec.requirements << 'imagemagick' end
Add more methods to Client::Cases
module OmnideskApi class Client module Cases def cases(options = {}) get 'cases.json', options end def case(case_id, options = {}) get "cases/#{case_id}.json", options end def messages(case_id, options = {}) get "cases/#{case_id}/messages.json", options end def cases_count(options = {}) options[:limit] = 1 cases(options)['total_count'] end def messages_count(case_id, options = {}) options[:limit] = 1 messages(case_id, options)['total_count'] end end end end
module OmnideskApi class Client module Cases def cases(options = {}) get 'cases.json', options end def case(case_id, options = {}) get "cases/#{case_id}.json", options end def create_case(options = {}) post 'cases.json', options end def update_case(case_id, options = {}) put "cases/#{case_id}.json", options end def trash_case(case_id, options = {}) put "cases/#{case_id}/trash.json", options end def spam_case(case_id, options = {}) put "cases/#{case_id}/spam.json", options end def restore_case(case_id, options = {}) put "cases/#{case_id}/restore.json", options end def delete_case(case_id, options = {}) delete "cases/#{case_id}.json", options end def messages(case_id, options = {}) get "cases/#{case_id}/messages.json", options end def create_message(case_id, options = {}) post "cases/#{case_id}/messages.json", options end def cases_count(options = {}) options[:limit] = 1 cases(options)['total_count'] end def messages_count(case_id, options = {}) options[:limit] = 1 messages(case_id, options)['total_count'] end end end end
Fix critical double quote bug
# $:.unshift File.dirname(__FILE__) $:.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $:.unshift(File.join(File.dirname(__FILE__), '..')) ENV["RACK_ENV"] ||= "development" require 'rubygems' require 'bundler' Bundler.setup Bundler.require(:default, ENV["RACK_ENV"].to_sym) require 'anygood' require 'app'
$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $:.unshift(File.join(File.dirname(__FILE__), '..')) ENV['RACK_ENV'] ||= 'development' require 'rubygems' require 'bundler' Bundler.setup Bundler.require(:default, ENV['RACK_ENV'].to_sym) require 'anygood' require 'app'
Refactor optimal_move to take in board and rules as parameters
class CompPlayer def minimax(board, rules, increment = 10) return 1000 if rules.won?(board, "X") return -1000 if rules.won?(board, "O") return 0 if rules.draw?(board, board.turn) board.valid_slots.map{ |index| minimax(board.move(index), rules, increment + 10) }.send(board.whose_turn(:max, :min)) + board.whose_turn(-increment, increment) end def optimal_move valid_slots.send(whose_turn(:max_by, :min_by)){|index| move(index).minimax} end end
class CompPlayer def minimax(board, rules, increment = 10) return 1000 if rules.won?(board, "X") return -1000 if rules.won?(board, "O") return 0 if rules.draw?(board, board.turn) board.valid_slots.map{ |index| minimax(board.move(index), rules, increment + 10) }.send(board.whose_turn(:max, :min)) + board.whose_turn(-increment, increment) end def optimal_move(board, rules) board.valid_slots.send(board.whose_turn(:max_by, :min_by)){|index| minimax(board.move(index), rules)} end end