Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Check for nil/blank headers in the file
require "rails_admin_import/config/legacy_model" module RailsAdminImport module Config class << self attr_accessor :logging attr_accessor :line_item_limit attr_accessor :rollback_on_error attr_accessor :header_converter attr_accessor :csv_options # Default is to downcase headers and add underscores to convert into attribute names HEADER_CONVERTER = lambda do |header| header.parameterize.underscore end def model(model_name, &block) unless @deprecation_shown warn "RailsAdminImport::Config#model is deprecated. " \ "Add a import section for your model inside the rails_admin " \ "config block. See the Readme.md for more details" @deprecation_shown = true end legacy_config = RailsAdminImport::Config::LegacyModel.new(model_name) legacy_config.instance_eval(&block) if block legacy_config end # Reset all configurations to defaults. def reset @logging = false @line_item_limit = 1000 @rollback_on_error = false @header_converter = HEADER_CONVERTER @csv_options = {} end end # Set default values for configuration options on load self.reset end end
require "rails_admin_import/config/legacy_model" module RailsAdminImport module Config class << self attr_accessor :logging attr_accessor :line_item_limit attr_accessor :rollback_on_error attr_accessor :header_converter attr_accessor :csv_options # Default is to downcase headers and add underscores to convert into attribute names HEADER_CONVERTER = lambda do |header| # check for nil/blank headers next if header.blank? header.parameterize.underscore end def model(model_name, &block) unless @deprecation_shown warn "RailsAdminImport::Config#model is deprecated. " \ "Add a import section for your model inside the rails_admin " \ "config block. See the Readme.md for more details" @deprecation_shown = true end legacy_config = RailsAdminImport::Config::LegacyModel.new(model_name) legacy_config.instance_eval(&block) if block legacy_config end # Reset all configurations to defaults. def reset @logging = false @line_item_limit = 1000 @rollback_on_error = false @header_converter = HEADER_CONVERTER @csv_options = {} end end # Set default values for configuration options on load self.reset end end
Update monkey patch to work with AASM 2.0.5
module AASMWithFixes def self.included(base) base.send(:include, AASM) base.module_eval do class << self def inherited(child) AASM::StateMachine[child] = AASM::StateMachine[self].clone AASM::StateMachine[child].events = AASM::StateMachine[self].events.clone super end end end end end
module AASM class StateMachine def clone klone = super klone.states = states.clone klone.events = events.clone klone end end end module AASMWithFixes def self.included(base) base.send(:include, AASM) end end
Use override and update to match default version
require 'spec_helper' describe 'idea::default' do context 'using version 2016.2.3 and setup_dir /opt' do let(:chef_run) do ChefSpec::SoloRunner.new(platform: 'centos', version: 6.6) do |node| node.default['idea']['version'] = '2016.2.3' node.default['idea']['setup_dir'] = '/opt' end.converge(described_recipe) end it 'creates /usr/share/applications/idea.desktop template' do expect(chef_run).to create_template('/usr/share/applications/idea.desktop') end it 'installs package idea from archive' do expect(chef_run).to install_ark('idea') end it 'creates /opt/idea-2016.2.3/bin/idea64.vmoptions' do expect(chef_run).to create_template('/opt/idea-2016.2.3/bin/idea64.vmoptions') end end end
require 'spec_helper' describe 'idea::default' do context 'using version 2016.2.4 and setup_dir /opt' do let(:chef_run) do ChefSpec::SoloRunner.new(platform: 'centos', version: 6.6) do |node| node.override['idea']['version'] = '2016.2.4' node.default['idea']['setup_dir'] = '/opt' end.converge(described_recipe) end it 'creates /usr/share/applications/idea.desktop template' do expect(chef_run).to create_template('/usr/share/applications/idea.desktop') end it 'installs package idea from archive' do expect(chef_run).to install_ark('idea') end it 'creates /opt/idea-2016.2.4/bin/idea64.vmoptions' do expect(chef_run).to create_template('/opt/idea-2016.2.4/bin/idea64.vmoptions') end end end
Add ok method to return 200.
module Omega class Controller attr_accessor :request, :response, :params, :env class << self %w[GET HEAD POST PUT PATCH DELETE].each do |http_method| define_method(http_method.downcase) do |named_routes, &block| named_routes.each do |name, route| Omega::Router.add_route(self, http_method, name, route, block) end end end end def halt(status, body = nil, headers = nil) Omega::Application.instance.halt(status, body, headers) end end end
module Omega class Controller attr_accessor :request, :response, :params, :env class << self %w[GET HEAD POST PUT PATCH DELETE].each do |http_method| define_method(http_method.downcase) do |named_routes, &block| named_routes.each do |name, route| Omega::Router.add_route(self, http_method, name, route, block) end end end end def halt(status, body = nil, headers = nil) Omega::Application.instance.halt(status, body, headers) end def ok halt 200 end end end
Update to use API Response module
module RDStation class Events include HTTParty include ::RDStation::RetryableRequest EVENTS_ENDPOINT = 'https://api.rd.services/platform/events'.freeze def initialize(authorization:) @authorization = authorization end def create(payload) retryable_request(@authorization) do |authorization| response = self.class.post(EVENTS_ENDPOINT, headers: authorization.headers, body: payload.to_json) response_body = JSON.parse(response.body) return response_body unless errors?(response_body) RDStation::ErrorHandler.new(response).raise_error end end private def errors?(response_body) response_body.is_a?(Array) || response_body['errors'] end end end
module RDStation class Events include HTTParty include ::RDStation::RetryableRequest EVENTS_ENDPOINT = 'https://api.rd.services/platform/events'.freeze def initialize(authorization:) @authorization = authorization end def create(payload) retryable_request(@authorization) do |authorization| response = self.class.post(EVENTS_ENDPOINT, headers: authorization.headers, body: payload.to_json) ApiResponse.build(response) end end end end
Raise error on failure of jasmine specs
namespace :jasmine do desc 'Run node jasmine' task :run => :environment do puts 'Running Jasmine Specs...' system('npx jasmine-browser-runner runSpecs') end end if %w(development test).include? Rails.env task(:default).prerequisites.unshift('jasmine:run') if Gem.loaded_specs.key?('jasmine') end
namespace :jasmine do desc 'Run node jasmine' task :run => :environment do puts 'Running Jasmine Specs...' system('npx jasmine-browser-runner runSpecs') or abort end end if %w(development test).include? Rails.env task(:default).prerequisites.unshift('jasmine:run') if Gem.loaded_specs.key?('jasmine') end
Make local authority importer continue if a row errors.
require 'csv' class LocalAuthorityDataImporter def self.update_all LocalServiceImporter.update LocalInteractionImporter.update LocalContactImporter.update end def self.update fh = fetch_data begin new(fh).run ensure fh.close end end def self.fetch_http_to_file(url) fh = Tempfile.new(['local_authority_data', 'csv']) fh.set_encoding('ascii-8bit') uri = URI.parse(url) fh.write Net::HTTP.get(uri) fh.rewind fh.set_encoding('windows-1252', 'UTF-8') fh end def initialize(fh) @filehandle = fh end def run CSV.new(@filehandle, headers: true).each do |row| process_row(row) end end end
require 'csv' class LocalAuthorityDataImporter def self.update_all LocalServiceImporter.update LocalInteractionImporter.update LocalContactImporter.update end def self.update fh = fetch_data begin new(fh).run ensure fh.close end end def self.fetch_http_to_file(url) fh = Tempfile.new(['local_authority_data', 'csv']) fh.set_encoding('ascii-8bit') uri = URI.parse(url) fh.write Net::HTTP.get(uri) fh.rewind fh.set_encoding('windows-1252', 'UTF-8') fh end def initialize(fh) @filehandle = fh end def run CSV.new(@filehandle, headers: true).each do |row| begin process_row(row) rescue => e Rails.logger.error "Error #{e.class} processing row in #{self.class}\n#{e.backtrace.join("\n")}" end end end end
Move SITE_URL into the Deathstar namespace.
require 'omniauth-oauth2' SITE_URL = "https://do.com" module OmniAuth module Strategies class Deathstar < OmniAuth::Strategies::OAuth2 option :name, "deathstar" option :client_options, { :site => SITE_URL, :authorize_url => SITE_URL = '/oauth2/authorize', :token_url => SITE_URL = '/oauth2/token' } uid {raw_info['id']} info do { name: raw_info['name'], first_name: raw_info['first_name'], last_name: raw_info['last_name'], email: raw_info['email'], image: raw_info['avatar']['48'] } end extra do {:raw_info => raw_info} end def raw_info @raw_info ||= access_token.get('/account.json').parsed || {} end end end end
require 'omniauth-oauth2' module OmniAuth module Strategies class Deathstar < OmniAuth::Strategies::OAuth2 SITE_URL = "https://do.com" option :name, "deathstar" option :client_options, { :site => SITE_URL, :authorize_url => SITE_URL = '/oauth2/authorize', :token_url => SITE_URL = '/oauth2/token' } uid {raw_info['id']} info do { name: raw_info['name'], first_name: raw_info['first_name'], last_name: raw_info['last_name'], email: raw_info['email'], image: raw_info['avatar']['48'] } end extra do {:raw_info => raw_info} end def raw_info @raw_info ||= access_token.get('/account.json').parsed || {} end end end end
Add simple link controller test
require 'rails_helper' RSpec.describe LinksController, type: :controller do end
require 'rails_helper' RSpec.describe LinksController, type: :controller do before do @local_authority = FactoryGirl.create(:local_authority, name: 'Angus') @service = FactoryGirl.create(:service, label: 'Service 1', lgsl_code: 1) @interaction = FactoryGirl.create(:interaction, label: 'Interaction 1', lgil_code: 3) end describe 'GET edit' do it 'retrieves HTTP success' do login_as_stub_user get :edit, local_authority_slug: @local_authority.slug, service_slug: @service.slug, interaction_slug: @interaction.slug expect(response).to have_http_status(:success) end end end
Remove deprecation warning for using table_exists?
if ActiveRecord.gem_version >= Gem::Version.new('5.0') class CreateUsers < ActiveRecord::Migration[4.2]; end else class CreateUsers < ActiveRecord::Migration; end end CreateUsers.class_eval do def up unless table_exists?("spree_users") create_table "spree_users", :force => true do |t| t.string "crypted_password", :limit => 128 t.string "salt", :limit => 128 t.string "email" t.string "remember_token" t.string "remember_token_expires_at" t.string "persistence_token" t.string "single_access_token" t.string "perishable_token" t.integer "login_count", :default => 0, :null => false t.integer "failed_login_count", :default => 0, :null => false t.datetime "last_request_at" t.datetime "current_login_at" t.datetime "last_login_at" t.string "current_login_ip" t.string "last_login_ip" t.string "login" t.integer "ship_address_id" t.integer "bill_address_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.string "openid_identifier" end end end end
if ActiveRecord.gem_version >= Gem::Version.new('5.0') class CreateUsers < ActiveRecord::Migration[4.2]; end else class CreateUsers < ActiveRecord::Migration; end end CreateUsers.class_eval do def up unless data_source_exists?("spree_users") create_table "spree_users", :force => true do |t| t.string "crypted_password", :limit => 128 t.string "salt", :limit => 128 t.string "email" t.string "remember_token" t.string "remember_token_expires_at" t.string "persistence_token" t.string "single_access_token" t.string "perishable_token" t.integer "login_count", :default => 0, :null => false t.integer "failed_login_count", :default => 0, :null => false t.datetime "last_request_at" t.datetime "current_login_at" t.datetime "last_login_at" t.string "current_login_ip" t.string "last_login_ip" t.string "login" t.integer "ship_address_id" t.integer "bill_address_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.string "openid_identifier" end end end end
Change RoomCreator service to be more friendly to Room interface
class RoomCreator attr_reader :owner, :room_name, :room def initialize(options) options.each do |k, v| instance_variable_set "@#{k}", v end end def call! ActiveRecord::Base.transaction do @room = Room.create! name: room_name, owner: owner Membership.create!(user: owner, room: room) end room end end
class RoomCreator attr_reader :owner, :name, :room def initialize(options) options.each do |k, v| instance_variable_set "@#{k}", v end end def call @room = Room.create name: name, owner: owner room.persisted? && Membership.create(user: owner, room: room) room end end
Update gem spec with description.
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'juxtapose/version' Gem::Specification.new do |spec| spec.name = "juxtapose" spec.version = Juxtapose::VERSION spec.authors = ["Joe Lind", "Thomas Mayfield"] spec.email = ["thomas@terriblelabs.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 require File.expand_path('../lib/juxtapose/version', __FILE__) Gem::Specification.new do |spec| spec.name = "juxtapose" spec.version = Juxtapose::VERSION spec.authors = ["Joe Lind", "Thomas Mayfield"] spec.email = ["thomas@terriblelabs.com"] spec.description = %q{Screenshot-based assertions for RubyMotion projects} spec.summary = %q{Screenshot-based assertions for RubyMotion 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" end
Fix a bug when building channel w/ MutableData
module Pakyow module UI module ChannelBuilder def self.build(scope: nil, mutation: nil, component: nil, qualifiers: [], data: [], qualifications: {}) channel = [] channel << "scope:#{scope}" unless scope.nil? channel << "mutation:#{mutation}" unless mutation.nil? channel << "component:#{component}" unless component.nil? channel_qualifiers = [] qualifiers = Array.ensure(qualifiers) unless qualifiers.empty? || data.empty? datum = Array.ensure(data).first qualifiers.inject(channel) do |channel, qualifier| channel_qualifiers << "#{qualifier}:#{datum[qualifier]}" end end qualifications.each do |name, value| next if value.nil? channel_qualifiers << "#{name}:#{value}" end channel = channel.join(';') if !channel_qualifiers.empty? channel << "::#{channel_qualifiers.join(';')}" end channel end end end end
module Pakyow module UI module ChannelBuilder def self.build(scope: nil, mutation: nil, component: nil, qualifiers: [], data: [], qualifications: {}) channel = [] channel << "scope:#{scope}" unless scope.nil? channel << "mutation:#{mutation}" unless mutation.nil? channel << "component:#{component}" unless component.nil? channel_qualifiers = [] qualifiers = Array.ensure(qualifiers) if data.is_a?(Pakyow::UI::MutableData) data = data.data end unless qualifiers.empty? || data.empty? datum = Array.ensure(data).first qualifiers.inject(channel) do |channel, qualifier| channel_qualifiers << "#{qualifier}:#{datum[qualifier]}" end end qualifications.each do |name, value| next if value.nil? channel_qualifiers << "#{name}:#{value}" end channel = channel.join(';') if !channel_qualifiers.empty? channel << "::#{channel_qualifiers.join(';')}" end channel end end end end
Add database cleaner to spec helper
require 'simplecov' SimpleCov.start do minimum_coverage 80 add_filter "/spec/" add_filter "/config/" end ENV['RAILS_ENV'] ||= 'test' require File.expand_path("../test_app/config/environment", __FILE__) require File.expand_path("../../lib/notifiable", __FILE__) require File.expand_path("../../app/controllers/notifiable/device_tokens_controller", __FILE__) require 'rspec/rails' require 'rspec/autorun' require 'factory_girl_rails' Rails.backtrace_cleaner.remove_silencers! Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } RSpec.configure do |config| config.mock_with :rspec config.use_transactional_fixtures = true config.infer_base_class_for_anonymous_controllers = false config.order = "random" config.include EngineControllerTestMonkeyPatch, :type => :controller config.before(:each) { Notifiable.delivery_method = :send } end class MockNotifier < Notifiable::NotifierBase def enqueue(notification, device_token) processed(notification, device_token) end end Notifiable.notifier_classes[:mock] = MockNotifier
require 'simplecov' SimpleCov.start do minimum_coverage 80 add_filter "/spec/" add_filter "/config/" end ENV['RAILS_ENV'] ||= 'test' require File.expand_path("../test_app/config/environment", __FILE__) require File.expand_path("../../lib/notifiable", __FILE__) require File.expand_path("../../app/controllers/notifiable/device_tokens_controller", __FILE__) require 'database_cleaner' require 'rspec/rails' require 'rspec/autorun' require 'factory_girl_rails' Rails.backtrace_cleaner.remove_silencers! Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } DatabaseCleaner.strategy = :truncation RSpec.configure do |config| config.mock_with :rspec config.use_transactional_fixtures = true config.infer_base_class_for_anonymous_controllers = false config.order = "random" config.include EngineControllerTestMonkeyPatch, :type => :controller config.before(:each) { DatabaseCleaner.start Notifiable.delivery_method = :send } config.after(:each) { DatabaseCleaner.clean } end class MockNotifier < Notifiable::NotifierBase def enqueue(notification, device_token) processed(notification, device_token) end end Notifiable.notifier_classes[:mock] = MockNotifier
Bring Yaks::Resource::Link to 100% explicit mutcov
RSpec.describe Yaks::Resource::Link do subject(:link) { described_class.new(rel: rel, uri: uri, options: options) } let(:rel) { :foo_rel } let(:uri) { 'http://api.example.org/rel/foo' } let(:options) { { title: 'mr. spectacular' } } its(:rel) { should eql :foo_rel } its(:uri) { should eql 'http://api.example.org/rel/foo' } its(:options) { should eql(title: 'mr. spectacular') } its(:title) { should eql('mr. spectacular') } its(:templated?) { should be false } context 'with explicit templated option' do let(:options) { super().merge(templated: true) } its(:templated?) { should be true } end describe '#rel?' do let(:rel) { "/rels/foo" } it 'should be true if the rel matches' do expect(link.rel?("/rels/foo")).to be true end it 'should be false if the rel does not match' do expect(link.rel?(:foo)).to be false end end end
RSpec.describe Yaks::Resource::Link do subject(:link) { described_class.new(rel: rel, uri: uri, options: options) } let(:rel) { :foo_rel } let(:uri) { 'http://api.example.org/rel/foo' } let(:options) { { title: 'mr. spectacular' } } its(:rel) { should eql :foo_rel } its(:uri) { should eql 'http://api.example.org/rel/foo' } its(:options) { should eql(title: 'mr. spectacular') } describe '#title' do its(:title) { should eql('mr. spectacular') } end describe '#templated?' do its(:templated?) { should be false } context 'with explicit templated option' do let(:options) { super().merge(templated: true) } its(:templated?) { should be true } end end describe '#rel?' do let(:rel) { "/rels/foo" } it 'should be true if the rel matches' do expect(link.rel?("/rels/foo")).to be true end it 'should be false if the rel does not match' do expect(link.rel?(:foo)).to be false end end end
Add test for verbose brew outdated output
describe "brew outdated", :integration_test do it "prints outdated Formulae" do setup_test_formula "testball" (HOMEBREW_CELLAR/"testball/0.0.1/foo").mkpath expect { brew "outdated" } .to output("testball\n").to_stdout .and not_to_output.to_stderr .and be_a_success end end
describe "brew outdated", :integration_test do context "quiet output" do it "prints outdated Formulae" do setup_test_formula "testball" (HOMEBREW_CELLAR/"testball/0.0.1/foo").mkpath expect { brew "outdated" } .to output("testball\n").to_stdout .and not_to_output.to_stderr .and be_a_success end end context "verbose output" do it "prints out the installed and newer versions" do setup_test_formula "testball" (HOMEBREW_CELLAR/"testball/0.0.1/foo").mkpath expect { brew "outdated", "--verbose" } .to output("testball (0.0.1) < 0.1\n").to_stdout .and not_to_output.to_stderr .and be_a_success end end end
Load extension based on ruby-specific version.
require 'sqlite3/sqlite3_native' require 'sqlite3/database' require 'sqlite3/version'
# support multiple ruby version (fat binaries under windows) begin RUBY_VERSION =~ /(\d+.\d+)/ require "sqlite3/#{$1}/sqlite3_native" rescue LoadError require 'sqlite3_native' end require 'sqlite3/database' require 'sqlite3/version'
Add notify list and get commands.
# encoding: utf-8 module GithubCLI class Commands::Notifications < Command namespace :notify option :all, :type => :boolean, :desc => "true to show notifications marked as read." option :participating, :type => :boolean, :desc => "true to show only notifications in which the user is directly participating or mentioned." option :since, :type => :string, :desc => "filters out any notifications updated before the given time" option :user, :type => :string, :aliases => ["-u"] option :repo, :type => :string, :aliases => ["-r"] desc 'list', 'List your notifications' long_desc <<-DESC Parameters all - Optional boolean - true to show notifications marked as read.\n participating - Optional boolean - true to show only notifications in which the user is directly participating or mentioned.\n since - Optional time - filters out any notifications updated before the given time.\n DESC def list params = options[:params].dup params['user'] = options[:user] if options[:user] params['repo'] = options[:repo] if options[:repo] Notification.all params, options[:format] end desc 'get <id>', 'View a single thread' def get(id) Notification.get id, options[:params], options[:format] end end # Notifications end # GithubCLI
Change to require Ruby > 2.0
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'tty/platform/version' Gem::Specification.new do |spec| spec.name = "tty-platform" spec.version = TTY::Platform::VERSION spec.authors = ["Piotr Murach"] spec.email = [""] spec.summary = %q{Query methods for detecting different operating systems.} spec.description = %q{Query methods for detecting different operating systems.} spec.homepage = "https://github.com/piotrmurach/tty-platform" spec.license = "MIT" spec.files = Dir['{lib,spec}/**/*.rb'] spec.files += Dir['{bin,tasks}/*', 'tty-platform.gemspec'] spec.files += Dir['README.md', 'CHANGELOG.md', 'LICENSE.txt', 'Rakefile'] 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.6" spec.add_development_dependency 'rspec', '~> 3.1' spec.add_development_dependency 'rake' end
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'tty/platform/version' Gem::Specification.new do |spec| spec.name = "tty-platform" spec.version = TTY::Platform::VERSION spec.authors = ["Piotr Murach"] spec.email = [""] spec.summary = %q{Query methods for detecting different operating systems.} spec.description = %q{Query methods for detecting different operating systems.} spec.homepage = "https://github.com/piotrmurach/tty-platform" spec.license = "MIT" spec.files = Dir['{lib,spec}/**/*.rb'] spec.files += Dir['{bin,tasks}/*', 'tty-platform.gemspec'] spec.files += Dir['README.md', 'CHANGELOG.md', 'LICENSE.txt', 'Rakefile'] 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.required_ruby_version = '>= 2.0.0' spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency 'rspec', '~> 3.1' spec.add_development_dependency 'rake' end
Set deprecation behavior to :notify in rails
begin require 'rails/railtie' # Register as early as possible to catch more warnings. # Warnings are enqueued and sent after gem is configured. GitHub::Deprecation.register! module GitHub::Deprecation class Railtie < Rails::Railtie config.to_prepare do # Starts reporting, warns if misconfigured. GitHub::Deprecation.start_reporting! end end end rescue LoadError => e # No Rails, no-op end
begin require 'rails/railtie' # Register as early as possible to catch more warnings. # Warnings are enqueued and sent after gem is configured. GitHub::Deprecation.register! module GitHub::Deprecation class Railtie < Rails::Railtie config.to_prepare do ActiveSupport::Deprecation.behavior = :notify # Starts reporting, warns if misconfigured. GitHub::Deprecation.start_reporting! end end end rescue LoadError => e # No Rails, no-op end
Add a file for misc tests, starting with test_empty_repository to try to reproduce an issue reported by a user on the mailing list
#!/usr/bin/ruby -w # # Test miscellaneous items that don't fit elsewhere # require "./#{File.dirname(__FILE__)}/etchtest" require 'webrick' class EtchMiscTests < Test::Unit::TestCase include EtchTests def setup # Generate a file to use as our etch target/destination @targetfile = released_tempfile #puts "Using #{@targetfile} as target file" # Generate a directory for our test repository @repodir = initialize_repository @server = get_server(@repodir) # Create a directory to use as a working directory for the client @testroot = tempdir #puts "Using #{@testroot} as client working directory" end def test_empty_repository # Does etch behave properly if the repository is empty? I.e. no source or # commands directories. testname = 'empty repository' run_etch(@server, @testroot, :testname => testname) end def teardown remove_repository(@repodir) FileUtils.rm_rf(@testroot) FileUtils.rm_rf(@targetfile) end end
Change product permalink references to slug
module Spree module Admin class SoundsController < ResourceController helper Spree::ProductSoundsHelper before_filter :load_data create.before :set_viewable update.before :set_viewable private def location_after_destroy admin_product_sounds_url(@product) end def location_after_save admin_product_sounds_url(@product) end def load_data @product = Product.find_by_permalink(params[:product_id]) @variants = @product.variants.collect do |variant| [variant.options_text, variant.id] end @variants.insert(0, [Spree.t(:all), @product.master.id]) end def set_viewable @sound.viewable_type = 'Spree::Variant' @sound.viewable_id = params[:sound][:viewable_id] end end end end
module Spree module Admin class SoundsController < ResourceController helper Spree::ProductSoundsHelper before_filter :load_data create.before :set_viewable update.before :set_viewable private def location_after_destroy admin_product_sounds_url(@product) end def location_after_save admin_product_sounds_url(@product) end def load_data @product = Product.find_by_slug(params[:product_id]) @variants = @product.variants.collect do |variant| [variant.options_text, variant.id] end @variants.insert(0, [Spree.t(:all), @product.master.id]) end def set_viewable @sound.viewable_type = 'Spree::Variant' @sound.viewable_id = params[:sound][:viewable_id] end end end end
Patch rake test for Ruby 1.9.3 and Rake 0.9.2.
# Patch for https://github.com/jimweirich/rake/issues/51 if Rake::VERSION == "0.9.2" && RUBY_VERSION == "1.9.3" %w[ units functionals integration ].each do |name| path = name.sub(/s$/, "") task("test:#{name}").clear_actions Rake::TestTask.new("test:#{name}") do |t| t.libs << "test" t.test_files = Dir["test/#{path}/**/*_test.rb"] end end end
Add Tracker id to TasksTable
require 'hirb' module PT class DataTable extend ::Hirb::Console def initialize(dataset) @rows = dataset.map{ |row| DataRow.new(row, dataset) } end def print if @rows.empty? puts "\n -- empty list -- \n" else self.class.table @rows, :fields => [:num] + self.class.fields, :unicode => true, :description => false end end def [](pos) pos = pos.to_i (pos < 1 || pos > @rows.length) ? nil : @rows[pos-1].record end def length @rows.length end def self.fields [] end end class ProjectTable < DataTable def self.fields [:name] end end class TasksTable < DataTable def self.fields [:name, :current_state] end end class MembersTable < DataTable def self.fields [:name] end end end
require 'hirb' module PT class DataTable extend ::Hirb::Console def initialize(dataset) @rows = dataset.map{ |row| DataRow.new(row, dataset) } end def print if @rows.empty? puts "\n -- empty list -- \n" else self.class.table @rows, :fields => [:num] + self.class.fields, :unicode => true, :description => false end end def [](pos) pos = pos.to_i (pos < 1 || pos > @rows.length) ? nil : @rows[pos-1].record end def length @rows.length end def self.fields [] end end class ProjectTable < DataTable def self.fields [:name] end end class TasksTable < DataTable def self.fields [:name, :current_state, :id] end end class MembersTable < DataTable def self.fields [:name] end end end
Add initial dependencies to gemspec
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'spira/active_record_isomorphisms/version' Gem::Specification.new do |spec| spec.name = "spira-active_record_isomorphisms" spec.version = Spira::ActiveRecordIsomorphisms::VERSION spec.authors = ["Nicholas Hurden"] spec.email = ["git@nhurden.com"] spec.summary = %q{TODO: Write a short summary. Required.} spec.description = %q{TODO: Write a longer description. Optional.} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.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 'spira/active_record_isomorphisms/version' Gem::Specification.new do |spec| spec.name = "spira-active_record_isomorphisms" spec.version = Spira::ActiveRecordIsomorphisms::VERSION spec.authors = ["Nicholas Hurden"] spec.email = ["git@nhurden.com"] spec.summary = %q{TODO: Write a short summary. Required.} spec.description = spec.summary #spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.required_ruby_version = ">= 1.9.3" spec.add_runtime_dependency "spira", "~> 0.7" spec.add_runtime_dependency "activerecord", "~> 4.1" spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.1" spec.add_development_dependency "sqlite3", "~> 1.3" spec.add_development_dependency "yard", "~> 0.6" end
Exclude specjour internals from rspec backtraces
module Specjour::RSpec::Runner def self.run(spec, output) args = ['--format=Specjour::RSpec::DistributedFormatter', spec] ::RSpec::Core::Runner.run args, $stderr, output ensure ::RSpec.configuration.formatters.clear end end
module Specjour::RSpec::Runner ::RSpec::Core::Runner::AT_EXIT_HOOK_BACKTRACE_LINE.replace "#{__FILE__}:#{__LINE__ + 3}:in `run'" def self.run(spec, output) args = ['--format=Specjour::RSpec::DistributedFormatter', spec] ::RSpec::Core::Runner.run args, $stderr, output ensure ::RSpec.configuration.formatters.clear end end
Use alias_method instead of prepend to avoid conflicts with hobo_support
# frozen_string_literal: true require_relative './multi_sender' # Invoca ::Array extensions module Invoca module Utils module ArrayMultiply def *(rhs = nil) if rhs super else Invoca::Utils::MultiSender.new(self, :map) end end end end end Array.prepend(Invoca::Utils::ArrayMultiply)
# frozen_string_literal: true require_relative './multi_sender' # Invoca ::Array extensions # TODO: Once the hobo_support gem is no longer used by any of our code, use prepend instead of alias class Array alias_method :multiply, :* def *(rhs=nil) if rhs multiply(rhs) else Invoca::Utils::MultiSender.new(self, :map) end end end
Change method from move files to copy files
module UltrasoundDriver class ProcessDirectory def initialize(input_path, destination_path) @input_path, @destination_path = input_path, destination_path @patients = [] end def work_directory read_main_folder process_folders end def read_main_folder Dir.entries(@input_path).each do |folder| next if ['.','..'].include? folder next unless File.directory? File.join(@input_path, folder) @patients << UltrasoundDriver::UltrasoundPatientFolder.new(File.join(@input_path, folder)) end end def process_folders @patients.each do |patient| patient.folder_date_of_services.each do |dos| full_path = patient.destination_path(@destination_path, dos) create_directory(full_path) move_files(dos,full_path) end end end def create_directory(full_path) if !File.directory? full_path FileUtils.mkdir_p full_path end end def move_files(dos_path, full_path) Dir.glob(dos_path + '/*.*' ).each do |filename| FileUtils.cp(filename, full_path) end end end end
module UltrasoundDriver class ProcessDirectory def initialize(input_path, destination_path) @input_path, @destination_path = input_path, destination_path @patients = [] end def work_directory read_main_folder process_folders end def read_main_folder Dir.entries(@input_path).each do |folder| next if ['.','..'].include? folder next unless File.directory? File.join(@input_path, folder) @patients << UltrasoundDriver::UltrasoundPatientFolder.new(File.join(@input_path, folder)) end end def process_folders @patients.each do |patient| patient.folder_date_of_services.each do |dos| full_path = patient.destination_path(@destination_path, dos) create_directory(full_path) copy_files(dos,full_path) end end end def create_directory(full_path) if !File.directory? full_path FileUtils.mkdir_p full_path end end def copy_files(dos_path, full_path) Dir.glob(dos_path + '/*.*' ).each do |filename| FileUtils.cp(filename, full_path) end end end end
Update OmniFocus Beta to version 2.2.x-r241602
cask :v1 => 'omnifocus-beta' do version '2.2.x-r238263' sha256 '2524ac2ec3541bd65a5aabac111c72f47a05d589b17e313ea37668a498476f58' url "http://omnistaging.omnigroup.com/omnifocus-2.2.x/releases/OmniFocus-#{version}-Test.dmg" name 'OmniFocus' homepage 'http://omnistaging.omnigroup.com/omnifocus-2.2.x/' license :commercial app 'OmniFocus.app' zap :delete => [ '~/Library/containers/com.omnigroup.omnifocus2', '~/Library/Preferences/com.omnigroup.OmniFocus2.LSSharedFileList.plist', '~/Library/Preferences/com.omnigroup.OmniSoftwareUpdate.plist', '~/Library/Caches/Metadata/com.omnigroup.OmniFocus2' ] end
cask :v1 => 'omnifocus-beta' do version '2.2.x-r241602' sha256 '72c8e43de504ba18450d8c04cefefeea8e90bb81561b8c52869c2ce91ed61ae8' url "http://omnistaging.omnigroup.com/omnifocus-2.2.x/releases/OmniFocus-#{version}-Test.dmg" name 'OmniFocus' homepage 'http://omnistaging.omnigroup.com/omnifocus-2.2.x/' license :commercial app 'OmniFocus.app' zap :delete => [ '~/Library/containers/com.omnigroup.omnifocus2', '~/Library/Preferences/com.omnigroup.OmniFocus2.LSSharedFileList.plist', '~/Library/Preferences/com.omnigroup.OmniSoftwareUpdate.plist', '~/Library/Caches/Metadata/com.omnigroup.OmniFocus2' ] end
Handle VM creation & ready check better.
require 'fog/core/model' module Fog module Compute class Octocloud class Server < Fog::Model identity :id attribute :memory attribute :name attribute :message attribute :expiry attribute :cube attribute :mac attribute :type, :aliases => :hypervisor_type attribute :hypervisor_host attribute :template attribute :running attribute :ip def running? running end def initialize(attributes={}) super end def save requires :memory, :type, :cube data = connection.create_vm(attributes) merge_attributes(data) true end def destroy requires :id connection.delete_vm(id) true end end end end end
require 'fog/core/model' module Fog module Compute class Octocloud class Server < Fog::Model identity :id attribute :memory attribute :name attribute :message attribute :expiry attribute :cube attribute :mac attribute :type, :aliases => :hypervisor_type attribute :hypervisor_host attribute :template attribute :running attribute :ip def running? running end def ready? reload running && ip end def public_ip_address ip end # def initialize(attributes={}) # super # end def save requires :memory, :type, :cube attributes[:cube] = cube.kind_of?(Cube) ? cube.name : cube attributes[:memory] = memory.to_i data = connection.create_vm(attributes) merge_attributes(data) true end def destroy requires :id connection.delete_vm(id) true end end end end end
Introduce GW2_POOL_SIZE to setup concurrency
require 'rest-gw2' warmup do RestCore.eagerload RestCore.eagerload(RestGW2) RestGW2::Client.new end run RestGW2::Server
require 'rest-gw2' warmup do RestCore.eagerload RestCore.eagerload(RestGW2) RestGW2::Client.new end if pool_size = ENV['GW2_POOL_SIZE'] RestGW2::Client.pool_size = Integer(pool_size) end run RestGW2::Server
Add enhanced spec tests for ConnectParams
describe FFI::VixDiskLib::API do let(:major_version) { described_class::VERSION_MAJOR } let(:minor_version) { described_class::VERSION_MINOR } let(:log) { lambda { |_string, _pointer| } } let(:lib_dir) { nil } context "init" do it "initializes successfully" do err = described_class.init(major_version, minor_version, log, log, log, lib_dir) expect(err).to eq(described_class::VixErrorType[:VIX_OK]) end end end
describe FFI::VixDiskLib::API do let(:major_version) { described_class::VERSION_MAJOR } let(:minor_version) { described_class::VERSION_MINOR } let(:log) { lambda { |_string, _pointer| } } let(:lib_dir) { nil } context "init" do it "initializes successfully" do err = described_class.init(major_version, minor_version, log, log, log, lib_dir) expect(err).to eq(described_class::VixErrorType[:VIX_OK]) end end context "ConnectParams" do case described_class::VERSION when "6.5.0" it "has vimApiVer" do expect(described_class::ConnectParams.members).to include(:vimApiVer) end else it "doesn't have vimApiVer" do expect(described_class::ConnectParams.members).to_not include(:vimApiVer) end end end end
Add uninstall stanza for Logitech Unifying
class LogitechUnifying < Cask url 'http://www.logitech.com/pub/controldevices/unifying/unifying1.10.421.dmg' homepage 'http://www.logitech.com/en-us/promotions/6072' version '1.10.421' sha256 'd9e196411cc4c0aec72fd01575eaffed228f95bc7d7ededc532d53f8602caa03' install 'Logitech Unifying Software.mpkg' end
class LogitechUnifying < Cask url 'http://www.logitech.com/pub/controldevices/unifying/unifying1.10.421.dmg' homepage 'http://www.logitech.com/en-us/promotions/6072' version '1.10.421' sha256 'd9e196411cc4c0aec72fd01575eaffed228f95bc7d7ededc532d53f8602caa03' install 'Logitech Unifying Software.mpkg' uninstall :pkgutil => 'com.Logitech.*pkg' end
Update Google Analytics dependence to the new reference
Pod::Spec.new do |s| s.name = 'JohnnyEnglish' s.version = '0.0.3' s.summary = 'A light-weight AOP-based analytics binder' s.homepage = "https://github.com/ef-ctx/JohnnyEnglish" s.license = { :type => 'MIT', :file => 'LICENSE' } s.authors = { "Dmitry Makarenko" => "dmitry.makarenko@ef.com", "Alberto De Bortoli" => "'alberto.debortoli@ef.com", "Mário Barbosa" => "mario.araujo@ef.com" } s.dependency 'Aspects', '~>1.4.1.1ctx' s.dependency 'GoogleAnalytics-iOS-SDK', '~> 3.0' s.platform = :ios s.ios.deployment_target = '7.0' s.requires_arc = true s.source = { :git => 'git@github.com:ef-ctx/JohnnyEnglish.git', :tag => "#{s.version}" } s.source_files = 'Sources/**/*.{h,m}' end
Pod::Spec.new do |s| s.name = 'JohnnyEnglish' s.version = '0.0.4' s.summary = 'A light-weight AOP-based analytics binder' s.homepage = "https://github.com/ef-ctx/JohnnyEnglish" s.license = { :type => 'MIT', :file => 'LICENSE' } s.authors = { "Dmitry Makarenko" => "dmitry.makarenko@ef.com", "Alberto De Bortoli" => "'alberto.debortoli@ef.com", "Mário Barbosa" => "mario.araujo@ef.com" } s.dependency 'Aspects', '~>1.4.1.1ctx' s.dependency 'GoogleAnalytics' s.platform = :ios s.ios.deployment_target = '7.0' s.requires_arc = true s.source = { :git => 'git@github.com:ef-ctx/JohnnyEnglish.git', :tag => "#{s.version}" } s.source_files = 'Sources/**/*.{h,m}' end
Remove process_action.action_controller from logs panel notifications because this informations are from the previous request
Log = Struct.new(:name, :duration, :payload) class LogsPanel < Panel def initialize @logs = [] end def notifications return ['sql.active_record', 'process_action.action_controller', 'process_request.around_filter_end', '!render_template.action_view'] end def notify(name, start, finish, id, payload) @logs << Log.new(name, ((finish - start) * 1000).round(1), payload) end def reset(request, response) @logs = [] end def render logs_render = '' File.open(File.expand_path('../views/logs-panel/log.html', File.dirname(__FILE__)), 'r') do |file| lines = file.readlines @logs.each do |log| logs_render += lines.join('').gsub('#{name}', log.name.to_s).gsub('#{duration}', "%0.1f" % log.duration).gsub('#{payload}', log.payload.to_s.gsub('\"', '"')) end end logs_panel_render = '' File.open(File.expand_path('../views/logs-panel.html', File.dirname(__FILE__)), 'r') do |file| logs_panel_render = file.readlines.join('').gsub('#{logs}', logs_render) end return logs_panel_render end end
Log = Struct.new(:name, :duration, :payload) class LogsPanel < Panel def initialize @logs = [] end def notifications return ['sql.active_record', 'process_request.around_filter_end', '!render_template.action_view'] end def notify(name, start, finish, id, payload) @logs << Log.new(name, ((finish - start) * 1000).round(1), payload) end def reset(request, response) @logs = [] end def render logs_render = '' File.open(File.expand_path('../views/logs-panel/log.html', File.dirname(__FILE__)), 'r') do |file| lines = file.readlines @logs.each do |log| logs_render += lines.join('').gsub('#{name}', log.name.to_s).gsub('#{duration}', "%0.1f" % log.duration).gsub('#{payload}', log.payload.to_s.gsub('\"', '"')) end end logs_panel_render = '' File.open(File.expand_path('../views/logs-panel.html', File.dirname(__FILE__)), 'r') do |file| logs_panel_render = file.readlines.join('').gsub('#{logs}', logs_render) end return logs_panel_render end end
Change to please code climate
# frozen_string_literal: true class AnalyticsController < ApplicationController before_action :check_for_admin_or_analyst, only: %i[show index] def show; end def index @last_days = 30 @full_width_content = true @visits = Visit.this_month @users = User.where(created_at: @last_days.days.ago..Time.now) @views = Ahoy::Event.where(name: '$view') @articles = Article.this_month end private def check_for_admin_or_analyst authenticate_user! return if current_user.admin? or current_user.analyst? redirect_to root_url # or whatever end end
# frozen_string_literal: true class AnalyticsController < ApplicationController before_action :check_for_admin_or_analyst, only: %i[show index] def show; end def index @last_days = 30 @full_width_content = true @visits = Visit.this_month @users = User.where(created_at: @last_days.days.ago..Time.now) @views = Ahoy::Event.where(name: '$view') @articles = Article.this_month end private def check_for_admin_or_analyst authenticate_user! return if current_user.admin? || current_user.analyst? redirect_to root_url # or whatever end end
Add script for generating code from a shorthand.
require 'pp' require 'set' MusicGraph = Struct.new(:bands, :musicians, :connections) Connection = Struct.new(:source, :target, :label) def musician_variable_name(human_name) name_parts = human_name.gsub(/[^a-zA-Z0-9 ]/, '').downcase.split name_parts.last + '_' + name_parts.first[0] end def band_variable_name(human_name) human_name.gsub(/[^a-zA-Z0-9 ]/, ' ').downcase.split.join('_') end def parse(source) bands = Set.new musicians = Set.new connections = [] current_band = nil lines = source.split("\n") lines.each do |line| # Ignore lines starting with question marks. next if line.match(/^\s*\?/) if line.match(/^\s/) # Parsing an indented line within a band section. This is a connection to # that band. abort "Unexpected indented line: '#{line}'" unless current_band if m = line.match(/^\s+\{(?<label>[^}]*)\}\s*(?<band>.+)$/) band = m[:band].strip bands.add(band) connections.push(Connection.new(band_variable_name(band), band_variable_name(current_band), m[:label])) elsif m = line.match(/^\s+(?:\[(?<label>[^}]*)\]\s*)?(?<musician>.+)$/) musician = m[:musician].strip musicians.add(musician) connections.push(Connection.new(musician_variable_name(musician), band_variable_name(current_band), m[:label])) else abort "Malformed line: '#{line}'" end else # Parsing a new band section. current_band = line.strip bands.add(current_band) end end MusicGraph.new(bands, musicians, connections) end def format(graph) graph.bands.each do |band| puts "#{band_variable_name(band)} = g.band '#{band}'" end puts graph.musicians.each do |musician| puts "#{musician_variable_name(musician)} = g.person '#{musician}'" end puts graph.connections.each do |connection| label = connection.label || 'member' puts "#{connection.target}.#{label} #{connection.source}" end end graph = parse(File.read(ARGV[0])) format(graph)
Change set_table_name for self.table_name= so it's compatible with ActiveRecord 3.2
module Ponch class Delivery < ActiveRecord::Base set_table_name :ponch_deliveries validates_presence_of :to, :from, :sent_at scope :opened, where("opened_at is not null") before_create :generate_code def opened? !opened_at.nil? end def open!(ip_address = nil) unless opened? self.opened_at = Time.now self.opened_ip = ip_address self.save! end end #class methods def self.create_from_mail(mail) self.create! to: mail.to.first, from: mail.from.first, subject: mail.subject, sent_at: Time.now end private def generate_code self.code = loop do code_attempt = SecureRandom.hex(20) break code_attempt unless self.class.find_by_code(code_attempt) end end end end
module Ponch class Delivery < ActiveRecord::Base self.table_name = "ponch_deliveries" validates_presence_of :to, :from, :sent_at scope :opened, where("opened_at is not null") before_create :generate_code def opened? !opened_at.nil? end def open!(ip_address = nil) unless opened? self.opened_at = Time.now self.opened_ip = ip_address self.save! end end #class methods def self.create_from_mail(mail) self.create! to: mail.to.first, from: mail.from.first, subject: mail.subject, sent_at: Time.now end private def generate_code self.code = loop do code_attempt = SecureRandom.hex(20) break code_attempt unless self.class.find_by_code(code_attempt) end end end end
Save original requested path before redirecting to sign-in
require_dependency "admin/application_controller" module Admin class AdminController < ApplicationController before_filter :authenticate_admin! def index end private def authenticate_admin! unless current_user && current_user.is_admin? redirect_to main_app.new_session_path, alert: t('admin.action.needs_sign_in', action: "Admin") end end end end
require_dependency "admin/application_controller" module Admin class AdminController < ApplicationController before_filter :authenticate_admin! def index end private def authenticate_admin! unless current_user && current_user.is_admin? session[:requested_path] = request.original_fullpath redirect_to main_app.new_session_path, alert: t('admin.action.needs_sign_in', action: "Admin") end end end end
Remove UrlHelpers from ApplicationController as it was breaking tests
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 include SessionsHelper include ActionView::Helpers::UrlHelper private # Confirms a logged-in user. def logged_in_user unless logged_in? store_location flash[:danger] = "Please log in.<br>If you don't already have an account, #{link_to('click here', new_user_path).html_safe} to get started!" redirect_to login_url end end # Confirms the correct user. def correct_user @user = User.find_by_id(params[:id]) || User.find_by_id(params[:user_id]) || @current_user redirect_to(root_url) unless current_user?(@user) 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 include SessionsHelper private # Confirms a logged-in user. def logged_in_user unless logged_in? store_location flash[:danger] = "Please log in.<br>If you don't already have an account, <a href='/signup'>click here</a> to get started!" redirect_to login_url end end # Confirms the correct user. def correct_user @user = User.find_by_id(params[:id]) || User.find_by_id(params[:user_id]) || @current_user redirect_to(root_url) unless current_user?(@user) end end
Update count for all members, THIS COULD GET EXPENSIVE
class Task < ActiveRecord::Base include Authority::Abilities self.authorizer_name = 'TaskAuthorizer' include Concerns::DateWriter acts_as_list scope: :group belongs_to :group belongs_to :person belongs_to :site has_many :comments, as: :commentable, dependent: :destroy scope_by_site_id scope :incomplete, -> { where(completed: false) } validates :name, :group_id, presence: true after_save :update_counter_cache after_destroy :update_counter_cache def person_id_or_all=id (self.group_scope = !!(id == "All")) ? self.person_id = nil : self.person_id = id id end def person_id_or_all group_scope ? "All" : person_id end def update_counter_cache self.person.update_attribute(:incomplete_tasks_count, self.person.tasks.incomplete.count) if self.person.present? end date_writer :duedate end
class Task < ActiveRecord::Base include Authority::Abilities self.authorizer_name = 'TaskAuthorizer' include Concerns::DateWriter acts_as_list scope: :group belongs_to :group belongs_to :person belongs_to :site has_many :comments, as: :commentable, dependent: :destroy scope_by_site_id scope :incomplete, -> { where(completed: false) } validates :name, :group_id, presence: true after_save :update_counter_cache after_destroy :update_counter_cache def person_id_or_all=id self.person_id= (self.group_scope = !!(id == "All")) ? nil : id id end def person_id_or_all group_scope ? "All" : person_id end def update_counter_cache Person.find([].append(self.group_scope && self.group.memberships.pluck(:person_id)).flatten.append(self.person_id).reject {|n| !n}.uniq).each do |assigned| assigned.update_attribute(:incomplete_tasks_count, assigned.tasks.incomplete.count) end end date_writer :duedate end
Stop using the deprecated CurationConcerns::SearchBuilder.
class DepositSearchBuilder < CurationConcerns::SearchBuilder # includes the depositor_facet to get information on deposits. # use caution when combining this with other searches as it sets the rows to zero to just get the facet information # @param solr_parameters the current solr parameters def include_depositor_facet(solr_parameters) solr_parameters[:"facet.field"].concat([Solrizer.solr_name("depositor", :symbol)]) # defualt facet limit is 10, which will only show the top 10 users not all users deposits solr_parameters[:"facet.limit"] = ::User.count # only get file information solr_parameters[:fq] = "has_model_ssim:GenericWork" # we only want the facte counts not the actual data solr_parameters[:rows] = 0 end end
class DepositSearchBuilder < ::SearchBuilder # includes the depositor_facet to get information on deposits. # use caution when combining this with other searches as it sets the rows to zero to just get the facet information # @param solr_parameters the current solr parameters def include_depositor_facet(solr_parameters) solr_parameters[:"facet.field"].concat([Solrizer.solr_name("depositor", :symbol)]) # defualt facet limit is 10, which will only show the top 10 users not all users deposits solr_parameters[:"facet.limit"] = ::User.count # only get file information solr_parameters[:fq] = "has_model_ssim:GenericWork" # we only want the facte counts not the actual data solr_parameters[:rows] = 0 end end
Add some pending tests on where to go next
require 'bigdecimal' require 'ynab' describe Ynab do let(:ynab) { Ynab.open('./spec/fixtures/Test~E8570C74.ynab4') } describe '.transactions' do let(:transactions) { ynab.transactions } let(:transaction) { ynab.transactions.first } it 'shows how many total transactions exist for a budget' do expect(transactions.count).to eq 4 end it "shows transaction's date" do expect(transaction.date).to eq Date.new(2014, 2, 17) end it "shows transaction's amount" do expect(transactions[3].amount).to eq -100.12 end it "shows transaction's memo" do expect(transaction.memo).to eq "A sample memo!" end it "shows transaction's account" it "shows transaction's payee" it "shows transaction's category" end end
require 'bigdecimal' require 'ynab' describe Ynab do let(:ynab) { Ynab.open('./spec/fixtures/Test~E8570C74.ynab4') } describe '.transactions' do let(:transactions) { ynab.transactions } let(:transaction) { ynab.transactions.first } it 'shows how many total transactions exist for a budget' do expect(transactions.count).to eq 4 end it "shows transaction's date" do expect(transaction.date).to eq Date.new(2014, 2, 17) end it "shows transaction's amount" do expect(transactions[3].amount).to eq -100.12 end it "shows transaction's memo" do expect(transaction.memo).to eq "A sample memo!" end it "shows transaction's account" do pending "waiting on parsing account objects" expect(transaction.account.name).to eq "Savings" end it "shows transaction's payee" do pending "waiting on parsing payee objects" expect(transaction.payee.name).to eq "Starting Balance" end it "shows transaction's category" do pending "waiting on parsing category objects" end end end
Create index for user_id, created_at in Micropost
class CreateMicroposts < ActiveRecord::Migration def change create_table :microposts do |t| t.string :content t.integer :user_id t.timestamps null: false end end end
class CreateMicroposts < ActiveRecord::Migration def change create_table :microposts do |t| t.string :content t.integer :user_id t.timestamps null: false end add_index :microposts, [:user_id, :created_at] end end
Change the files in the gemspec
# Provide a simple gemspec so you can easily use your enginex # project in your rails apps through git. Gem::Specification.new do |s| s.name = "asset_hash" s.summary = "Asset hasher for Cloudfront custom origin domain asset hosting." s.description = "This gem allows you to copy your static assets to a versions including a unique hash in the filename. By using this and modifying your Rails asset path you can easily serve static content on Cloudfront using the custom origin policy." s.files = Dir["{app,lib,config}/**/*"] + ["MIT-LICENSE", "Rakefile", "Gemfile", "README.rdoc"] s.version = "0.1" if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 2 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<mime-types>, [">= 1.16"]) else s.add_dependency(%q<mime-types>, [">= 1.16"]) end else s.add_dependency(%q<mime-types>, [">= 1.16"]) end end
# Provide a simple gemspec so you can easily use your enginex # project in your rails apps through git. Gem::Specification.new do |s| s.name = "asset_hash" s.summary = "Asset hasher for Cloudfront custom origin domain asset hosting." s.description = "This gem allows you to copy your static assets to a versions including a unique hash in the filename. By using this and modifying your Rails asset path you can easily serve static content on Cloudfront using the custom origin policy." s.files = Dir["{app,lib,config}/**/*"] + ["MIT-LICENSE", "Rakefile", "Gemfile", "README.textile"] s.version = "0.1" if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 2 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<mime-types>, [">= 1.16"]) else s.add_dependency(%q<mime-types>, [">= 1.16"]) end else s.add_dependency(%q<mime-types>, [">= 1.16"]) end end
Add formtastic 2.0 compatible form helper
module Formtastic module Inputs class EnumInput < Formtastic::Inputs::SelectInput def raw_collection raise "Attribute '#{@method}' has no enum class" unless enum = @object.class.active_enum_for(@method) @raw_collection ||= enum.to_select end end end end module ActiveEnum module FormHelpers module Formtastic2 def default_input_type_with_active_enum(method, options) return :enum if @object.class.respond_to?(:active_enum_for) && @object.class.active_enum_for(method) default_input_type_without_active_enum(method, options) end end end end Formtastic::Helpers::InputHelper.class_eval do include ActiveEnum::FormHelpers::Formtastic2 alias_method_chain :default_input_type, :active_enum end
Configure Devise for deleting a User
feature "User Deletes profile" do before do @user = Fabricate(:user) end scenario "Happy path" do visit '/' click_link "Sign In" fill_in "Email", with: "#{@user.email}" fill_in "Password", with: "#{@user.password}" click_button "Log in" expect(page).to have_content("Edit Profile") click_link "Edit Profile" expect(current_path).to eq(edit_user_registration_path) click_link "Cancel my account" expect(current_path).to eq(new_user_session_path) expect(page).to have_content("Bye! Your account has been successfully cancelled. We hope to see you again soon.") end end
Add missing authorization to read Place models for guest users.
class Ability include CanCan::Ability def initialize(user) # Create guest user aka. anonymous (not logged-in) when user is nil. user ||= User.new if user.has_role? :admin can :manage, :all elsif user.has_role? :user can :manage, Farm do |farm| farm.authorized?(user) end can :manage, Depot do |depot| depot.authorized?(user) end can :read, Place can :read, Depot can :create, Depot can :read, Farm can :create, Farm can :read, Image can :create, Image can :geocode, :location can :read, User do |u| user.id == u.id end else # guest user aka. anonymous can :read, Farm can :read, Depot can :read, Image end end end
class Ability include CanCan::Ability def initialize(user) # Create guest user aka. anonymous (not logged-in) when user is nil. user ||= User.new if user.has_role? :admin can :manage, :all elsif user.has_role? :user can :manage, Farm do |farm| farm.authorized?(user) end can :manage, Depot do |depot| depot.authorized?(user) end can :read, Place can :read, Depot can :create, Depot can :read, Farm can :create, Farm can :read, Image can :create, Image can :geocode, :location can :read, User do |u| user.id == u.id end else # guest user aka. anonymous can :read, Place can :read, Farm can :read, Depot can :read, Image end end end
Fix platform dependent issue of sticky bit.
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../../../shared/file/sticky', __FILE__) describe "File.sticky?" do it_behaves_like :file_sticky, :sticky?, File it_behaves_like :file_sticky_missing, :sticky?, File end describe "File.sticky?" do it "returns false if file does not exist" do File.sticky?("I_am_a_bogus_file").should == false end it "returns false if the file has not sticky bit set" do filename = tmp("i_exist") touch(filename) File.sticky?(filename).should == false rm_r filename end platform_is_not :windows do it "returns true if the file has sticky bit set" do filename = tmp("i_exist") touch(filename) system "chmod +t #{filename}" File.sticky?(filename).should == true rm_r filename end end end
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../../../shared/file/sticky', __FILE__) describe "File.sticky?" do it_behaves_like :file_sticky, :sticky?, File it_behaves_like :file_sticky_missing, :sticky?, File end describe "File.sticky?" do it "returns false if file does not exist" do File.sticky?("I_am_a_bogus_file").should == false end it "returns false if the file has not sticky bit set" do filename = tmp("i_exist") touch(filename) File.sticky?(filename).should == false rm_r filename end platform_is :linux, :darwin do it "returns true if the file has sticky bit set" do filename = tmp("i_exist") touch(filename) system "chmod +t #{filename}" File.sticky?(filename).should == true rm_r filename end end platform_is :bsd do # FreeBSD and NetBSD can't set stiky bit to a normal file it "cannot set sticky bit to a normal file" do filename = tmp("i_exist") touch(filename) stat = File.stat(filename) mode = stat.mode raise_error(Errno::EFTYPE){File.chmod(mode|01000, filename)} File.sticky?(filename).should == false rm_r filename end end end
Apply the sync at 8 & 11 pm
set :output, { error: 'log/cron.error.log', standard: 'log/cron.log'} # We need Rake to use our own environment job_type :rake, "cd :path && /usr/local/bin/govuk_setenv tariff-api bundle exec rake :task --silent :output" every 1.hour do rake "tariff:sync:apply" end
set :output, { error: 'log/cron.error.log', standard: 'log/cron.log'} # We need Rake to use our own environment job_type :rake, "cd :path && /usr/local/bin/govuk_setenv tariff-api bundle exec rake :task --silent :output" every 1.day, at: "8:00 pm" do rake "tariff:sync:apply" end every 1.day, at: "11:00 pm" do rake "tariff:sync:apply" end
Update Opera developer to 29.0.1781.0
cask :v1 => 'opera-developer' do version '28.0.1750.5' sha256 '323d8a24b6afd63fba8c0d17a6e810cc4cfd454df488499a395bf0ff70421335' url "http://get.geo.opera.com/pub/opera-developer/#{version}/mac/Opera_Developer_#{version}_Setup.dmg" homepage 'http://www.opera.com/developer' license :unknown app 'Opera Developer.app' end
cask :v1 => 'opera-developer' do version '29.0.1781.0' sha256 'b3b24c1456722318eea3549169af43f268ccc0f015d3a8ad739bbe2c57a42d26' url "http://get.geo.opera.com/pub/opera-developer/#{version}/mac/Opera_Developer_#{version}_Setup.dmg" homepage 'http://www.opera.com/developer' license :unknown app 'Opera Developer.app' end
Fix same bug for schools.
class SchoolsController < ApplicationController load_resource def index @schools = School.order(:official_name).paginate(:page => params[:page], :per_page => 25) end def create @school = School.new(school_params) @school.save redirect_to @school end def update if @school.update(school_params) redirect_to @school else render 'edit' end end private def school_params params.require(:school).permit(:name, :official_name, :website, :office_phone, :fax, :address1, :address2, :city, :state, :zip, :country, :notes, :region, :prek, :elementary, :middle, :highschool) end end
class SchoolsController < ApplicationController load_and_authorize_resource except: [:create] def index @schools = School.order(:official_name).paginate(:page => params[:page], :per_page => 25) end def create @school = School.new(school_params) @school.save redirect_to @school end def update if @school.update(school_params) redirect_to @school else render 'edit' end end private def school_params params.require(:school).permit(:name, :official_name, :website, :office_phone, :fax, :address1, :address2, :city, :state, :zip, :country, :notes, :region, :prek, :elementary, :middle, :highschool) end end
Add detect_spreefinery_single_sign_on for frontend UserSessionsController
Spree::UserSessionsController.class_eval do skip_before_action :detect_spreefinery_single_sign_on! private # This overrides what Spree defines, so that we can get back to Refinery. def after_sign_in_path_for(resource) session["spree_user_return_to"] || super end end
Make sure GTypeModule is loaded before trying to get its interfaces.
require File.expand_path('../gir_ffi_test_helper.rb', File.dirname(__FILE__)) describe "The generated GObject module" do before do GirFFI.setup :GObject end describe "#type_interfaces" do it "works, showing that returning an array of GType works" do tp = GObject.type_from_name 'GTypeModule' tp.must_be :>, 0 ifcs = GObject.type_interfaces tp assert_equal 1, ifcs.size end end describe "the TypePlugin interface" do it "is implemented as a module" do mod = GObject::TypePlugin assert_instance_of Module, mod refute_instance_of Class, mod end end describe "the TypeModule class" do it "has the GObject::TypePlugin module as an ancestor" do klass = GObject::TypeModule assert_includes klass.ancestors, GObject::TypePlugin end end end
require File.expand_path('../gir_ffi_test_helper.rb', File.dirname(__FILE__)) describe "The generated GObject module" do before do GirFFI.setup :GObject end describe "#type_interfaces" do it "works, showing that returning an array of GType works" do klass = GObject::TypeModule ifcs = GObject.type_interfaces klass.get_gtype assert_equal 1, ifcs.size end end describe "the TypePlugin interface" do it "is implemented as a module" do mod = GObject::TypePlugin assert_instance_of Module, mod refute_instance_of Class, mod end end describe "the TypeModule class" do it "has the GObject::TypePlugin module as an ancestor" do klass = GObject::TypeModule assert_includes klass.ancestors, GObject::TypePlugin end end end
Reduce minimum required OS version
Pod::Spec.new do |s| s.name = "UIImageView-Letters" s.version = "1.1.3" s.summary = "UIImageView category that generates letter initials as image." s.description = "An easy, helpful UIImageView category that generates letter initials as a placeholder for user profile images, with a randomized background color." s.homepage = "https://github.com/bachonk/UIImageView-Letters" s.screenshots = "http://i.imgur.com/xSBjVQ7.png" s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { "Tom Bachant" => "tom@dashride.com" } s.platform = :ios, '7.0' s.source = { :git => "https://github.com/bachonk/UIImageView-Letters.git", :tag => '1.1.3' } s.source_files = 'UIImageView+Letters' s.requires_arc = true end
Pod::Spec.new do |s| s.name = "UIImageView-Letters" s.version = "1.1.4" s.summary = "UIImageView category that generates letter initials as image." s.description = "An easy, helpful UIImageView category that generates letter initials as a placeholder for user profile images, with a randomized background color." s.homepage = "https://github.com/bachonk/UIImageView-Letters" s.screenshots = "http://i.imgur.com/xSBjVQ7.png" s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { "Tom Bachant" => "tom@dashride.com" } s.platform = :ios, '6.0' s.source = { :git => "https://github.com/bachonk/UIImageView-Letters.git", :tag => '1.1.4' } s.source_files = 'UIImageView+Letters' s.requires_arc = true end
Revert "concat should check the input if escape or not using SafeBuffer concat method"
# Overwrites helper methods in Action Pack to give them Rails XSS powers. These powers are there by default in Rails 3. module RailsXssHelper def link_to(*args, &block) if block_given? options = args.first || {} html_options = args.second concat(link_to(capture(&block), options, html_options)) else name = args.first options = args.second || {} html_options = args.third url = url_for(options) if html_options html_options = html_options.stringify_keys href = html_options['href'] convert_options_to_javascript!(html_options, url) tag_options = tag_options(html_options) else tag_options = nil end href_attr = "href=\"#{url}\"" unless href "<a #{href_attr}#{tag_options}>#{ERB::Util.h(name || url)}</a>".html_safe end end end ActionController::Base.helper(RailsXssHelper) module ActionView module Helpers module TextHelper def concat(string, unused_binding = nil) if unused_binding ActiveSupport::Deprecation.warn("The binding argument of #concat is no longer needed. Please remove it from your views and helpers.", caller) end output_buffer.concat(string) end end module TagHelper private def content_tag_string_with_escaping(name, content, options, escape = true) content_tag_string_without_escaping(name, ERB::Util.h(content), options, escape) end alias_method_chain :content_tag_string, :escaping end end end
# Overwrites helper methods in Action Pack to give them Rails XSS powers. These powers are there by default in Rails 3. module RailsXssHelper def link_to(*args, &block) if block_given? options = args.first || {} html_options = args.second concat(link_to(capture(&block), options, html_options)) else name = args.first options = args.second || {} html_options = args.third url = url_for(options) if html_options html_options = html_options.stringify_keys href = html_options['href'] convert_options_to_javascript!(html_options, url) tag_options = tag_options(html_options) else tag_options = nil end href_attr = "href=\"#{url}\"" unless href "<a #{href_attr}#{tag_options}>#{ERB::Util.h(name || url)}</a>".html_safe end end end ActionController::Base.helper(RailsXssHelper) module ActionView module Helpers module TagHelper private def content_tag_string_with_escaping(name, content, options, escape = true) content_tag_string_without_escaping(name, ERB::Util.h(content), options, escape) end alias_method_chain :content_tag_string, :escaping end end end
Make internals public so workflow can be hacked
module Yarrow class ScanSource < Process::StepProcessor accepts Config::Instance provides Content::Graph def step(config) Yarrow::Content::Graph.from_source(config) end end class ExpandCollections < Process::StepProcessor accepts Content::Graph provides Content::Graph def step(content) model = Content::Model.new(content.config.content) model.expand(content.graph) content end end class FlattenManifest < Process::StepProcessor accepts Content::Graph provides Web::Manifest def step(content) Web::Manifest.build(content.graph) end end # class BuildOutput < Process::StepProcessor # accepts Output::Manifest # provides Output::Result # end # Generates documentation from a model. class Generator def initialize(config) @config = config @workflow = Process::Workflow.new(config) end def process(&block) workflow.connect(ScanSource.new) workflow.connect(ExpandCollections.new) workflow.connect(FlattenManifest.new) workflow.process do |result| block.call(result) end end def generate process do |manifest| generators.each do |generator| generator.generate(manifest) end end end private attr_reader :config, :workflow def generators [Web::Generator.new(config)] end end end
module Yarrow class ScanSource < Process::StepProcessor accepts Config::Instance provides Content::Graph def step(config) Yarrow::Content::Graph.from_source(config) end end class ExpandCollections < Process::StepProcessor accepts Content::Graph provides Content::Graph def step(content) model = Content::Model.new(content.config.content) model.expand(content.graph) content end end class FlattenManifest < Process::StepProcessor accepts Content::Graph provides Web::Manifest def step(content) Web::Manifest.build(content.graph) end end # class BuildOutput < Process::StepProcessor # accepts Output::Manifest # provides Output::Result # end # Generates documentation from a model. class Generator def initialize(config) @config = config @workflow = Process::Workflow.new(config) end def process(&block) workflow.connect(ScanSource.new) workflow.connect(ExpandCollections.new) workflow.connect(FlattenManifest.new) workflow.process do |result| block.call(result) end end def generate process do |manifest| generators.each do |generator| generator.generate(manifest) end end end #private attr_reader :config, :workflow def generators [Web::Generator.new(config)] end end end
Allow using JsonFormatter from CLI via '-f json'
require 'thor' module Pronto class CLI < Thor require 'pronto' require 'pronto/version' desc 'exec', 'Run Pronto' method_option :commit, type: :string, default: nil, aliases: '-c', banner: 'Commit for the diff, defaults to master' method_option :runner, type: :array, default: [], aliases: '-r', banner: 'Run only the passed runners' def exec gem_names = options[:runner].any? ? options[:runner] : ::Pronto.gem_names gem_names.each do |gem_name| require "pronto/#{gem_name}" end puts ::Pronto.run(options[:commit]) rescue Rugged::RepositoryError puts '"pronto" should be run from a git repository' end desc 'list', 'Lists pronto runners that are available to be used' def list puts ::Pronto.gem_names end desc 'version', 'Show the Pronto version' map %w(-v --version) => :version def version puts "Pronto version #{::Pronto::VERSION}" end end end
require 'thor' module Pronto class CLI < Thor require 'pronto' require 'pronto/version' desc 'exec', 'Run Pronto' method_option :commit, type: :string, default: nil, aliases: '-c', banner: 'Commit for the diff, defaults to master' method_option :runner, type: :array, default: [], aliases: '-r', banner: 'Run only the passed runners' method_option :formatter, type: :string, default: nil, aliases: '-f', banner: 'Formatter, defaults to text. Available: text, json.' def exec gem_names = options[:runner].any? ? options[:runner] : ::Pronto.gem_names gem_names.each do |gem_name| require "pronto/#{gem_name}" end formatter = if options[:formatter] == 'json' ::Pronto::Formatter::JsonFormatter.new else ::Pronto::Formatter::TextFormatter.new end puts ::Pronto.run(options[:commit], '.', formatter) rescue Rugged::RepositoryError puts '"pronto" should be run from a git repository' end desc 'list', 'Lists pronto runners that are available to be used' def list puts ::Pronto.gem_names end desc 'version', 'Show the Pronto version' map %w(-v --version) => :version def version puts "Pronto version #{::Pronto::VERSION}" end end end
Remove versions from development dependencies
# encoding: utf-8 Gem::Specification.new do |gem| gem.name = 'memdash' gem.version = '0.0.1' gem.authors = ['Brian Ryckbost', 'Steve Richert'] gem.email = ['bryckbost@gmail.com', 'steve.richert@gmail.com'] gem.description = 'A dashboard for your memcache' gem.summary = 'A dashboard for your memcache' gem.homepage = 'https://github.com/bryckbost/memdash' gem.add_dependency 'activerecord', '~> 3.0' gem.add_dependency 'dalli', '~> 2.0' gem.add_development_dependency 'database_cleaner', '~> 0.7' gem.add_development_dependency 'rake', '>= 0.8.7' gem.add_development_dependency 'rspec', '~> 2.0' gem.add_development_dependency 'sqlite3' gem.files = `git ls-files`.split($\) gem.test_files = gem.files.grep(/^spec\//) gem.require_paths = ['lib'] end
# encoding: utf-8 Gem::Specification.new do |gem| gem.name = 'memdash' gem.version = '0.0.1' gem.authors = ['Brian Ryckbost', 'Steve Richert'] gem.email = ['bryckbost@gmail.com', 'steve.richert@gmail.com'] gem.description = 'A dashboard for your memcache' gem.summary = 'A dashboard for your memcache' gem.homepage = 'https://github.com/bryckbost/memdash' gem.add_dependency 'activerecord', '~> 3.0' gem.add_dependency 'dalli', '~> 2.0' gem.add_development_dependency 'database_cleaner' gem.add_development_dependency 'rake' gem.add_development_dependency 'rspec' gem.add_development_dependency 'sqlite3' gem.files = `git ls-files`.split($\) gem.test_files = gem.files.grep(/^spec\//) gem.require_paths = ['lib'] end
Make sure the message is right so the cucumber feature passes.
require "rubygems/command" class Gem::Commands::PrecompileCommand < Gem::Command def initialize super "precompile", "Create a bundle containing the compiled artifacts for this platform", :output => Dir.pwd, :arch => false add_option('-o PATH', '--output=PATH', 'The output directory for the generated bundle. Defaults to the current directory') do |path,options| options[:output] = path end add_option('-a','--arch-dirs','Adds the architecture sub-folders to the output directory before writing') do |arch, options| options[:arch] = true end end def arguments "GEMFILE path to the gem file to compile" end def usage "#{program_name} GEMFILE" end def execute gemfiles = options[:args] # no gem, no binary if gemfiles.empty? raise Gem::CommandLineError, "Please specify a gem file on the command line, e.g. #{program_name} foo-0.1.0.gem" end require "rubygems/precompiler" gemfiles.each do |gemfile| compiler = Gem::Precompiler.new(gemfile, options) if compiler.has_extension? $stderr.puts "Compiling '#{compiler.gem_name}'... " compiler.compile $stderr.puts "done." else $stderr.puts "The gem '#{compiler.gem_name}' doesn't contain a compiled extension" end end end end
require "rubygems/command" class Gem::Commands::PrecompileCommand < Gem::Command def initialize super "precompile", "Create a bundle containing the compiled artifacts for this platform", :output => Dir.pwd, :arch => false add_option('-o PATH', '--output=PATH', 'The output directory for the generated bundle. Defaults to the current directory') do |path,options| options[:output] = path end add_option('-a','--arch-dirs','Adds the architecture sub-folders to the output directory before writing') do |arch, options| options[:arch] = true end end def arguments "GEMFILE path to the gem file to compile" end def usage "#{program_name} GEMFILE" end def execute gemfiles = options[:args] # no gem, no binary if gemfiles.empty? raise Gem::CommandLineError, "Please specify a gem file on the command line, e.g. #{program_name} foo-0.1.0.gem" end require "rubygems/precompiler" gemfiles.each do |gemfile| compiler = Gem::Precompiler.new(gemfile, options) if compiler.has_extension? $stderr.write "Compiling '#{compiler.gem_name}'... " compiler.compile $stderr.puts "done." else $stderr.puts "The gem '#{compiler.gem_name}' doesn't contain a compiled extension" end end end end
Add proper error message to 404
module Fog module DNS class DNSimple class Real # Gets record from given domain. # # ==== Parameters # * domain<~String> # * record_id<~String> # ==== Returns # * response<~Excon::Response>: # * record<~Hash> # * name<~String> # * ttl<~Integer> # * created_at<~String> # * special_type<~String> # * updated_at<~String> # * domain_id<~Integer> # * id<~Integer> # * content<~String> # * record_type<~String> # * prio<~Integer> def get_record(domain, record_id) request( :expects => 200, :method => "GET", :path => "/domains/#{domain}/records/#{record_id}" ) end end class Mock def get_record(domain, record_id) response = Excon::Response.new if self.data[:records].has_key? domain response.status = 200 response.body = self.data[:records][domain].detect { |record| record["record"]["id"] == record_id } else response.status = 404 end response end end end end end
module Fog module DNS class DNSimple class Real # Gets record from given domain. # # ==== Parameters # * domain<~String> # * record_id<~String> # ==== Returns # * response<~Excon::Response>: # * record<~Hash> # * name<~String> # * ttl<~Integer> # * created_at<~String> # * special_type<~String> # * updated_at<~String> # * domain_id<~Integer> # * id<~Integer> # * content<~String> # * record_type<~String> # * prio<~Integer> def get_record(domain, record_id) request( :expects => 200, :method => "GET", :path => "/domains/#{domain}/records/#{record_id}" ) end end class Mock def get_record(domain, record_id) response = Excon::Response.new if self.data[:records].has_key? domain response.status = 200 response.body = self.data[:records][domain].detect { |record| record["record"]["id"] == record_id } else response.status = 404 response.body = { "error" => "Couldn't find Domain with name = #{domain}" } end response end end end end end
Fix slow request by converting to ms
module TransactionHelpers def transaction_with_exception appsignal_transaction.tap do |o| begin raise ArgumentError, 'oh no' rescue ArgumentError => exception env = {} o.add_exception( Appsignal::ExceptionNotification.new(env, exception) ) end end end def regular_transaction appsignal_transaction(:process_action_event => notification_event) end def slow_transaction(args={}) appsignal_transaction( { :process_action_event => notification_event( :start => Time.parse('01-01-2001 10:01:00'), :ending => Time.parse('01-01-2001 10:01:00') + 250.0 ) }.merge(args) ) end def appsignal_transaction(args = {}) process_action_event = args.delete(:process_action_event) events = args.delete(:events) || [ notification_event(:name => 'query.mongoid') ] exception = args.delete(:exception) Appsignal::Transaction.create( '1', { 'HTTP_USER_AGENT' => 'IE6', 'SERVER_NAME' => 'localhost', 'action_dispatch.routes' => 'not_available' }.merge(args) ).tap do |o| o.set_process_action_event(process_action_event) o.add_exception(exception) events.each { |event| o.add_event(event) } end end end
module TransactionHelpers def transaction_with_exception appsignal_transaction.tap do |o| begin raise ArgumentError, 'oh no' rescue ArgumentError => exception env = {} o.add_exception( Appsignal::ExceptionNotification.new(env, exception) ) end end end def regular_transaction appsignal_transaction(:process_action_event => notification_event) end def slow_transaction(args={}) appsignal_transaction( { :process_action_event => notification_event( :start => Time.parse('01-01-2001 10:01:00'), :ending => ( Time.parse('01-01-2001 10:01:00') + Appsignal.config[:slow_request_threshold] / 1000.0 ) ) }.merge(args) ) end def appsignal_transaction(args = {}) process_action_event = args.delete(:process_action_event) events = args.delete(:events) || [ notification_event(:name => 'query.mongoid') ] exception = args.delete(:exception) Appsignal::Transaction.create( '1', { 'HTTP_USER_AGENT' => 'IE6', 'SERVER_NAME' => 'localhost', 'action_dispatch.routes' => 'not_available' }.merge(args) ).tap do |o| o.set_process_action_event(process_action_event) o.add_exception(exception) events.each { |event| o.add_event(event) } end end end
Use narrow definition of files to include in gemspec
$:.push File.expand_path("../lib", __FILE__) require "high_voltage/version" Gem::Specification.new do |s| s.name = 'high_voltage' s.version = HighVoltage::VERSION.dup s.authors = ['Matt Jankowski', 'Dan Croak', 'Nick Quaranto', 'Chad Pytel', 'Joe Ferris', 'J. Edward Dewyea', 'Tammer Saleh', 'Mike Burns', 'Tristan Dunn'] s.email = ['support@thoughtbot.com'] s.homepage = 'http://github.com/thoughtbot/high_voltage' s.summary = 'Simple static page rendering controller' s.description = 'Fire in the disco. Fire in the ... taco bell.' s.license = 'MIT' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_paths = ["lib"] s.add_development_dependency('activesupport', '>= 3.1.0') s.add_development_dependency('appraisal') s.add_development_dependency('capybara') s.add_development_dependency('pry') s.add_development_dependency('rspec-rails', '~> 3.5') end
$:.push File.expand_path("../lib", __FILE__) require "high_voltage/version" Gem::Specification.new do |s| s.name = 'high_voltage' s.version = HighVoltage::VERSION.dup s.authors = ['Matt Jankowski', 'Dan Croak', 'Nick Quaranto', 'Chad Pytel', 'Joe Ferris', 'J. Edward Dewyea', 'Tammer Saleh', 'Mike Burns', 'Tristan Dunn'] s.email = ['support@thoughtbot.com'] s.homepage = 'http://github.com/thoughtbot/high_voltage' s.summary = 'Simple static page rendering controller' s.description = 'Fire in the disco. Fire in the ... taco bell.' s.license = 'MIT' s.files = `git ls-files -- {app,config,lib}/*`.split("\n") s.files += %w[ CHANGELOG.md CONTRIBUTING.md MIT-LICENSE README.md ] s.test_files = [] s.require_paths = ["lib"] s.add_development_dependency('activesupport', '>= 3.1.0') s.add_development_dependency('appraisal') s.add_development_dependency('capybara') s.add_development_dependency('pry') s.add_development_dependency('rspec-rails', '~> 3.5') end
Add specs for BEGIN/END behaviour with -n
describe "The -n command line option" do before :each do @names = fixture __FILE__, "names.txt" end it "runs the code in loop conditional on Kernel.gets()" do ruby_exe("puts $_", :options => "-n", :escape => true, :args => " < #{@names}").should == "alice\nbob\njames\n" end end
describe "The -n command line option" do before :each do @names = fixture __FILE__, "names.txt" end it "runs the code in loop conditional on Kernel.gets()" do ruby_exe("puts $_", :options => "-n", :escape => true, :args => " < #{@names}").should == "alice\nbob\njames\n" end it "only evaluates BEGIN blocks once" do ruby_exe("BEGIN { puts \"hi\" }; puts $_", :options => "-n", :escape => true, :args => " < #{@names}").should == "hi\nalice\nbob\njames\n" end it "only evaluates END blocks once" do ruby_exe("puts $_; END {puts \"bye\"}", :options => "-n", :escape => true, :args => " < #{@names}").should == "alice\nbob\njames\nbye\n" end it "allows summing over a whole file" do script = <<-script BEGIN { $total = 0 } $total += 1 END { puts $total } script ruby_exe(script, :options => "-n", :escape => true, :args => " < #{@names}").should == "3\n" end end
Add thread ID to api logs
module ApiLogging extend ActiveSupport::Concern API_LOGGER = ActiveSupport::TaggedLogging.new(Rails.logger) def api_log(record={}) tm = Time.now record.merge!(timestamp: tm.strftime('%F %T'), unix_time: tm.to_i) ::ApiLogging::API_LOGGER.tagged('api') { |l| l.info(record.to_json) } end end
module ApiLogging extend ActiveSupport::Concern API_LOGGER = ActiveSupport::TaggedLogging.new(Rails.logger) def api_log(record={}) tm = Time.now record.merge!( thread: Thread.current.object_id, timestamp: tm.strftime('%F %T'), unix_time: tm.to_i ) ::ApiLogging::API_LOGGER.tagged('api') { |l| l.info(record.to_json) } end end
Exclude data values for passed tests to trim test result storage size
module Crucible module Tests class TestResult attr_accessor :key attr_accessor :id attr_accessor :description attr_accessor :status attr_accessor :message attr_accessor :data attr_accessor :warnings attr_accessor :requires attr_accessor :validates attr_accessor :links attr_accessor :code def initialize(key, description, status, message, data) @key = key @status = status @description = description @message = message @data = data end def update(status, message, data) @status = status @message = message @data = data self end def passed? return ( (@status==true) or (@status=='passed') ) end def failed? !self.passed? end def to_hash hash = {} hash['key'] = @key hash['id'] = @id || @key hash['description'] = force_encoding(@description) hash['status'] = force_encoding(@status) if @message.class == Array hash['message'] = @message.map { |m| force_encoding(m) } else hash['message'] = force_encoding(@message) end hash['data'] = force_encoding(@data) hash['warnings'] = warnings if warnings hash['requires'] = requires if requires hash['validates'] = validates if validates hash['links'] = links if links hash['code'] = @code hash end private def force_encoding(value) return nil if value.blank? value.force_encoding("UTF-8") end end end end
module Crucible module Tests class TestResult attr_accessor :key attr_accessor :id attr_accessor :description attr_accessor :status attr_accessor :message attr_accessor :data attr_accessor :warnings attr_accessor :requires attr_accessor :validates attr_accessor :links attr_accessor :code def initialize(key, description, status, message, data) @key = key @status = status @description = description @message = message @data = data end def update(status, message, data) @status = status @message = message @data = data self end def passed? return ( (@status==true) or (@status=='passed') ) end def failed? !self.passed? end def to_hash hash = {} hash['key'] = @key hash['id'] = @id || @key hash['description'] = force_encoding(@description) hash['status'] = force_encoding(@status) if @message.class == Array hash['message'] = @message.map { |m| force_encoding(m) } else hash['message'] = force_encoding(@message) end hash['data'] = force_encoding(@data) unless hash['status'] == 'pass' hash['warnings'] = warnings if warnings hash['requires'] = requires if requires hash['validates'] = validates if validates hash['links'] = links if links hash['code'] = @code hash end private def force_encoding(value) return nil if value.blank? value.force_encoding("UTF-8") end end end end
Convert Haml::Template docs to YARD.
require 'haml/engine' module Haml module Template extend self @options = {} attr_accessor :options end end # Decide how we want to load Haml into Rails. # Patching was necessary for versions <= 2.0.1, # but we can make it a normal handler for higher versions. if defined?(ActionView::TemplateHandler) require 'haml/template/plugin' else require 'haml/template/patch' end if defined?(RAILS_ROOT) # Update init.rb to the current version # if it's out of date. # # We can probably remove this as of v1.9, # because the new init file is sufficiently flexible # to not need updating. rails_init_file = File.join(RAILS_ROOT, 'vendor', 'plugins', 'haml', 'init.rb') haml_init_file = Haml.scope('init.rb') begin if File.exists?(rails_init_file) require 'fileutils' FileUtils.cp(haml_init_file, rails_init_file) unless FileUtils.cmp(rails_init_file, haml_init_file) end rescue SystemCallError warn <<END HAML WARNING: #{rails_init_file} is out of date and couldn't be automatically updated. Please run `haml --rails #{File.expand_path(RAILS_ROOT)}' to update it. END end end
require 'haml/engine' module Haml # The class that keeps track of the global options for Haml within Rails. module Template extend self @options = {} # The options hash for Haml when used within Rails. # See [the Haml options documentation](../Haml.html#haml_options). # # @return [Hash<Symbol, Object>] attr_accessor :options end end # Decide how we want to load Haml into Rails. # Patching was necessary for versions <= 2.0.1, # but we can make it a normal handler for higher versions. if defined?(ActionView::TemplateHandler) require 'haml/template/plugin' else require 'haml/template/patch' end if defined?(RAILS_ROOT) # Update init.rb to the current version # if it's out of date. # # We can probably remove this as of v1.9, # because the new init file is sufficiently flexible # to not need updating. rails_init_file = File.join(RAILS_ROOT, 'vendor', 'plugins', 'haml', 'init.rb') haml_init_file = Haml.scope('init.rb') begin if File.exists?(rails_init_file) require 'fileutils' FileUtils.cp(haml_init_file, rails_init_file) unless FileUtils.cmp(rails_init_file, haml_init_file) end rescue SystemCallError warn <<END HAML WARNING: #{rails_init_file} is out of date and couldn't be automatically updated. Please run `haml --rails #{File.expand_path(RAILS_ROOT)}' to update it. END end end
Remove the duplicate homepage gemspec config
# coding: utf-8 lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "appbundle_updater/version" Gem::Specification.new do |spec| spec.name = "appbundle-updater" spec.version = AppbundleUpdater::VERSION spec.authors = ["lamont-granquist"] spec.email = ["lamont@chef.io"] spec.description = %q{Updates appbundled apps in Chef's omnibus packages} spec.summary = spec.description spec.homepage = "" spec.license = "Apache-2.0" spec.homepage = "https://github.com/chef/appbundle-updater" spec.files = `git ls-files`.split($/).select { |x| !x.match?(/^\./) } 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"] # This Gem DELIBERATELY has no dependencies other than the ruby stdlib end
# coding: utf-8 lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "appbundle_updater/version" Gem::Specification.new do |spec| spec.name = "appbundle-updater" spec.version = AppbundleUpdater::VERSION spec.authors = ["lamont-granquist"] spec.email = ["lamont@chef.io"] spec.description = %q{Updates appbundled apps in Chef's omnibus packages} spec.summary = spec.description spec.license = "Apache-2.0" spec.homepage = "https://github.com/chef/appbundle-updater" spec.files = `git ls-files`.split($/).select { |x| !x.match?(/^\./) } 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"] # This Gem DELIBERATELY has no dependencies other than the ruby stdlib end
Remove unused methods from PublicUploadsController
class PublicUploadsController < ApplicationController include ActionView::Helpers::AssetTagHelper def show asset_host = URI.parse(Plek.new.public_asset_host).host redirect_to host: asset_host end private def fail if image? upload_path redirect_to view_context.path_to_image('thumbnail-placeholder.png') elsif incoming_upload_exists? upload_path redirect_to_placeholder else render plain: "Not found", status: :not_found end end def redirect_to_placeholder # Cache is explicitly 1 minute to prevent the virus redirect beng # cached by CDNs. expires_in(1.minute, public: true) redirect_to placeholder_url end def send_file_for_mime_type if (mime_type = mime_type_for(upload_path)) send_file real_path_for_x_accel_mapping(upload_path), type: mime_type, disposition: 'inline' else send_file real_path_for_x_accel_mapping(upload_path), disposition: 'inline' end end def image?(path) ['.jpg', '.jpeg', '.png', '.gif'].include?(File.extname(path)) end def mime_type_for(path) Mime::Type.lookup_by_extension(File.extname(path).from(1).downcase) end def expires_headers expires_in(Whitehall.uploads_cache_max_age, public: true) end def upload_path basename = [params[:path], params[:format]].compact.join('.') File.join(Whitehall.clean_uploads_root, basename) end def attachment_visible? upload_exists? upload_path end def upload_exists?(path) File.exist?(path) && file_is_clean?(path) end def incoming_upload_exists?(path) path = path.sub(Whitehall.clean_uploads_root, Whitehall.incoming_uploads_root) File.exist?(path) end def file_is_clean?(path) path.starts_with?(Whitehall.clean_uploads_root) end def real_path_for_x_accel_mapping(potentially_symlinked_path) File.realpath(potentially_symlinked_path) end end
class PublicUploadsController < ApplicationController def show asset_host = URI.parse(Plek.new.public_asset_host).host redirect_to host: asset_host end end
Remove the frontend files from the linked dirs
# Set some Capistrano defaults set :linked_files, [] set :linked_files, %w(app/config/parameters.yml) set :linked_dirs, [] set :linked_dirs, %w(app/logs app/sessions src/Frontend/Files) # Run required tasks after the stage Capistrano::DSL.stages.each do |stage| after stage, 'forkcms:configure:composer' after stage, 'forkcms:configure:cachetool' end # Make sure the composer executable is installed namespace :deploy do after :starting, 'composer:install_executable' after :starting, 'cachetool:install_executable' after :publishing, 'forkcms:symlink:document_root' after :publishing, 'forkcms:opcache:reset' after :updated, 'forkcms:migrations:execute' before :reverted, 'forkcms:migrations:rollback' end # Load the tasks load File.expand_path('../../tasks/configure.rake', __FILE__) load File.expand_path('../../tasks/database.rake', __FILE__) load File.expand_path('../../tasks/maintenance.rake', __FILE__) load File.expand_path('../../tasks/migrations.rake', __FILE__) load File.expand_path('../../tasks/opcache.rake', __FILE__) load File.expand_path('../../tasks/symlink.rake', __FILE__)
# Set some Capistrano defaults set :linked_files, [] set :linked_files, %w(app/config/parameters.yml) set :linked_dirs, [] set :linked_dirs, %w(app/logs app/sessions) # Run required tasks after the stage Capistrano::DSL.stages.each do |stage| after stage, 'forkcms:configure:composer' after stage, 'forkcms:configure:cachetool' end # Make sure the composer executable is installed namespace :deploy do after :starting, 'composer:install_executable' after :starting, 'cachetool:install_executable' after :publishing, 'forkcms:symlink:document_root' after :publishing, 'forkcms:opcache:reset' after :updated, 'forkcms:migrations:execute' before :reverted, 'forkcms:migrations:rollback' end # Load the tasks load File.expand_path('../../tasks/configure.rake', __FILE__) load File.expand_path('../../tasks/database.rake', __FILE__) load File.expand_path('../../tasks/maintenance.rake', __FILE__) load File.expand_path('../../tasks/migrations.rake', __FILE__) load File.expand_path('../../tasks/opcache.rake', __FILE__) load File.expand_path('../../tasks/symlink.rake', __FILE__)
Return 1 if build fails
module Slinky class Builder def self.build options, config dir = options[:src_dir] || config.src_dir build_dir = options[:build_dir] || config.build_dir manifest = Manifest.new(dir, config, :build_to => build_dir, :devel => false, :no_minify => config.dont_minify || options[:no_minify]) begin manifest.build rescue SlinkyError => e e.messages.each{|m| $stderr.puts(m.foreground(:red)) } end end end end
module Slinky class Builder def self.build options, config dir = options[:src_dir] || config.src_dir build_dir = options[:build_dir] || config.build_dir manifest = Manifest.new(dir, config, :build_to => build_dir, :devel => false, :no_minify => config.dont_minify || options[:no_minify]) begin manifest.build rescue SlinkyError => e e.messages.each{|m| $stderr.puts(m.foreground(:red)) } exit 1 end end end end
Add a basic Winnow::Matcher that passes specs.
module Winnow class Matcher class << self def find_matches(fingerprints_a, fingerprints_b) values_a = value_to_fprint_map(fingerprints_a) values_b = value_to_fprint_map(fingerprints_b) shared_values = values_a.keys & values_b.keys shared_values.map do |value| matches_from_a = values_a[value] matches_from_b = values_b[value] MatchDatum.new(matches_from_a, matches_from_b) end end private def value_to_fprint_map(fingerprints) mapping = {} fingerprints.each do |fp| (mapping[fp.value] ||= []) << fp end mapping end end end end
Set the downloaded image as wallpaper
#!/usr/bin/env ruby require './downloader.rb' dl = Downloader.new dl.get_top_link
#!/usr/bin/env ruby require './downloader.rb' dl = Downloader.new filename = dl.get_top_link if filename.nil? puts "Error : could not download any wallpaper!" else `osascript set_wallpaper.scpt #{filename}` end
Add favorite serializer for ember data (id:name)
class FavoriteSerializer < ActiveModel::Serializer embed :ids, include: true attributes :id, :user_id, :item_id, :item_type, :fav_rank def user_id object.user.name end has_one :item, polymorphic: true end
Remove ancestry from dev gems(2)
$:.push File.expand_path('../lib', __FILE__) # Maintain your gem's version: require 'seo_cms/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = 'seo_cms' s.version = SeoCms::VERSION s.authors = ['Romain Vigo Benia'] s.email = ['romain@livementor.com'] s.homepage = 'http://www.livementor.com' s.summary = 'simple SEO static CMS.' s.description = 'simple SEO static CMS.' s.files = Dir['{app,config,db,lib}/**/*'] + ['MIT-LICENSE', 'Rakefile', 'README.md'] s.test_files = Dir['test/**/*'] s.add_runtime_dependency 'rails', '~> 3.2' s.add_runtime_dependency 'ancestry', '>= 0', '>= 0' s.add_development_dependency 'sqlite3' # s.add_development_dependency 'ancestry', '>= 0', '>= 0' spec.add_development_dependency 'bundler', '~> 1.7' spec.add_development_dependency 'rake', '~> 10.0' s.add_development_dependency 'test-unit' end
$:.push File.expand_path('../lib', __FILE__) # Maintain your gem's version: require 'seo_cms/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = 'seo_cms' s.version = SeoCms::VERSION s.authors = ['Romain Vigo Benia'] s.email = ['romain@livementor.com'] s.homepage = 'http://www.livementor.com' s.summary = 'simple SEO static CMS.' s.description = 'simple SEO static CMS.' s.files = Dir['{app,config,db,lib}/**/*'] + ['MIT-LICENSE', 'Rakefile', 'README.md'] s.test_files = Dir['test/**/*'] s.add_runtime_dependency 'rails', '~> 3.2' s.add_runtime_dependency 'ancestry', '>= 0', '>= 0' s.add_development_dependency 'sqlite3' # s.add_development_dependency 'ancestry', '>= 0', '>= 0' s.add_development_dependency 'bundler', '~> 1.7' s.add_development_dependency 'rake', '~> 10.0' s.add_development_dependency 'test-unit' end
Implement assigning attributes from file name in structure documents form.
module TaggableDocument extend ActiveSupport::Concern included do belongs_to :document_tag singleton_class.prepend ClassOverrides end attr_accessor :attributes_from_file_name attr_accessor :folder # returns boolean indicating whether or not update was successful def update_from_filename filename self.original_filename = filename self.valid? end module ClassOverrides def allowable_params Document::FORM_PARAMS + [:document_tag_id, :file_date] end end end
module TaggableDocument extend ActiveSupport::Concern included do belongs_to :document_tag singleton_class.prepend ClassOverrides end attr_accessor :attributes_from_file_name attr_accessor :folder # returns boolean indicating whether or not update was successful def update_from_filename filename self.original_filename = filename self.valid? end module ClassOverrides def allowable_params Document::FORM_PARAMS + [:document_tag_id, :file_date, :attributes_from_file_name] end end end
Add empty test outling plan for traffic-light testing
require_relative 'test_base' class TrafficLightTest < TestBase def self.hex_prefix '7B7' end # - - - - - - - - - - - - - - - - - test '9DA', %w( start-point files colour is red ) do # In order to properly test traffic-light-colour I will need # to generate new images with a modified # /usr/local/bin/red_amber_green.rb file # Plan to do this is # 0. get the manifest which includes image-name and start-point files. # 1. get the name of the image from the manifest # 2. open a tmp-dir # 3. save a modified red_amber_green.rb file # 4. save a new Dockerfile FROM the image # 5. Dockerfile will use COPY to overwrite red_amber_green.rb # 6. [docker build] to create a new image tagged with test id. end end
Make sure that rating value is a String
# frozen_string_literal: true require 'json' module RubyCritic module Turbulence def self.data(analysed_modules) analysed_modules.map do |analysed_module| { name: analysed_module.name, x: analysed_module.churn, y: analysed_module.complexity, rating: analysed_module.rating } end.to_json end end end
# frozen_string_literal: true require 'json' module RubyCritic module Turbulence def self.data(analysed_modules) analysed_modules.map do |analysed_module| { name: analysed_module.name, x: analysed_module.churn, y: analysed_module.complexity, rating: analysed_module.rating.to_s } end.to_json end end end
Add Cucumber and Aruba for testing.
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rock_candy/version' Gem::Specification.new do |spec| spec.name = 'rock_candy' spec.version = RockCandy::VERSION spec.authors = ['Scrappy Academy'] spec.description = %q{Provides sugary syntax to help crystalize your test/spec structure.} spec.summary = %q{Ruby test sugar add-on.} spec.homepage = 'https://github.com/ScrappyAcademy/rock_candy' 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' spec.add_development_dependency "coveralls" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rock_candy/version' Gem::Specification.new do |spec| spec.name = 'rock_candy' spec.version = RockCandy::VERSION spec.authors = ['Scrappy Academy'] spec.description = %q{Provides sugary syntax to help crystalize your test/spec structure.} spec.summary = %q{Ruby test sugar add-on.} spec.homepage = 'https://github.com/ScrappyAcademy/rock_candy' 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' spec.add_development_dependency 'cucumber', '~> 1.3.5' spec.add_development_dependency 'aruba', '~> 0.5.3' spec.add_development_dependency "coveralls" end
Update Zocalo references to WorkDocs inside the cask
cask :v1 => 'amazon-zocalo' do version :latest sha256 :no_check # cloudfront.net is the official download host per the vendor homepage url 'https://dpfrknqwmbop6.cloudfront.net/mac/Amazon%20Zocalo.pkg' name 'Amazon Zocalo' homepage 'http://aws.amazon.com/zocalo/' license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder pkg 'Amazon Zocalo.pkg' uninstall :pkgutil => 'com.amazon.aws.AmazonZocalo' end
cask :v1 => 'amazon-workdocs' do version :latest sha256 :no_check # cloudfront.net is the official download host per the vendor homepage url 'https://d28gdqadgmua23.cloudfront.net/mac/Amazon%20WorkDocs.pkg' name 'Amazon WorkDocs' homepage 'http://aws.amazon.com/workdocs/' license :gratis pkg 'Amazon WorkDocs.pkg' uninstall :pkgutil => 'com.amazon.aws.AmazonWorkDocs' end
Apply fix to migrate method
module Songkick module OAuth2 class Schema def self.migrate ActiveRecord::Base.logger ||= Logger.new(StringIO.new) if ActiveRecord.version.version >= '5.2' ActiveRecord::MigrationContext.new(migrations_path).up else ActiveRecord::Migrator.up(migrations_path) end end class << self alias :up :migrate end def self.rollback ActiveRecord::Base.logger ||= Logger.new(StringIO.new) if ActiveRecord.version.version >= '6.0' ActiveRecord::MigrationContext.new(migrations_path, ActiveRecord::Base.connection.schema_migration).down elsif ActiveRecord.version.version >= '5.2' ActiveRecord::MigrationContext.new(migrations_path).down else ActiveRecord::Migrator.down(migrations_path) end end class << self alias :down :rollback end def self.migrations_path File.expand_path('../schema', __FILE__) end end end end
module Songkick module OAuth2 class Schema def self.migrate ActiveRecord::Base.logger ||= Logger.new(StringIO.new) if ActiveRecord.version.version >= '6.0' ActiveRecord::MigrationContext.new(migrations_path, ActiveRecord::Base.connection.schema_migration).up elsif ActiveRecord.version.version >= '5.2' ActiveRecord::MigrationContext.new(migrations_path).up else ActiveRecord::Migrator.up(migrations_path) end end class << self alias :up :migrate end def self.rollback ActiveRecord::Base.logger ||= Logger.new(StringIO.new) if ActiveRecord.version.version >= '6.0' ActiveRecord::MigrationContext.new(migrations_path, ActiveRecord::Base.connection.schema_migration).down elsif ActiveRecord.version.version >= '5.2' ActiveRecord::MigrationContext.new(migrations_path).down else ActiveRecord::Migrator.down(migrations_path) end end class << self alias :down :rollback end def self.migrations_path File.expand_path('../schema', __FILE__) end end end end
Validate presence of create link
describe LabGroupsController do describe "join" do student = Factory.create(:student) gc = Factory.create(:given_course) lg = Factory.create(:lab_group, given_course: gc) src = Factory.create(:student_registered_for_course, given_course: gc, student: student) it "should be member of group" do login_as(student) post :join, role: "student", given_course: gc, lab_group: {id: lg.id} lg.student_registered_for_courses << src lg.student_registered_for_courses.exists?(src).should be_true end end describe "POST /create" do student = Factory.create(:student) gc = Factory.create(:given_course) it "success notice is being shown" do login_as(student) post :create, role: "student", course_id: gc flash[:notice].should == "Lab Group was successfully created" end end end
describe LabGroupsController do render_views describe "join" do student = Factory.create(:student) gc = Factory.create(:given_course) lg = Factory.create(:lab_group, given_course: gc) src = Factory.create(:student_registered_for_course, given_course: gc, student: student) it "should be member of group" do login_as(student) post :join, role: "student", given_course: gc, lab_group: {id: lg.id} lg.student_registered_for_courses << src lg.student_registered_for_courses.exists?(src).should be_true end end describe "POST /create" do student = Factory.create(:student) gc = Factory.create(:given_course) it "success notice is being shown" do login_as(student) post :create, role: "student", course_id: gc flash[:notice].should == "Lab Group was successfully created" end end describe "GET /new" do student = Factory.create(:student) gc = Factory.create(:given_course) it "should see a link to 'Create a Lab Group'" do login_as(student) visit new_course_lab_group_path("student", gc.id) page.should have_link('Create a Lab Group') end end end
Add integration tests for installation of mcrouter
require 'spec_helper' describe 'mcrouter::default' do # Serverspec examples can be found at # http://serverspec.org/resource_types.html it 'does something' do skip 'Replace this with meaningful tests' end end
require 'spec_helper' describe 'mcrouter::default' do context 'installs mcrouter to the $PATH' do describe command('which mcrouter') do its(:stdout) { is_expected.to match(%r{/usr/local/bin/mcrouter}) } end end end
Move config directory down a level
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # default['logstash']['package_url'] = 'https://logstash.objects.dreamhost.com/release/logstash-1.1.5-monolithic.jar' default['logstash']['user'] = 'logstash' default['logstash']['group'] = 'logstash' default['logstash']['authbind_enable'] = false default['logstash']['install_path'] = '/usr/local/logstash' default['logstash']['config_path'] = '/etc/logstash' default['logstash']['log_path'] = '/var/log/logstash' default['logstash']['tmp_path'] = '/usr/local/logstash/tmp' default['logstash']['xms'] = '1024M' default['logstash']['xmx'] = '1024M' default['logstash']['java_opts'] = '' default['logstash']['gc_opts'] = '-XX:+UseParallelOldGC'
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # default['logstash']['package_url'] = 'https://logstash.objects.dreamhost.com/release/logstash-1.1.5-monolithic.jar' default['logstash']['user'] = 'logstash' default['logstash']['group'] = 'logstash' default['logstash']['authbind_enable'] = false default['logstash']['install_path'] = '/usr/local/logstash' default['logstash']['config_path'] = '/etc/logstash/config' default['logstash']['log_path'] = '/var/log/logstash' default['logstash']['tmp_path'] = '/usr/local/logstash/tmp' default['logstash']['xms'] = '1024M' default['logstash']['xmx'] = '1024M' default['logstash']['java_opts'] = '' default['logstash']['gc_opts'] = '-XX:+UseParallelOldGC'
Use roda session middleware instead of rack session middleware in session spec on Ruby 2+
require_relative "spec_helper" describe "session handling" do include CookieJar it "should give a warning if session variable is not available" do app do |r| begin session rescue Exception => e e.message end end body.must_match("You're missing a session handler, try using the sessions plugin.") end it "should return session if rack session middleware is used" do app(:bare) do use Rack::Session::Cookie, :secret=>'1' route do |r| r.on do (session[1] ||= 'a'.dup) << 'b' session[1] end end end _, _, b = req b.join.must_equal 'ab' _, _, b = req b.join.must_equal 'abb' _, _, b = req b.join.must_equal 'abbb' end end
require_relative "spec_helper" describe "session handling" do include CookieJar it "should give a warning if session variable is not available" do app do |r| begin session rescue Exception => e e.message end end body.must_match("You're missing a session handler, try using the sessions plugin.") end it "should return session if session middleware is used" do require 'roda/session_middleware' app(:bare) do if RUBY_VERSION >= '2.0' require 'roda/session_middleware' use RodaSessionMiddleware, :secret=>'1'*64 else use Rack::Session::Cookie, :secret=>'1'*64 end route do |r| r.on do (session[1] ||= 'a'.dup) << 'b' session[1] end end end _, _, b = req b.join.must_equal 'ab' _, _, b = req b.join.must_equal 'abb' _, _, b = req b.join.must_equal 'abbb' end end
Add after sign up path
require_dependency "ajo_register/application_controller" class AjoRegister::PasswordsController < Devise::PasswordsController def new super end def create self.resource = resource_class.send_reset_password_instructions(resource_params) if successfully_sent?(resource) respond_with({}, :location => after_sending_reset_password_instructions_path_for(resource_name)) else redirect_to request.fullpath end end def destroy super end def edit super end def update super end end
require_dependency "ajo_register/application_controller" class AjoRegister::PasswordsController < Devise::PasswordsController def new super end def create self.resource = resource_class.send_reset_password_instructions(resource_params) if successfully_sent?(resource) respond_with({}, :location => after_sending_reset_password_instructions_path_for(resource_name)) else redirect_to :back end end def destroy super end def edit super end def update super end end
Add license information to the gemspec
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'ruby_installer' Gem::Specification.new do |spec| spec.name = "rubyinstaller" spec.version = RubyInstaller::GEM_VERSION spec.authors = ["Lars Kanis"] spec.email = ["lars@greiz-reinsdorf.de"] spec.summary = %q{MSYS2 based RubyInstaller for Windows} spec.description = %q{This project provides an Installer for Ruby on Windows based on the MSYS2 toolchain.} spec.homepage = "https://github.com/larskanis/rubyinstaller2" spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_runtime_dependency "rake", "~> 12.0" spec.add_development_dependency "rake", "~> 12.0" spec.add_development_dependency "bundler", "~> 1.14" spec.add_development_dependency "minitest", "~> 5.0" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'ruby_installer' Gem::Specification.new do |spec| spec.name = "rubyinstaller" spec.version = RubyInstaller::GEM_VERSION spec.authors = ["Lars Kanis"] spec.email = ["lars@greiz-reinsdorf.de"] spec.summary = %q{MSYS2 based RubyInstaller for Windows} spec.description = %q{This project provides an Installer for Ruby on Windows based on the MSYS2 toolchain.} spec.homepage = "https://github.com/larskanis/rubyinstaller2" spec.license = "BSD-3-Clause" spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_runtime_dependency "rake", "~> 12.0" spec.add_development_dependency "rake", "~> 12.0" spec.add_development_dependency "bundler", "~> 1.14" spec.add_development_dependency "minitest", "~> 5.0" end
Add spec for closing revert modal on escape keypress
require 'rails_helper' describe 'Merge request > User sees Revert modal', :js do let(:project) { create(:project, :public, :repository) } let(:user) { project.creator } let(:merge_request) { create(:merge_request, source_project: project) } before do sign_in(user) visit project_merge_request_path(project, merge_request) click_button('Merge') visit(merge_request_path(merge_request)) click_link('Revert') end it 'shows the revert modal' do expect(page).to have_content('Revert this merge request') end it 'closes the revert modal with escape keypress' do find('#modal-revert-commit').send_keys(:escape) expect(page).not_to have_content('Revert this merge request') end end
Add spec to test homepage
require 'spec_helper' describe 'homepage', :type => :feature do it "loads a page with the site's name" do visit '/' expect(page).to have_content 'No more ideas' end end
Fix wrong missing message for report in base distributor
module Knapsack module Distributors class BaseDistributor attr_reader :report, :node_specs, :spec_pattern def initialize(args={}) @report = args[:report] || raise('Missing report_path') @ci_node_total = args[:ci_node_total] || raise('Missing ci_node_total') @ci_node_index = args[:ci_node_index] || raise('Missing ci_node_index') @spec_pattern = args[:spec_pattern] || raise('Missing spec_pattern') end def ci_node_total @ci_node_total.to_i end def ci_node_index @ci_node_index.to_i end def specs_for_current_node specs_for_node(ci_node_index) end def specs_for_node(node_index) assign_spec_files_to_node post_specs_for_node(node_index) end def assign_spec_files_to_node default_node_specs post_assign_spec_files_to_node end def all_specs @all_specs ||= Dir[spec_pattern] end protected def post_specs_for_node(node_index) raise NotImplementedError end def post_assign_spec_files_to_node raise NotImplementedError end def default_node_specs raise NotImplementedError end end end end
module Knapsack module Distributors class BaseDistributor attr_reader :report, :node_specs, :spec_pattern def initialize(args={}) @report = args[:report] || raise('Missing report') @ci_node_total = args[:ci_node_total] || raise('Missing ci_node_total') @ci_node_index = args[:ci_node_index] || raise('Missing ci_node_index') @spec_pattern = args[:spec_pattern] || raise('Missing spec_pattern') end def ci_node_total @ci_node_total.to_i end def ci_node_index @ci_node_index.to_i end def specs_for_current_node specs_for_node(ci_node_index) end def specs_for_node(node_index) assign_spec_files_to_node post_specs_for_node(node_index) end def assign_spec_files_to_node default_node_specs post_assign_spec_files_to_node end def all_specs @all_specs ||= Dir[spec_pattern] end protected def post_specs_for_node(node_index) raise NotImplementedError end def post_assign_spec_files_to_node raise NotImplementedError end def default_node_specs raise NotImplementedError end end end end
Remove template ordering logic from Hexaflexagon
require "hexflex/side" require "hexflex/tape_template" require "hexflex/glue_template" require "hexflex/template_orderer" module Hexflex class Hexaflexagon attr_accessor :sides def initialize(side_fills) @raw_fills = side_fills @sides = Array.new(3) do |index| Side.new(fill: side_fills[index]) end end def as_template(template) case template when :glue GlueTemplate.new(self) when :tape TapeTemplate.new(sides) end end def triangles self.sides.map(&:triangles).flatten end def triangles_in_template_order TemplateOrderer.new(self).triangles end end end
require "hexflex/side" require "hexflex/tape_template" require "hexflex/glue_template" require "hexflex/template_orderer" module Hexflex class Hexaflexagon attr_accessor :sides def initialize(side_fills) @raw_fills = side_fills @sides = Array.new(3) do |index| Side.new(fill: side_fills[index]) end end def as_template(template) case template when :glue GlueTemplate.new(self) when :tape TapeTemplate.new(sides) end end def triangles self.sides.map(&:triangles).flatten end end end
Change wording of SpaceBeforeBrace message
module SCSSLint # Checks for the presence of a single space before an opening brace. class Linter::SpaceBeforeBrace < Linter include LinterRegistry def visit_root(node) engine.lines.each_with_index do |line, index| line.scan /[^"](?<![^ ] )\{/ do |match| @lints << Lint.new(engine.filename, index + 1, description) end end end def description 'Opening curly braces ({) must be preceded by one space' end end end
module SCSSLint # Checks for the presence of a single space before an opening brace. class Linter::SpaceBeforeBrace < Linter include LinterRegistry def visit_root(node) engine.lines.each_with_index do |line, index| line.scan /[^"](?<![^ ] )\{/ do |match| @lints << Lint.new(engine.filename, index + 1, description) end end end def description 'Opening curly braces ({) should be preceded by one space' end end end
Fix credentials regex for MongoMapper
module Sorcery module Model module Adapters module MongoMapper extend ActiveSupport::Concern included do include Sorcery::Model end def increment(attr) self.class.increment(id, attr => 1) end def save!(options = {}) save(options) end def sorcery_save(options = {}) mthd = options.delete(:raise_on_failure) ? :save! : :save self.send(mthd, options) end def update_many_attributes(attrs) update_attributes(attrs) end module ClassMethods def credential_regex(credential) return { :$regex => /^#{credential}$/i } if (@sorcery_config.downcase_username_before_authenticating) return credential end def find_by_credentials(credentials) @sorcery_config.username_attribute_names.each do |attribute| @user = where(attribute => credential_regex(credentials[0])).first break if @user end @user end def find_by_id(id) find(id) end def find_by_activation_token(token) where(sorcery_config.activation_token_attribute_name => token).first end def transaction(&blk) tap(&blk) end def find_by_sorcery_token(token_attr_name, token) where(token_attr_name => token).first end end end end end end
module Sorcery module Model module Adapters module MongoMapper extend ActiveSupport::Concern included do include Sorcery::Model end def increment(attr) self.class.increment(id, attr => 1) end def save!(options = {}) save(options) end def sorcery_save(options = {}) mthd = options.delete(:raise_on_failure) ? :save! : :save self.send(mthd, options) end def update_many_attributes(attrs) update_attributes(attrs) end module ClassMethods def credential_regex(credential) return { :$regex => /^#{Regexp.escape(credential)}$/i } if (@sorcery_config.downcase_username_before_authenticating) return credential end def find_by_credentials(credentials) @sorcery_config.username_attribute_names.each do |attribute| @user = where(attribute => credential_regex(credentials[0])).first break if @user end @user end def find_by_id(id) find(id) end def find_by_activation_token(token) where(sorcery_config.activation_token_attribute_name => token).first end def transaction(&blk) tap(&blk) end def find_by_sorcery_token(token_attr_name, token) where(token_attr_name => token).first end end end end end end
Update AppCode to version 3.1.7
cask :v1 => 'appcode' do version '3.1.6' sha256 'e172dae4027de31bd941f7e062e2a5fefaa56d1a2e0031a846a9ba57f8f1b911' url "http://download.jetbrains.com/objc/AppCode-#{version}.dmg" name 'AppCode' homepage 'http://www.jetbrains.com/objc/' license :commercial app 'AppCode.app' caveats <<-EOS.undent #{token} requires Java 6 like any other IntelliJ-based IDE. You can install it with brew cask install caskroom/homebrew-versions/java6 The vendor (JetBrains) doesn't support newer versions of Java (yet) due to several critical issues, see details at https://intellij-support.jetbrains.com/entries/27854363 To use existing newer Java at your own risk, add JVMVersion=1.6+ to ~/Library/Preferences/IntelliJIdea14/idea.properties EOS end
cask :v1 => 'appcode' do version '3.1.7' sha256 '07e044187062c183af49c67259fe8ea207a846476c21d105c2643779ac4b405c' url "http://download.jetbrains.com/objc/AppCode-#{version}.dmg" name 'AppCode' homepage 'http://www.jetbrains.com/objc/' license :commercial app 'AppCode.app' caveats <<-EOS.undent #{token} requires Java 6 like any other IntelliJ-based IDE. You can install it with brew cask install caskroom/homebrew-versions/java6 The vendor (JetBrains) doesn't support newer versions of Java (yet) due to several critical issues, see details at https://intellij-support.jetbrains.com/entries/27854363 To use existing newer Java at your own risk, add JVMVersion=1.6+ to ~/Library/Preferences/IntelliJIdea14/idea.properties EOS end
Add new test units for making sure we get complete responses
Shindo.tests('Excon Response Validation') do env_init with_server('good') do tests('good responses with complete headers') do 100.times do res = Excon.get('http://127.0.0.1:9292/chunked/simple') returns(true) { res.body == "hello world" } returns(true) { res.raw_status == "HTTP/1.1 200 OK\r\n" } returns(true) { res.status == 200} returns(true) { res.reason_phrase == "OK" } returns(true) { res.remote_ip == "127.0.0.1" } end end end with_server('error') do tests('error responses with complete headers') do 100.times do res = Excon.get('http://127.0.0.1:9292/error/not_found') returns(true) { res.body == "server says not found" } returns(true) { res.raw_status == "HTTP/1.1 404 Not Found\r\n" } returns(true) { res.status == 404} returns(true) { res.reason_phrase == "Not Found" } returns(true) { res.remote_ip == "127.0.0.1" } end end end env_restore end
Use the archive URL, since @github / @kneath deprecated Downloads.
require 'formula' class Chruby < Formula homepage 'https://github.com/postmodern/chruby#readme' url 'https://github.com/downloads/postmodern/chruby/chruby-0.2.4.tar.gz' sha1 'c89d4a4732d63515b1948a3d0dd0e3a2d4ed1057' head 'https://github.com/postmodern/chruby.git' def install system 'make', 'install', "PREFIX=#{prefix}" end def caveats; <<-EOS.undent For a system wide install, add the following to /etc/profile.d/chruby.sh. #!/bin/sh source #{HOMEBREW_PREFIX}/opt/chruby/share/chruby/chruby.sh RUBIES=(/opt/rubies/*) For a local install, add the following to ~/.bashrc or ~/.zshrc. #!/bin/sh source #{HOMEBREW_PREFIX}/opt/chruby/share/chruby/chruby.sh RUBIES=(~/.rubies/*) To use existing Rubies installed by RVM, rbenv or rbfu, set RUBIES to the following: RVM: RUBIES=(~/.rvm/rubies/*) rbenv: RUBIES=(~/.rbenv/versions/*) rbfu: RUBIES=('~/.rbfu/rubies/*) EOS end end
require 'formula' class Chruby < Formula homepage 'https://github.com/postmodern/chruby#readme' url 'https://github.com/postmodern/chruby/archive/v0.2.4.tar.gz' sha1 'c89d4a4732d63515b1948a3d0dd0e3a2d4ed1057' head 'https://github.com/postmodern/chruby.git' def install system 'make', 'install', "PREFIX=#{prefix}" end def caveats; <<-EOS.undent For a system wide install, add the following to /etc/profile.d/chruby.sh. #!/bin/sh source #{HOMEBREW_PREFIX}/opt/chruby/share/chruby/chruby.sh RUBIES=(/opt/rubies/*) For a local install, add the following to ~/.bashrc or ~/.zshrc. #!/bin/sh source #{HOMEBREW_PREFIX}/opt/chruby/share/chruby/chruby.sh RUBIES=(~/.rubies/*) To use existing Rubies installed by RVM, rbenv or rbfu, set RUBIES to the following: RVM: RUBIES=(~/.rvm/rubies/*) rbenv: RUBIES=(~/.rbenv/versions/*) rbfu: RUBIES=('~/.rbfu/rubies/*) EOS end end
Migrate authorizations controller to pundit
class Users::AuthorizationsController < ApplicationController load_and_authorize_resource inherit_resources belongs_to :user actions :destroy def destroy destroy! do |format| format.html { redirect_to edit_user_path(parent) } end end end
class Users::AuthorizationsController < ApplicationController inherit_resources belongs_to :user actions :destroy def destroy authorize resource destroy! do |format| format.html { redirect_to edit_user_path(parent) } end end end
Add unit tests for MigrationDumper.
require 'stringio' require 'helper' class MigrationDumperTest < TestCase def test_without_calls create_dumper assert_change <<-STR STR end def test_create_table_call create_dumper \ create_call(:create_table, "table", :force => true) { |t| t.string "uid", :limit => 32, :unique => true t.integer "amount" } assert_change <<-STR create_table "table", :force => true do |t| t.string "uid", :limit => 32, :unique => true t.integer "amount" end STR end def test_index_call create_dumper \ create_call(:add_index, "table", "uid", :unique => true), create_call(:add_index, "table", %w[composite index]) assert_change <<-STR add_index "table", "uid", :unique => true add_index "table", ["composite", "index"] STR end private def create_dumper(*calls) @dumper = Unschema::MigrationDumper.new("foo_bar", calls) end def create_call(name, *args, &block) Unschema::SchemaIntermediator::Call.new(name, *args, &block) end def assert_change(inner) expect = <<-STR class CreateFooBar < ActiveRecord::Migration def change STR unless inner.empty? expect << inner.unindent.indent(expect.indentation + 4) end expect << <<-STR end end STR assert_dump expect end def assert_dump(expect) io = StringIO.new @dumper.dump_to(io) assert_string io.string, expect end end
FIx the response parser to use Faraday's 'on_complete' handler.
require 'faraday' require 'json' require 'recursive-open-struct' require_relative '../response' module Smartsheet module API module Middleware class ResponseParser < Faraday::Middleware def initialize(app) super(app) end def call(env) response = @app.call(env) if env[:response_headers]['content-type'] =~ /\bjson\b/ hash_body = JSON.parse(env[:body]) env[:body] = RecursiveOpenStruct.new(hash_body, recurse_over_arrays: true) end env[:body] = Response.from_result env[:body] response end end end end end
require 'faraday' require 'json' require 'recursive-open-struct' require_relative '../response' module Smartsheet module API module Middleware class ResponseParser < Faraday::Middleware def initialize(app) super(app) end def call(env) @app.call(env).on_complete do |response_env| if response_env[:response_headers]['content-type'] =~ /\bjson\b/ hash_body = JSON.parse(response_env[:body]) response_env[:body] = RecursiveOpenStruct.new(hash_body, recurse_over_arrays: true) end response_env[:body] = Response.from_result response_env[:body] end end end end end end
Return LIMIT if everything else fails
module Travis::API::V3 class Services::Requests::Create < Service TIME_FRAME = 1.hour LIMIT = 10 private_constant :TIME_FRAME, :LIMIT result_type :request params "request", "user", :config, :message, :branch, :token def run raise LoginRequired unless access_control.logged_in? or access_control.full_access? raise NotFound unless repository = find(:repository) access_control.permissions(repository).create_request! user = find(:user) if access_control.full_access? and params_for? 'user'.freeze user ||= access_control.user remaining = remaining_requests(repository) raise RequestLimitReached, repository: repository if remaining == 0 payload = query.schedule(repository, user) accepted(remaining_requests: remaining, repository: repository, request: payload) end def limit(repository) if repository.settings.nil? Travis.config.requests_create_api_limit || 50 else repository.settings["api_builds_rate_limit"] || Travis.config.requests_create_api_limit || 50 end end def remaining_requests(repository) api_builds_rate_limit = limit(repository) return api_builds_rate_limit if access_control.full_access? count = query(:requests).count(repository, TIME_FRAME) count > api_builds_rate_limit ? 0 : api_builds_rate_limit - count end end end
module Travis::API::V3 class Services::Requests::Create < Service TIME_FRAME = 1.hour LIMIT = 10 private_constant :TIME_FRAME, :LIMIT result_type :request params "request", "user", :config, :message, :branch, :token def run raise LoginRequired unless access_control.logged_in? or access_control.full_access? raise NotFound unless repository = find(:repository) access_control.permissions(repository).create_request! user = find(:user) if access_control.full_access? and params_for? 'user'.freeze user ||= access_control.user remaining = remaining_requests(repository) raise RequestLimitReached, repository: repository if remaining == 0 payload = query.schedule(repository, user) accepted(remaining_requests: remaining, repository: repository, request: payload) end def limit(repository) if repository.settings.nil? Travis.config.requests_create_api_limit || LIMIT else repository.settings["api_builds_rate_limit"] || Travis.config.requests_create_api_limit || LIMIT end end def remaining_requests(repository) api_builds_rate_limit = limit(repository) return api_builds_rate_limit if access_control.full_access? count = query(:requests).count(repository, TIME_FRAME) count > api_builds_rate_limit ? 0 : api_builds_rate_limit - count end end end