Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Update AppCode EAP to build 141.2000
cask :v1 => 'appcode-eap' do version '141.1399.2' sha256 '2dd8a0a9246067ae6e092b9934cbadac6730a74fe400c8929b09792a0c0cda83' url "https://download.jetbrains.com/objc/AppCode-#{version}.dmg" name 'AppCode' homepage 'https://confluence.jetbrains.com/display/OBJC/AppCode+EAP' license :commercial app 'AppCode EAP.app' zap :delete => [ '~/Library/Preferences/com.jetbrains.AppCode-EAP.plist', '~/Library/Preferences/AppCode32', '~/Library/Application Support/AppCode32', '~/Library/Caches/AppCode32', '~/Library/Logs/AppCode32', ] conflicts_with :cask => 'appcode-eap-bundled-jdk' 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 EOS end
cask :v1 => 'appcode-eap' do version '141.2000.4' sha256 '964a077f89c3317116aeb566d398c96754f3eb06474f3c7039974f38197123ac' url "https://download.jetbrains.com/objc/AppCode-#{version}.dmg" name 'AppCode' homepage 'https://confluence.jetbrains.com/display/OBJC/AppCode+EAP' license :commercial app 'AppCode EAP.app' zap :delete => [ '~/Library/Preferences/com.jetbrains.AppCode-EAP.plist', '~/Library/Preferences/AppCode32', '~/Library/Application Support/AppCode32', '~/Library/Caches/AppCode32', '~/Library/Logs/AppCode32', ] conflicts_with :cask => 'appcode-eap-bundled-jdk' 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 EOS end
Update publication queue status on acceptance of first eid
module Actions class UpdateEvidenceItemStatus include Actions::Transactional attr_reader :evidence_item, :originating_user, :new_status def initialize(evidence_item, originating_user, new_status) @evidence_item = evidence_item @originating_user = originating_user @new_status = new_status end private def execute evidence_item.lock! if evidence_item.status != new_status evidence_item.status = new_status evidence_item.save! Event.create( action: new_status, originating_user: originating_user, subject: evidence_item ) evidence_item.subscribe_user(originating_user) else errors << "Attempted to update to status #{new_status} but it was already completed" end end end end
module Actions class UpdateEvidenceItemStatus include Actions::Transactional attr_reader :evidence_item, :originating_user, :new_status def initialize(evidence_item, originating_user, new_status) @evidence_item = evidence_item @originating_user = originating_user @new_status = new_status end private def execute evidence_item.lock! if evidence_item.status != new_status update_source_status evidence_item.status = new_status evidence_item.save! Event.create( action: new_status, originating_user: originating_user, subject: evidence_item ) evidence_item.subscribe_user(originating_user) else errors << "Attempted to update to status #{new_status} but it was already completed" end end def update_source_status conditions = [ new_status == 'accepted', evidence_item_count_for_source == 0, evidence_item.source.status == 'submitted' ] if conditions.all? evidence_item.source.status = 'partially curated' evidence_item.source.save end end def evidence_item_count_for_source evidence_item.source.evidence_items.where(status: 'accepted').count end end end
Handle exception differencies between 1.8 and 1.9
shared_examples_for 'a #freeze method' do it_should_behave_like 'an idempotent method' it 'returns object' do should be(object) end it 'prevents future modifications' do subject expect { object.instance_variable_set(:@foo,:bar) }.to raise_error(RuntimeError,"can't modify frozen #{object.class.inspect}") end its(:frozen?) { should be(true) } it 'allows to access attribute' do subject.name.should eql('John') end end
shared_examples_for 'a #freeze method' do let(:sample_exception) do begin object.dup.freeze.instance_variable_set(:@foo,:bar) rescue => exception exception end end let(:expected_exception_class) do # Ruby 1.8 blows up with TypeError Ruby 1.9 with RuntimeError sample_exception.class end let(:expected_exception_message) do # Ruby 1.8 blows up with a different message than Ruby 1.9 sample_exception.message end it_should_behave_like 'an idempotent method' it 'returns object' do should be(object) end it 'prevents future modifications' do subject expectation = raise_error(expected_exception_class,expected_exception_message) expect { object.instance_variable_set(:@foo,:bar) }.to(expectation) end its(:frozen?) { should be(true) } it 'allows to access attribute' do subject.name.should eql('John') end end
Add tests for mandatory field helpers
require "spec_helper" RSpec.describe MandatoryFieldHelper, type: :helper do context "#validate_mandatory_text_fields" do it "returns an array of mandatory text field not populated" do session["full_name"] = "" session["job_title"] = "text" invalid_fields = validate_mandatory_text_fields(%w[full_name job_title], "contact_information") expect(invalid_fields).to eq [{ text: "Enter Full name" }] end end context "#validate_date_fields" do it "returns an error if year is blank" do invalid_fields = validate_date_fields("", "6", "25", "Date") expect(invalid_fields).to eq [{ text: "Date must include a year" }] end it "returns an error if month is blank" do invalid_fields = validate_date_fields("1990", "", "25", "Date") expect(invalid_fields).to eq [{ text: "Date must include a month" }] end it "returns an error if day is blank" do invalid_fields = validate_date_fields("1990", "6", "", "Date") expect(invalid_fields).to eq [{ text: "Date must include a day" }] end it "returns multiple errors if multiple date fields are blank" do invalid_fields = validate_date_fields("", "", "", "Date") expect(invalid_fields).to eq [ { text: "Date must include a year" }, { text: "Date must include a month" }, { text: "Date must include a day" }, ] end it "returns an error if date is not valid" do invalid_fields = validate_date_fields("2019", "02", "30", "Date") expect(invalid_fields).to eq [{ text: "Enter a real Date" }] end end context "#validate_radio_field" do it "return an error if no radio button selected" do invalid_fields = validate_radio_field("organisation_type", radio: "", other: "") expect(invalid_fields).to eq [{ text: "Select Organisation type" }] end it "returns an error when Other selected but no custom text entered" do invalid_fields = validate_radio_field("organisation_type", radio: "Other", other: "") expect(invalid_fields).to eq [{ text: "Enter Organisation type" }] end end end
Fix AMQP argument error in integration tests
require 'spec_helper' require 'rabbitmq/http/client' describe GovukSeedCrawler do let(:options) {{ :exchange => "govuk_seed_crawler_integration", :topic => "#", :site_root => "https://www.gov.uk/", }} let(:amqp_vhost) { "/" } let(:rabbitmq_mgmt_client) { RabbitMQ::HTTP::Client.new("http://guest:guest@127.0.0.1:15672") } let(:probable_min_number_of_urls) { 1000 } subject { GovukSeedCrawler::Seeder::seed(options) } before(:each) do rabbitmq_mgmt_client.declare_exchange(amqp_vhost, options[:exchange], { :type => "topic" }) end after(:each) do rabbitmq_mgmt_client.delete_exchange(amqp_vhost, options[:exchange]) end it "publishes URLs it finds to an AMQP topic exchange" do subject sleep(1) # give the management API time to recognise the messages we've just published exchange_info = rabbitmq_mgmt_client.exchange_info(amqp_vhost, options[:exchange]) number_of_messages_on_exchange = exchange_info["message_stats"]["publish_in"] expect(number_of_messages_on_exchange).to be > probable_min_number_of_urls end end
require 'spec_helper' require 'rabbitmq/http/client' describe GovukSeedCrawler do let(:options) {{ :amqp_exchange => "govuk_seed_crawler_integration", :amqp_topic => "#", :site_root => "https://www.gov.uk/", }} let(:amqp_vhost) { "/" } let(:rabbitmq_mgmt_client) { RabbitMQ::HTTP::Client.new("http://guest:guest@127.0.0.1:15672") } let(:probable_min_number_of_urls) { 1000 } subject { GovukSeedCrawler::Seeder::seed(options) } before(:each) do rabbitmq_mgmt_client.declare_exchange(amqp_vhost, options[:amqp_exchange], { :type => "topic" }) end after(:each) do rabbitmq_mgmt_client.delete_exchange(amqp_vhost, options[:amqp_exchange]) end it "publishes URLs it finds to an AMQP topic exchange" do subject sleep(1) # give the management API time to recognise the messages we've just published exchange_info = rabbitmq_mgmt_client.exchange_info(amqp_vhost, options[:amqp_exchange]) number_of_messages_on_exchange = exchange_info["message_stats"]["publish_in"] expect(number_of_messages_on_exchange).to be > probable_min_number_of_urls end end
Fix 2v2 max rating data source.
module Audit class PvPData def self.add(character, data) character.data['honor_level'] = character.details["honor_level"] || "-" character.data['honorable_kills'] = data['totalHonorableKills'] ['2v2','3v3','RBG'].each do |bracket| character.data["#{bracket}_rating"] = data['pvp']['brackets']["ARENA_BRACKET_#{bracket}"]['rating'] character.data["#{bracket}_season_played"] = data['pvp']['brackets']["ARENA_BRACKET_#{bracket}"]['seasonPlayed'] character.data["#{bracket}_week_played"] = data['pvp']['brackets']["ARENA_BRACKET_#{bracket}"]['weeklyPlayed'] end character.data['max_2v2_rating'] = data['statistics']['subCategories'][9]['subCategories'][0]['statistics'][25]['quantity'] character.data['max_3v3_rating'] = data['statistics']['subCategories'][9]['subCategories'][0]['statistics'][24]['quantity'] end end end
module Audit class PvPData def self.add(character, data) character.data['honor_level'] = character.details["honor_level"] || "-" character.data['honorable_kills'] = data['totalHonorableKills'] ['2v2','3v3','RBG'].each do |bracket| character.data["#{bracket}_rating"] = data['pvp']['brackets']["ARENA_BRACKET_#{bracket}"]['rating'] character.data["#{bracket}_season_played"] = data['pvp']['brackets']["ARENA_BRACKET_#{bracket}"]['seasonPlayed'] character.data["#{bracket}_week_played"] = data['pvp']['brackets']["ARENA_BRACKET_#{bracket}"]['weeklyPlayed'] end character.data['max_2v2_rating'] = data['statistics']['subCategories'][9]['subCategories'][0]['statistics'][24]['quantity'] character.data['max_3v3_rating'] = data['statistics']['subCategories'][9]['subCategories'][0]['statistics'][23]['quantity'] end end end
Use `attributes_for` to generate test data
require "spec_helper" describe "Contact creation", auth: :user do include Admin::ContactSteps let!(:contact_group) { create(:contact_group, :with_organisation, title: "new contact type") } let(:contact) { build :contact } let!(:contact_organisation) { create :organisation } before { verify !contact_exists(contact) } specify "it can be created" do expect { create_contact( title: contact.title, description: contact.description, contact_information: contact.contact_information ) do select contact_organisation, from: "contact_organisation_id" select contact_group, from: "contact_contact_group_ids" end }.to change { Contact.count }.by(1) end end
require "spec_helper" describe "Contact creation", auth: :user do include Admin::ContactSteps let!(:contact_group) { create(:contact_group, :with_organisation, title: "new contact type") } let(:contact) { attributes_for :contact } let!(:contact_organisation) { create :organisation } before { verify !contact_exists(contact) } specify "it can be created" do expect { create_contact( title: contact[:title], description: contact[:description], contact_information: contact[:contact_information] ) do select contact_organisation, from: "contact_organisation_id" select contact_group, from: "contact_contact_group_ids" end }.to change { Contact.count }.by(1) end end
Make the hovercards cuke more reliable
When(/^I activate the first hovercard$/) do first('.hovercardable').hover end Then(/^I should see a hovercard$/) do page.should have_css('#hovercard', visible: true) end When(/^I deactivate the first hovercard$/) do page.execute_script("$('.hovercardable').first().trigger('mouseleave');") end Then(/^I should not see a hovercard$/) do page.should_not have_css('#hovercard', visible: true) end When (/^I hover "([^"]*)" within "([^"]*)"$/) do |name, selector| with_scope(selector) do find(".author", text: name).hover end end
When(/^I activate the first hovercard$/) do page.execute_script("$('.hovercardable').first().trigger('mouseenter');") end Then(/^I should see a hovercard$/) do page.should have_css('#hovercard', visible: true) end When(/^I deactivate the first hovercard$/) do page.execute_script("$('.hovercardable').first().trigger('mouseleave');") end Then(/^I should not see a hovercard$/) do page.should_not have_css('#hovercard', visible: true) end When (/^I hover "([^"]*)" within "([^"]*)"$/) do |name, selector| with_scope(selector) do find(".author", text: name).hover end end
Allow overwriting logger and config
module Appsignal class AuthCheck ACTION = 'auth'.freeze attr_reader :config attr_accessor :transmitter delegate :uri, :to => :transmitter def initialize(environment) @config = Appsignal::Config.new(Rails.root, environment).load end def perform self.transmitter = Appsignal::Transmitter.new( @config[:endpoint], ACTION, @config[:api_key] ) transmitter.transmit({}) end end end
module Appsignal class AuthCheck ACTION = 'auth'.freeze attr_reader :environment, :logger attr_accessor :transmitter delegate :uri, :to => :transmitter def initialize(*args) @environment = args.shift options = args.empty? ? {} : args.last @config = options[:config] @logger = options[:logger] end def config @config ||= Appsignal::Config.new(Rails.root, environment, logger).load end def perform self.transmitter = Appsignal::Transmitter.new( config[:endpoint], ACTION, config[:api_key] ) transmitter.transmit({}) end end end
Update Erlang documentation (19.0, 18.3)
module Docs class Erlang < FileScraper self.type = 'erlang' self.root_path = 'doc/index.html' self.links = { home: 'https://www.erlang.org/', code: 'https://github.com/erlang/otp' } html_filters.insert_after 'container', 'erlang/pre_clean_html' html_filters.push 'erlang/entries', 'erlang/clean_html' options[:only_patterns] = [/\Alib/] options[:skip_patterns] = [ /pdf/, /release_notes/, /result/, /java/, /\/html\/.*_app\.html\z/, /_examples\.html\z/, /\Alib\/edoc/, /\Alib\/erl_docgen/, /\Alib\/hipe/, /\Alib\/ose/, /\Alib\/test_server/, /\Alib\/jinterface/, /\Alib\/wx/, /\Alib\/ic/, /\Alib\/Cos/i ] options[:attribution] = <<-HTML &copy; 1999&ndash;2016 Ericsson AB<br> Licensed under the Apache License, Version 2.0. HTML version '18' do self.release = '18.3' self.dir = '/Users/Thibaut/DevDocs/Docs/Erlang18' end end end
module Docs class Erlang < FileScraper self.type = 'erlang' self.root_path = 'doc/index.html' self.links = { home: 'https://www.erlang.org/', code: 'https://github.com/erlang/otp' } html_filters.insert_after 'container', 'erlang/pre_clean_html' html_filters.push 'erlang/entries', 'erlang/clean_html' options[:only_patterns] = [/\Alib/] options[:skip_patterns] = [ /pdf/, /release_notes/, /result/, /java/, /\/html\/.*_app\.html\z/, /_examples\.html\z/, /\Alib\/edoc/, /\Alib\/erl_docgen/, /\Alib\/hipe/, /\Alib\/ose/, /\Alib\/test_server/, /\Alib\/jinterface/, /\Alib\/wx/, /\Alib\/ic/, /\Alib\/Cos/i ] options[:attribution] = <<-HTML &copy; 1999&ndash;2016 Ericsson AB<br> Licensed under the Apache License, Version 2.0. HTML version '19' do self.release = '19.0' self.dir = '/Users/Thibaut/DevDocs/Docs/Erlang19' end version '18' do self.release = '18.3' self.dir = '/Users/Thibaut/DevDocs/Docs/Erlang18' end end end
Allow passing in of arguments
module Peek module Views class Host < View # Returns Peek::Views::Host def initialize @hostname = hostname end def hostname `hostname` end end end end
module Peek module Views class Host < View # Returns Peek::Views::Host def initialize(options = {}) @hostname = hostname end def hostname `hostname` end end end end
Add the necessary modular gems as *runtime* dependencies
#-*- mode: ruby -*- require File.expand_path( '../lib/leafy/rack/version', __FILE__ ) Gem::Specification.new do |s| s.name = 'leafy-rack' s.version = Leafy::Rack::VERSION s.author = 'christian meier' s.email = [ 'christian.meier@lookout.com' ] s.license = 'MIT' s.summary = %q(rack middleware to expose leafy metrics/health data and more) s.homepage = 'https://github.com/lookout/leafy' s.description = %q(rack middleware to expose leafy metrics/health data as well a ping rack and a thread-dump rack) s.files = `git ls-files`.split($/) s.requirements << 'jar io.dropwizard.metrics:metrics-json, 3.1.0' s.requirements << 'jar io.dropwizard.metrics:metrics-jvm, 3.1.0' s.add_runtime_dependency 'jar-dependencies', '~> 0.1.8' s.add_development_dependency 'rspec', '~> 3.1.0' s.add_development_dependency 'yard', '~> 0.8.7' s.add_development_dependency 'rake', '~> 10.2' s.add_development_dependency 'leafy-metrics', '~> 0.1.0' s.add_development_dependency 'leafy-health', '~> 0.1.0' end # vim: syntax=Ruby
#-*- mode: ruby -*- require File.expand_path( '../lib/leafy/rack/version', __FILE__ ) Gem::Specification.new do |s| s.name = 'leafy-rack' s.version = Leafy::Rack::VERSION s.author = 'christian meier' s.email = [ 'christian.meier@lookout.com' ] s.license = 'MIT' s.summary = %q(rack middleware to expose leafy metrics/health data and more) s.homepage = 'https://github.com/lookout/leafy' s.description = %q(rack middleware to expose leafy metrics/health data as well a ping rack and a thread-dump rack) s.files = `git ls-files`.split($/) s.requirements << 'jar io.dropwizard.metrics:metrics-json, 3.1.0' s.requirements << 'jar io.dropwizard.metrics:metrics-jvm, 3.1.0' s.add_runtime_dependency 'jar-dependencies', '~> 0.1.8' s.add_runtime_dependency 'leafy-metrics', '~> 0.1.0' s.add_runtime_dependency 'leafy-health', '~> 0.1.0' s.add_development_dependency 'rspec', '~> 3.1.0' s.add_development_dependency 'yard', '~> 0.8.7' s.add_development_dependency 'rake', '~> 10.2' end # vim: syntax=Ruby
Add unique index to posts_tags to boost join performace.
class AddUniqueIndexToPostsTag < ActiveRecord::Migration def self.up add_index :posts_tags, [:post_id, :tag_id], :unique => true end def self.down remove_index :posts_tags, :column => [:post_id, :tag_id] end end
Update 'Completed' message. Colorize status code
require 'action_controller/log_subscriber' require 'colorize' require 'awesome_print' class ActionController::LogSubscriber def start_processing(event) return unless logger.info? payload = event.payload params = payload[:params].except(*INTERNAL_PARAMS) format = payload[:format] format = format.to_s.upcase if format.is_a?(Symbol) #TODO try centering again, remember that colorize adds chars info "#{payload[:action]}".upcase.colorize(:red) + " #{payload[:controller]}".colorize(:red) unless params.empty? info " Params: ".colorize(:blue) ap params end end end
require 'action_controller/log_subscriber' require 'colorize' require 'awesome_print' class ActionController::LogSubscriber def start_processing(event) return unless logger.info? payload = event.payload params = payload[:params].except(*INTERNAL_PARAMS) format = payload[:format] format = format.to_s.upcase if format.is_a?(Symbol) #TODO try centering again, remember that colorize adds chars info "#{payload[:action]}".upcase.colorize(:red) + " #{payload[:controller]}".colorize(:red) unless params.empty? info " Params: ".colorize(:blue) ap params end end def process_action(event) return unless logger.info? payload = event.payload additions = ActionController::Base.log_process_action(payload) status = payload[:status] if status.nil? && payload[:exception].present? exception_class_name = payload[:exception].first status = ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name) end message = format_message(status) info(message) end def format_message(status) if status < 300 status.to_s.colorize(:green) elsif status < 400 status.to_s.colorize(:yellow) elsif status < 500 status.to_s.colorize(:red) elsif status < 600 status.to_s.colorize(:light_red) else status end end end
Use the expected class name...
require 'test_helper' class ProgrammeTest < ActiveSupport::TestCase def template_programme g = Programme.new(:slug=>"childcare", :name=>"Something") edition = g.editions.first edition.title = 'One' g end test "order parts shouldn't fail if one part's order attribute is nil" do g = template_programme edition = g.editions.first edition.parts.build edition.parts.build(:order => 1) assert edition.order_parts end end
require 'test_helper' class ProgrammeEditionTest < ActiveSupport::TestCase def template_programme g = Programme.new(:slug=>"childcare", :name=>"Something") edition = g.editions.first edition.title = 'One' g end test "order parts shouldn't fail if one part's order attribute is nil" do g = template_programme edition = g.editions.first edition.parts.build edition.parts.build(:order => 1) assert edition.order_parts end end
Update for compatibility with ruby 3.0
# coding: utf-8 lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "slugworth/version" Gem::Specification.new do |spec| spec.name = "slugworth" spec.version = Slugworth::VERSION spec.authors = ["Matt Polito"] spec.email = ["matt.polito@gmail.com"] spec.description = %q{Easy slug functionality} spec.summary = %q{Easy slug functionality} spec.homepage = "https://github.com/mattpolito/slugworth" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.required_ruby_version = ">= 1.9.2" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" spec.add_development_dependency "rspec", "~> 3.3" spec.add_development_dependency "activerecord", "~> 4.0.0" spec.add_development_dependency "pry" spec.add_development_dependency "database_cleaner", "~> 1.0.1" spec.add_development_dependency "sqlite3" end
# coding: utf-8 lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "slugworth/version" Gem::Specification.new do |spec| spec.name = "slugworth" spec.version = Slugworth::VERSION spec.authors = ["Matt Polito"] spec.email = ["matt.polito@gmail.com"] spec.description = %q{Easy slug functionality} spec.summary = %q{Easy slug functionality} spec.homepage = "https://github.com/mattpolito/slugworth" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.required_ruby_version = ">= 2.6" spec.add_development_dependency "rake" spec.add_development_dependency "rspec", "~> 3.0" spec.add_development_dependency "activerecord", ">= 4.0" spec.add_development_dependency "pry" spec.add_development_dependency "database_cleaner", "~> 1.0" spec.add_development_dependency "sqlite3" end
Add dir_config to allow user customization of paths.
require 'mkmf' have_library( 'htp', 'htp_connp_create' ) || abort( "Can't find HTP library." ) have_header( 'htp/htp.h' ) || abort( "Can't find htp.h" ) create_makefile( 'htp' )
require 'mkmf' dir_config( 'htp' ) have_library( 'htp', 'htp_connp_create' ) || abort( "Can't find HTP library." ) have_header( 'htp/htp.h' ) || abort( "Can't find htp.h" ) create_makefile( 'htp' )
Add model auth_config from spree_auth_devise
module Spree class AuthConfiguration < Preferences::Configuration preference :registration_step, :boolean, :default => true preference :signout_after_password_change, :boolean, :default => true end end
Remove unused code from service_requests controller.
class ServiceRequestsController < ApplicationController skip_before_action :admin_only def show @service_request = ServiceRequest.find(params[:user_id]) end def new @service_request = ServiceRequest.new end def create @service_request = ServiceRequest.new(service_request_params) if @service_request.save flash[:success] = 'Created a new service request!' redirect_to @current_user else render 'new' end end def destroy if ServiceRequest.find(params[:id]).destroy flash[:success] = 'Service request deleted' else flash[:danger] = 'An unknown error occurred and the service request was not deleted. Please try again later or contact support.' end redirect_to root_url end def service_request_params params.require(:service_request).permit(:user_id, :request) end end
class ServiceRequestsController < ApplicationController skip_before_action :admin_only def new @service_request = ServiceRequest.new end def create @service_request = ServiceRequest.new(service_request_params) if @service_request.save flash[:success] = 'Created a new service request!' redirect_to @current_user else render 'new' end end def destroy if ServiceRequest.find(params[:id]).destroy flash[:success] = 'Service request deleted' else flash[:danger] = 'An unknown error occurred and the service request was not deleted. Please try again later or contact support.' end redirect_to root_url end def service_request_params params.require(:service_request).permit(:user_id, :request) end end
Fix call signature for GitInfo.from_path
require 'shipitron' require 'shellwords' require 'shipitron/git_info' module Shipitron module Server module Git class CloneLocalCopy include Metaractor required :application required :repository_url optional :repository_branch before do context.repository_branch ||= 'master' end def call Logger.info "Using this branch: #{repository_branch}" FileUtils.cd('/home/shipitron') do `git clone git-cache #{Shellwords.escape application} --recursive --branch #{Shellwords.escape repository_branch}` end Logger.info 'Using this git commit:' context.git_info = GitInfo.from_path("/home/shipitron/#{application}") Logger.info context.git_info.one_liner end private def application context.application end def repository_url context.repository_url end def repository_branch context.repository_branch end end end end end
require 'shipitron' require 'shellwords' require 'shipitron/git_info' module Shipitron module Server module Git class CloneLocalCopy include Metaractor required :application required :repository_url optional :repository_branch before do context.repository_branch ||= 'master' end def call Logger.info "Using this branch: #{repository_branch}" FileUtils.cd('/home/shipitron') do `git clone git-cache #{Shellwords.escape application} --recursive --branch #{Shellwords.escape repository_branch}` end Logger.info 'Using this git commit:' context.git_info = GitInfo.from_path(path: "/home/shipitron/#{application}") Logger.info context.git_info.one_liner end private def application context.application end def repository_url context.repository_url end def repository_branch context.repository_branch end end end end end
Convert Proj4::Point away from a Struct.
module Proj4 class Point < Struct.new(:x, :y, :z) end end
module Proj4 class Point attr_accessor :x, :y, :z def initialize(x, y, z = nil) @x, @y, @z = x, y, z end end end
Clean postgres first now we have an updater
Before do $tables_created ||= false return $tables_created if $tables_created delete_all_titles_from_elasticsearch # es-updater should recreate sleep($ELASTICSEARCH_SLEEP.to_i) clean_register_database end Before('@existing_user') do @new_user = {} @new_user['user'] = {} @new_user['user']['user_id'] = 'username' + timestamp @new_user['user']['password'] = 'dummypassword' insert_user(@new_user) end at_exit do puts 'End of Cucumber tests' puts 'Recreating tables and indexes' unless $tables_created delete_all_titles_from_elasticsearch # es-updater should recreate clean_register_database end sleep($ELASTICSEARCH_SLEEP.to_i) puts 'Creating user landregistry with password integration' @new_user = {} @new_user['user'] = {} @new_user['user']['user_id'] = 'landregistry' @new_user['user']['password'] = 'integration' insert_user(@new_user) puts 'Creating title DN1000 with postcode PL9 8TB' insert_title_with_owners end
Before do $tables_created ||= false return $tables_created if $tables_created delete_all_titles_from_elasticsearch # es-updater should recreate sleep($ELASTICSEARCH_SLEEP.to_i) clean_register_database end Before('@existing_user') do @new_user = {} @new_user['user'] = {} @new_user['user']['user_id'] = 'username' + timestamp @new_user['user']['password'] = 'dummypassword' insert_user(@new_user) end at_exit do puts 'End of Cucumber tests' puts 'Recreating tables and indexes' unless $tables_created clean_register_database delete_all_titles_from_elasticsearch # es-updater should recreate end sleep($ELASTICSEARCH_SLEEP.to_i) puts 'Creating user landregistry with password integration' @new_user = {} @new_user['user'] = {} @new_user['user']['user_id'] = 'landregistry' @new_user['user']['password'] = 'integration' insert_user(@new_user) puts 'Creating title DN1000 with postcode PL9 8TB' insert_title_with_owners end
Return to same level of abstraction
require "active_storage/blob" require "mini_magick" # Image blobs can have variants that are the result of a set of transformations applied to the original. class ActiveStorage::Variant attr_reader :blob, :variation delegate :service, to: :blob def initialize(blob, variation) @blob, @variation = blob, variation end def processed process unless service.exist?(key) self end def key "variants/#{blob.key}/#{variation.key}" end def url(expires_in: 5.minutes, disposition: :inline) service.url key, expires_in: expires_in, disposition: disposition, filename: blob.filename end private def process service.upload key, transform(service.download(blob.key)) end def transform(io) File.open MiniMagick::Image.read(io).tap { |image| variation.transform(image) }.path end end
require "active_storage/blob" require "mini_magick" # Image blobs can have variants that are the result of a set of transformations applied to the original. class ActiveStorage::Variant attr_reader :blob, :variation delegate :service, to: :blob def initialize(blob, variation) @blob, @variation = blob, variation end def processed process unless processed? self end def key "variants/#{blob.key}/#{variation.key}" end def url(expires_in: 5.minutes, disposition: :inline) service.url key, expires_in: expires_in, disposition: disposition, filename: blob.filename end private def processed? service.exist?(key) end def process service.upload key, transform(service.download(blob.key)) end def transform(io) File.open MiniMagick::Image.read(io).tap { |image| variation.transform(image) }.path end end
Add custom postgres options to column "index:" properties as well.
module SchemaPlusPgIndexes module Middleware module Postgresql module Dumper module Indexes # Dump index extensions def after(env) index_defs = Dumper.get_index_definitions(env, env.table) env.table.indexes.each do |index_dump| index_def = index_defs.find(&its.name == index_dump.name) index_dump.options[:case_sensitive] = false unless index_def.case_sensitive? index_dump.options[:expression] = index_def.expression if index_def.expression and index_def.case_sensitive? unless index_def.operator_classes.blank? if index_def.columns.uniq.length <= 1 && index_def.operator_classes.values.uniq.length == 1 index_dump.options[:operator_class] = index_def.operator_classes.values.first else index_dump.options[:operator_class] = index_def.operator_classes end end end end end module Table # Move index definitions inline def after(env) index_defs = Dumper.get_index_definitions(env, env.table) env.table.indexes.select(&its.columns.blank?).each do |index| env.table.statements << "t.index #{{name: index.name}.merge(index.options).to_s.sub(/^{(.*)}$/, '\1')}" env.table.indexes.delete(index) end end end def self.get_index_definitions(env, table_dump) env.dump.data.index_definitions ||= {} env.dump.data.index_definitions[table_dump.name] ||= env.connection.indexes(table_dump.name) end end end end end
module SchemaPlusPgIndexes module Middleware module Postgresql module Dumper module Table # Dump index extensions def after(env) index_defs = env.connection.indexes(env.table.name) def set_index_options(name, options, index_defs) index_def = index_defs.find(&its.name == name) options[:case_sensitive] = false unless index_def.case_sensitive? options[:expression] = index_def.expression if index_def.expression and index_def.case_sensitive? unless index_def.operator_classes.blank? if index_def.columns.uniq.length <= 1 && index_def.operator_classes.values.uniq.length == 1 options[:operator_class] = index_def.operator_classes.values.first else options[:operator_class] = index_def.operator_classes end end end env.table.columns.each do |column_dump| index = column_dump.options[:index] set_index_options(index[:name], index, index_defs) if index end env.table.indexes.each do |index_dump| set_index_options(index_dump.name, index_dump.options, index_defs) end end end end end end end
Add simple cov as a development dependency
# coding: utf-8 lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "sandbox/version" Gem::Specification.new do |spec| spec.name = "sandbox" spec.version = Sandbox::VERSION spec.authors = ["Jon Wheeler"] spec.email = ["jon@doejo.com"] spec.description = %q{CLI for Sandbox} spec.summary = %q{Create, Destroy and Manage Sandbox VMs from the command line} spec.homepage = "https://github.com/jonwheeler/sandbox" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency "rest-client", "~> 1.6" spec.add_dependency "terminal_helpers", "~> 0.1" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" spec.add_development_dependency "rspec", "~> 2.14" end
# coding: utf-8 lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "sandbox/version" Gem::Specification.new do |spec| spec.name = "sandbox" spec.version = Sandbox::VERSION spec.authors = ["Jon Wheeler"] spec.email = ["jon@doejo.com"] spec.description = %q{CLI for Sandbox} spec.summary = %q{Create, Destroy and Manage Sandbox VMs from the command line} spec.homepage = "https://github.com/jonwheeler/sandbox" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency "rest-client", "~> 1.6" spec.add_dependency "terminal_helpers", "~> 0.1" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" spec.add_development_dependency "rspec", "~> 2.14" spec.add_development_dependency "simplecov", "~> 0.7" end
Split message tests into 3 different tests
require "test_helper" include Warden::Test::Helpers feature "CanUserMessage" do scenario "should message another user", js: true do @user1 = FactoryGirl.create(:user) @user2 = FactoryGirl.create(:user) login_as @user1 visit message_new_path(@user2) send_message("hola trololo", "hola mundo") page.must_have_content body page.must_have_content "Mover mensaje a papelera" send_message("What a nice emoji😀!") page.must_have_content reply end def send_message(body, subject = nil) fill_in("mailboxer_message_subject", with: subject) if subject fill_in "mailboxer_message_body", with: body click_button "Enviar" end end
require "test_helper" include Warden::Test::Helpers feature "CanUserMessage" do before do @user1 = FactoryGirl.create(:user) @user2 = FactoryGirl.create(:user) login_as @user1 visit message_new_path(@user2) end it "should message another user", js: true do send_message("hola trololo", "hola mundo") page.must_have_content "hola trololo" page.must_have_content "Mover mensaje a papelera" end it "should message another user using emojis", js: true do skip "emojis not supported" send_message("What a nice emoji😀!", "hola mundo") page.must_have_content "What a nice emoji😀!" page.must_have_content "Mover mensaje a papelera" end it "should reply to a message", js: true do send_message("hola trololo", "hola mundo") send_message("hola trululu") page.must_have_content "hola trululu" end def send_message(body, subject = nil) fill_in("mailboxer_message_subject", with: subject) if subject fill_in "mailboxer_message_body", with: body click_button "Enviar" end end
Add example for variable that's not expected in the context
require 'spec_helper' require 'test_doubles' describe LightService::Orchestrator do class TestExecute extend LightService::Orchestrator def self.run(context) with(context).reduce(steps) end def self.steps [ TestDoubles::AddOneAction, execute(->(ctx) { ctx.number += 1 }), TestDoubles::AddOneAction ] end end it 'calls the lambda in the execute block using the context' do result = TestExecute.run(:number => 0) expect(result).to be_success expect(result.number).to eq(3) end end
require 'spec_helper' require 'test_doubles' describe LightService::Orchestrator do class TestExecute extend LightService::Orchestrator def self.run(context) with(context).reduce(steps) end def self.steps [ TestDoubles::AddOneAction, execute(->(ctx) { ctx.number += 1 }), execute(->(ctx) { ctx[:something] = 'hello' }), TestDoubles::AddOneAction ] end end it 'calls the lambda in the execute block using the context' do result = TestExecute.run(:number => 0) expect(result).to be_success expect(result.number).to eq(3) expect(result[:something]).to eq('hello') end end
Replace before_filter for Rails 5.1
module Spina module Admin class ProjectsController < AdminController before_filter :set_breadcrumb before_action :set_project, only: [:show, :edit, :update, :destroy] layout "spina/admin/admin" def show end def index @projects = Project.all end def new add_breadcrumb "New project", spina.new_admin_project_path @project = Project.new end def edit add_breadcrumb @project.title end def create add_breadcrumb "New project" @project = Project.new(project_params) if @project.save redirect_to spina.admin_projects_url else render :new end end def update add_breadcrumb @project.title if @project.update_attributes(project_params) redirect_to spina.admin_projects_url else render :edit end end def destroy @project.destroy redirect_to spina.admin_projects_url end private def set_project @project = Project.find(params[:id]) end def set_breadcrumb add_breadcrumb "Projects", spina.admin_projects_path end def project_params params.require(:project).permit( :title, :slug, :description, :lat, :long, :description, :duration, :completion_date, :project_category_id, :testimonial, :testimonial_name, :photo_id, :photo_collection_id, photo_collection_attributes: [:photo_tokens, :photo_positions]) end end end end
module Spina module Admin class ProjectsController < AdminController before_action :set_breadcrumb before_action :set_project, only: [:show, :edit, :update, :destroy] layout "spina/admin/admin" def show end def index @projects = Project.all end def new add_breadcrumb "New project", spina.new_admin_project_path @project = Project.new end def edit add_breadcrumb @project.title end def create add_breadcrumb "New project" @project = Project.new(project_params) if @project.save redirect_to spina.admin_projects_url else render :new end end def update add_breadcrumb @project.title if @project.update_attributes(project_params) redirect_to spina.admin_projects_url else render :edit end end def destroy @project.destroy redirect_to spina.admin_projects_url end private def set_project @project = Project.find(params[:id]) end def set_breadcrumb add_breadcrumb "Projects", spina.admin_projects_path end def project_params params.require(:project).permit( :title, :slug, :description, :lat, :long, :description, :duration, :completion_date, :project_category_id, :testimonial, :testimonial_name, :photo_id, :photo_collection_id, photo_collection_attributes: [:photo_tokens, :photo_positions]) end end end end
Return a calltree file instead of appending the html call graph to the page
require 'ruby-prof' require 'set' module ActionController module ActionProfiler MODES = Set.new(%w(process_time wall_time cpu_time allocated_objects memory)) # Pass profile=1 query param to profile the page load. def action_profiler(&block) if !RubyProf.running? && mode = params[:profile] if MODES.include?(mode) RubyProf.measure_mode = RubyProf.const_get(mode.upcase) end result = RubyProf.profile(&block) if response.body.is_a?(String) output = StringIO.new min_percent = (params[:profile_percent] || 10).to_i RubyProf::GraphHtmlPrinter.new(result).print(output, :min_percent => min_percent) if output.string =~ /<body>(.*)<\/body>/m response.body.sub! '</body>', %(<div id="RubyProf">#{$1}</div></body>) else ActionController::Base.logger.info "[PROFILE] Non-HTML profile result: #{output.string}" end else ActionController::Base.logger.info '[PROFILE] Non-HTML response body, skipping results' end else yield end end end end
require 'ruby-prof' require 'set' module ActionController module ActionProfiler MODES = Set.new(%w(process_time wall_time cpu_time allocated_objects memory)) # Pass profile=1 query param to profile the page load. def action_profiler(&block) if !RubyProf.running? && mode = params[:profile] if MODES.include?(mode) RubyProf.measure_mode = RubyProf.const_get(mode.upcase) end result = RubyProf.profile(&block) if response.body.is_a?(String) min_percent = (params[:profile_percent] || 0.05).to_f output = StringIO.new RubyProf::CallTreePrinter.new(result).print(output, :min_percent => min_percent) response.body.replace(output.string) response.headers['Content-Length'] = response.body.size response.headers['Content-Type'] = 'application/octet-stream' response.headers['Content-Disposition'] = %(attachment; filename="#{File.basename(request.path)}.tree") end else yield end end end end
Add configurable size to ProcessingPool
module Trusted module Request class ProcessingPool attr_reader :handler, :thread_pool def initialize(handler) @handler = handler @thread_pool = Concurrent::FixedThreadPool.new(5) end private def execute_future(request, response, observer) future = Concurrent::Future.new(executor: thread_pool, args: [request, response], &handler) future.add_observer(observer) future.execute end end end end
module Trusted module Request class ProcessingPool attr_reader :handler, :thread_pool def initialize(handler, thread_pool_size) @handler = handler @thread_pool = Concurrent::FixedThreadPool.new(thread_pool_size) end private def execute_future(request, response, observer) future = Concurrent::Future.new(executor: thread_pool, args: [request, response], &handler) future.add_observer(observer) future.execute end end end end
Define status for an OmniauthSignin
class OmniauthSignIn attr_accessor :provider delegate :authorization, :user, :no_account_conflicts?, to: :@user_initializer, allow_nil: true def initialize(user, provider) @user, @provider = user, provider end def complete(omniauth_data) @user_initializer = UserInitializer.new(provider, omniauth_data) @user_initializer.setup end def user_email @user_initializer.try(:email) end end
class OmniauthSignIn attr_accessor :provider delegate :authorization, :user, :no_account_conflicts?, to: :@user_initializer, allow_nil: true def initialize(user, provider) @user, @provider = user, provider end def complete(omniauth_data) @user_initializer = UserInitializer.new(provider, omniauth_data) @user_initializer.setup end def status if already_signed_in? || authorization_exists? :success elsif empty_email? :needs_email else :needs_ownership_confirmation end end end
Test struct methods ending in ?, !
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes', __FILE__) describe "Struct#initialize" do it "is private" do StructClasses::Car.should have_private_instance_method(:initialize) end it "does nothing when passed a set of fields equal to self" do car = same_car = StructClasses::Car.new("Honda", "Accord", "1998") car.instance_eval { initialize("Honda", "Accord", "1998") } car.should == same_car end it "explicitly sets instance variables to nil when args not provided to initialize" do car = StructClasses::Honda.new car.make.should == nil # still nil despite override in Honda#initialize b/c of super order end it "can be overriden" do StructClasses::SubclassX.new(:y).new.key.should == :value end end
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes', __FILE__) describe "Struct#initialize" do it "is private" do StructClasses::Car.should have_private_instance_method(:initialize) end it 'allows valid Ruby method names for members' do valid_method_names = [ :method1, :method_1, :method_1?, :method_1!, :a_method ] valid_method_names.each do |method_name| klass = Struct.new(method_name) instance = klass.new(:value) instance.send(method_name).should == :value writer_method = "#{method_name}=".to_sym result = instance.send(writer_method, :new_value) result.should == :new_value instance.send(method_name).should == :new_value end end it "does nothing when passed a set of fields equal to self" do car = same_car = StructClasses::Car.new("Honda", "Accord", "1998") car.instance_eval { initialize("Honda", "Accord", "1998") } car.should == same_car end it "explicitly sets instance variables to nil when args not provided to initialize" do car = StructClasses::Honda.new car.make.should == nil # still nil despite override in Honda#initialize b/c of super order end it "can be overriden" do StructClasses::SubclassX.new(:y).new.key.should == :value end end
Save Stripe plan to user when signing up as a supporter
class SupportersController < ApplicationController before_filter :authenticate_user! def new end def create # Create or retrieve the Stripe customer if current_user.stripe_customer_id # TODO: Handle missing or deleted customer customer = Stripe::Customer.retrieve current_user.stripe_customer_id else customer = Stripe::Customer.create( email: params[:stripeEmail], card: params[:stripeToken], description: "Customer for @#{current_user.nickname}" ) current_user.update! stripe_customer_id: customer.id end # TODO: Handle missing or incorrect plan subscription = customer.subscriptions.create plan: params[:plan_id] @price = subscription[:plan][:amount] rescue Stripe::CardError => e flash[:error] = e.message redirect_to supporters_path end end
class SupportersController < ApplicationController before_filter :authenticate_user! def new end def create # Create or retrieve the Stripe customer if current_user.stripe_customer_id # TODO: Handle missing or deleted customer customer = Stripe::Customer.retrieve current_user.stripe_customer_id else customer = Stripe::Customer.create( email: params[:stripeEmail], card: params[:stripeToken], description: "Customer for @#{current_user.nickname}" ) current_user.update! stripe_customer_id: customer.id end # TODO: Handle missing or incorrect plan subscription = customer.subscriptions.create plan: params[:plan_id] current_user.update! stripe_plan_id: subscription[:plan][:id] @price = subscription[:plan][:amount] rescue Stripe::CardError => e flash[:error] = e.message redirect_to supporters_path end end
Update podspec for new release with doc link
Pod::Spec.new do |s| s.platform = :ios, "8.0" s.name = "RQVisual" s.version = "1.0.0" s.summary = "A tool for laying out views in code." s.description = <<-DESC Visual is a tool for laying out views in code using a visual style formats similar to those used by NSLayoutConstraint. DESC s.homepage = "https://github.com/rqueue/RQVisual" s.license = "MIT" s.author = { "Ryan Quan" => "ryanhquan@gmail.com" } s.source = { :git => "https://github.com/rqueue/RQVisual.git", :tag => "1.0.0" } s.source_files = "RQVisual", "RQVisual/**/*.{h,m}" s.requires_arc = true s.documentation_url = "https://github.com/rqueue/RQVisual" end
Pod::Spec.new do |s| s.platform = :ios, "8.0" s.name = "RQVisual" s.version = "1.0.1" s.summary = "A tool for laying out views in code." s.description = <<-DESC Visual is a tool for laying out views in code using a visual style formats similar to those used by NSLayoutConstraint. DESC s.homepage = "https://github.com/rqueue/RQVisual" s.license = "MIT" s.author = { "Ryan Quan" => "ryanhquan@gmail.com" } s.source = { :git => "https://github.com/rqueue/RQVisual.git", :tag => "1.0.1" } s.source_files = "RQVisual", "RQVisual/**/*.{h,m}" s.requires_arc = true s.documentation_url = "https://github.com/rqueue/RQVisual" end
Reorder setting of `@dirname` instance variable to make it available while running the `convert` method.
module JAPR class Converter extend JAPR::SubclassTracking def initialize(asset) @content = asset.content @type = File.extname(asset.filename).downcase @converted = convert @dirname = asset.dirname end def converted @converted end # Filetype to process (e.g. '.coffee') def self.filetype '' end # Logic to convert assets # # Available instance variables: # @file File to be converted # @content Contents of @file as a string # @type Filetype of file (e.g. '.coffee') # # Returns converted string def convert @content end end end
module JAPR class Converter extend JAPR::SubclassTracking def initialize(asset) @content = asset.content @type = File.extname(asset.filename).downcase @dirname = asset.dirname @converted = convert end def converted @converted end # Filetype to process (e.g. '.coffee') def self.filetype '' end # Logic to convert assets # # Available instance variables: # @file File to be converted # @content Contents of @file as a string # @type Filetype of file (e.g. '.coffee') # # Returns converted string def convert @content end end end
Add missing method on Spree::Konbini
module Spree class Konbini < Spree::Base STORES = %i(lawson family-mart sunkus circle-k ministop daily-yamazaki seven-eleven) belongs_to :payment_method belongs_to :user, class_name: Spree.user_class, foreign_key: 'user_id' has_many :payments, as: :source validates :convenience, presence: true def actions %w{capture void} end def can_capture?(payment) return false unless ['checkout', 'pending'].include?(payment.state) payment.source.expires_at && (payment.source.expires_at > DateTime.current) end def can_void?(payment) payment.state != 'void' end def instruction_partial_path "spree/orders/konbini" end end end
module Spree class Konbini < Spree::Base STORES = %i(lawson family-mart sunkus circle-k ministop daily-yamazaki seven-eleven) belongs_to :payment_method belongs_to :user, class_name: Spree.user_class, foreign_key: 'user_id' has_many :payments, as: :source validates :convenience, presence: true def actions %w{capture void} end def can_capture?(payment) return false unless ['checkout', 'pending'].include?(payment.state) payment.source.expires_at && (payment.source.expires_at > DateTime.current) end def can_void?(payment) payment.state != 'void' end def instruction_partial_path "spree/orders/konbini" end def imported false end end end
Move include to top of file
module Arel # :nodoc: module Visitors # :nodoc: # Different super-class under JRuby JDBC adapter. PostGISSuperclass = if defined?(::ArJdbc::PostgreSQL::BindSubstitution) ::ArJdbc::PostgreSQL::BindSubstitution else PostgreSQL end class PostGIS < PostGISSuperclass # :nodoc: FUNC_MAP = { 'st_wkttosql' => 'ST_GeomFromEWKT', } include RGeo::ActiveRecord::SpatialToSql def st_func(standard_name) FUNC_MAP[standard_name.downcase] || standard_name end def visit_String(node, collector) collector << "#{st_func('ST_WKTToSQL')}(#{quote(node)})" end def visit_RGeo_ActiveRecord_SpatialNamedFunction(node, collector) aggregate(st_func(node.name), node, collector) end end end end
module Arel # :nodoc: module Visitors # :nodoc: # Different super-class under JRuby JDBC adapter. PostGISSuperclass = if defined?(::ArJdbc::PostgreSQL::BindSubstitution) ::ArJdbc::PostgreSQL::BindSubstitution else PostgreSQL end class PostGIS < PostGISSuperclass # :nodoc: include RGeo::ActiveRecord::SpatialToSql FUNC_MAP = { 'st_wkttosql' => 'ST_GeomFromEWKT', } def st_func(standard_name) FUNC_MAP[standard_name.downcase] || standard_name end def visit_String(node, collector) collector << "#{st_func('ST_WKTToSQL')}(#{quote(node)})" end def visit_RGeo_ActiveRecord_SpatialNamedFunction(node, collector) aggregate(st_func(node.name), node, collector) end end end end
Make the user available in TypingEvent
require 'discordrb/events/generic' module Discordrb::Events class TypingEvent attr_reader :channel, :timestamp def initialize(data, bot) @user_id = data['user_id'] @channel_id = data['user_id'] @channel = bot.channel(@channel_id) @timestamp = Time.at(data['timestamp'].to_i) end end class TypingEventHandler < EventHandler def matches?(event) # Check for the proper event type return false unless event.is_a? TypingEvent return [ matches_all(@attributes[:in], event.channel) do |a,e| if a.is_a? String a == e.name elsif a.is_a? Fixnum a == e.id else a == e end end, matches_all(@attributes[:from], event.user) do |a,e| if a.is_a? String a == e.name elsif a.is_a? Fixnum a == e.id else a == e end end ].reduce(true, &:&) end end end
require 'discordrb/events/generic' module Discordrb::Events class TypingEvent attr_reader :channel, :user, :timestamp def initialize(data, bot) @user_id = data['user_id'] @user = bot.user(@user_id) @channel_id = data['channel_id'] @channel = bot.channel(@channel_id) @timestamp = Time.at(data['timestamp'].to_i) end end class TypingEventHandler < EventHandler def matches?(event) # Check for the proper event type return false unless event.is_a? TypingEvent return [ matches_all(@attributes[:in], event.channel) do |a,e| if a.is_a? String a == e.name elsif a.is_a? Fixnum a == e.id else a == e end end, matches_all(@attributes[:from], event.user) do |a,e| if a.is_a? String a == e.name elsif a.is_a? Fixnum a == e.id else a == e end end ].reduce(true, &:&) end end end
Bring the mysql::server attributes into scope Minor documentation adjustment
# # Cookbook Name:: lamp # Attributes:: default # # Copyright 2013, Mediacurrent # # All rights reserved - Do Not Redistribute include_attribute "php" # Install build-essential. default['build_essential']['compiletime'] = true # Mysql settings. default['mysql']['server_root_password'] = 'password' default['mysql']['server_debian_password'] = 'password' default['mysql']['server_repl_password'] = 'password' # sane settings for development environment # http://project.mediacurrent.com/mct/node/21400 default['mysql']['tunable']['max_allowed_packet'] = "64M" default['mysql']['tunable']['max_connections'] = "40" default['mysql']['tunable']['query_cache_limit'] = "8M" default['mysql']['tunable']['query_cache_size'] = "64M" # Custom PHP settings. default['lamp']['php']['apache_conf_dir'] = '/etc/php5/apache2' default['lamp']['php']['error_reporting'] = 'E_ALL'
# # Cookbook Name:: lamp # Attributes:: default # # Copyright 2013, Mediacurrent # # All rights reserved - Do Not Redistribute include_attribute "mysql::server" include_attribute "php" # Install build-essential. default['build_essential']['compiletime'] = true # Mysql settings. default['mysql']['server_root_password'] = 'password' default['mysql']['server_debian_password'] = 'password' default['mysql']['server_repl_password'] = 'password' # Sane settings for development environment. # http://project.mediacurrent.com/mct/node/21400 default['mysql']['tunable']['max_allowed_packet'] = "64M" default['mysql']['tunable']['max_connections'] = "40" default['mysql']['tunable']['query_cache_limit'] = "8M" default['mysql']['tunable']['query_cache_size'] = "64M" # Custom PHP settings. default['lamp']['php']['apache_conf_dir'] = '/etc/php5/apache2' default['lamp']['php']['error_reporting'] = 'E_ALL'
Add tests for network scripts dir
require_relative "../../../../base" describe "VagrantPlugins::GuestPld::Cap::NetworkScriptsDir" do let(:caps) do VagrantPlugins::GuestPld::Plugin .components .guest_capabilities[:pld] end let(:machine) { double("machine") } describe ".network_scripts_dir" do let(:cap) { caps.get(:network_scripts_dir) } let(:name) { "banana-rama.example.com" } it "is /etc/sysconfig/interfaces" do expect(cap.network_scripts_dir(machine)).to eq("/etc/sysconfig/interfaces") end end end
Make `ConsultationUpdateTest` spec way more accurate
require "test_helper" module GobiertoAdmin module GobiertoBudgetConsultations class ConsultationUpdateTest < ActionDispatch::IntegrationTest def setup super @path = edit_admin_budget_consultation_path(consultation) end def consultation @consultation ||= gobierto_budget_consultations_consultations(:madrid_open) end def admin @admin ||= consultation.admin end def site @site ||= consultation.site end def test_consultation_update with_signed_in_admin(admin) do with_current_site(site) do visit @path within "form.edit_consultation" do fill_in "consultation_title", with: "Consultation Title" fill_in "consultation_description", with: "Consultation Description" fill_in "consultation_opening_date_range", with: "2016-01-01 - 2016-12-01" within ".consultation-visibility-level-radio-buttons" do choose "Draft" end click_button "Update Consultation" end assert has_content?("Consultation was successfully updated.") within "table.consultations-list tbody tr", match: :first do assert has_content?("Consultation Title") assert has_content?("Draft") click_link "Consultation Title" end within ".consultation-visibility-level-radio-buttons" do assert has_checked_field?("Draft") end end end end end end end
require "test_helper" module GobiertoAdmin module GobiertoBudgetConsultations class ConsultationUpdateTest < ActionDispatch::IntegrationTest def setup super @path = edit_admin_budget_consultation_path(consultation) end def consultation @consultation ||= gobierto_budget_consultations_consultations(:madrid_open) end def admin @admin ||= consultation.admin end def site @site ||= consultation.site end def test_consultation_update with_signed_in_admin(admin) do with_current_site(site) do visit @path within "form.edit_consultation" do fill_in "consultation_title", with: "Consultation Title" fill_in "consultation_description", with: "Consultation Description" fill_in "consultation_opening_date_range", with: "2016-01-01 - 2016-12-01" within ".consultation-visibility-level-radio-buttons" do choose "Draft" end click_button "Update Consultation" end assert has_content?("Consultation was successfully updated.") within "table.consultations-list tbody tr#consultation-item-#{consultation.id}" do assert has_content?("Consultation Title") assert has_content?("Draft") click_link "Consultation Title" end within ".consultation-visibility-level-radio-buttons" do assert has_checked_field?("Draft") end end end end end end end
Add functions for the derivative of the sigmoid function.
module NeuralNets class Math ## # The sigmoid function def self.sigmoid(x) 1.0/(1.0 + Math.exp(-x)) end ## # NMatrix version of the sigmoid function def self.sigmoid_vec(x) one = NMatrix.ones([x.rows, x.cols]) one/(one + (-x).exp) end end end
module NeuralNets class Math ## # The sigmoid function def self.sigmoid(x) 1.0/(1.0 + Math.exp(-x)) end ## # NMatrix version of the sigmoid function def self.sigmoid_vec(x) one = NMatrix.ones([x.rows, x.cols]) one/(one + (-x).exp) end ## # Derivative of the sigmoid function def self.sigmoid_prime(x) sigma = self.sigmoid(x) sigma*(1.0 - sigma) end ## # NMatrix version of the derivative of the sigmoid function def self.sigmoid_prime_vec(x) one = NMatrix.ones([x.rows, x.cols]) sigma = self.sigmoid_vec(x) sigma.dot(one - sigma) end end end
Add rake tasks for the new methods in AssetRemover
namespace :asset_manager do desc "Migrates Assets to Asset Manager." task :migrate_assets, [:target_dir] => :environment do |_, args| abort(usage_string) unless args[:target_dir] migrator = MigrateAssetsToAssetManager.new(args[:target_dir]) puts migrator migrator.perform end desc "Removes all organisation logos." task remove_organisation_logo: :environment do files = AssetRemover.new.remove_organisation_logo puts files end private def usage_string %{Usage: asset_manager:migrate_assets[<path>] Where <path> is a subdirectory under Whitehall.clean_uploads_root e.g. `system/uploads/organisation/logo` } end end
namespace :asset_manager do desc "Migrates Assets to Asset Manager." task :migrate_assets, [:target_dir] => :environment do |_, args| abort(usage_string) unless args[:target_dir] migrator = MigrateAssetsToAssetManager.new(args[:target_dir]) puts migrator migrator.perform end %i(remove_organisation_logo remove_consultation_response_form_data_file remove_classification_featuring_image_data_file remove_default_news_organisation_image_data_file remove_feature_image remove_image_data_file remove_person_image remove_promotional_feature_item_image remove_take_part_page_image).each do |method| desc "Calls AssetRemover##{method}." task method => :environment do files = AssetRemover.new.send(method) puts files end end private def usage_string %{Usage: asset_manager:migrate_assets[<path>] Where <path> is a subdirectory under Whitehall.clean_uploads_root e.g. `system/uploads/organisation/logo` } end end
Remove spurious puts in test
RSpec.describe "vm_extensions" do let(:manifest) { cloud_config_with_defaults } describe "prometheus_lb" do it "Should add the prometheus lb config" do expect(manifest['vm_extensions.prometheus_lb.cloud_properties.lb_target_groups']).to_not be_empty end end describe "bosh_client" do it "Should add the bosh_client security group" do puts manifest['vm_extensions'] expect(manifest['vm_extensions.bosh_client.cloud_properties.security_groups']).to_not be_empty end end end
RSpec.describe "vm_extensions" do let(:manifest) { cloud_config_with_defaults } describe "prometheus_lb" do it "Should add the prometheus lb config" do expect(manifest['vm_extensions.prometheus_lb.cloud_properties.lb_target_groups']).to_not be_empty end end describe "bosh_client" do it "Should add the bosh_client security group" do expect(manifest['vm_extensions.bosh_client.cloud_properties.security_groups']).to_not be_empty end end end
Mark admin as updated when we are going to reboot it
require "velum/salt" # UpdatesController handles all the interaction with the updates of all nodes. class UpdatesController < ApplicationController before_action :admin_needs_update, only: :create # Reboot the admin node. def create ::Velum::Salt.call( action: "cmd.run", targets: "admin", arg: "systemctl reboot" ) render json: { status: "rebooting" } end protected def admin_needs_update render json: { status: "unknown" } if Minion.where(role: Minion.roles[:admin]) .needs_update.count.zero? end end
require "velum/salt" # UpdatesController handles all the interaction with the updates of all nodes. class UpdatesController < ApplicationController before_action :admin_needs_update, only: :create # Reboot the admin node. def create # rubocop:disable SkipsModelValidations Minion.admin.update_all highstate: Minion.highstates[:applied] # rubocop:enable SkipsModelValidations ::Velum::Salt.call( action: "cmd.run", targets: "admin", arg: "systemctl reboot" ) render json: { status: "rebooting" } end protected def admin_needs_update render json: { status: "unknown" } if Minion.where(role: Minion.roles[:admin]) .needs_update.count.zero? end end
Remove redundant serialization of refable_qings
# frozen_string_literal: true module ConditionalLogicForm # Serializes Condition for use in condition form. class ConditionSerializer < ApplicationSerializer attributes :id, :left_qing_id, :right_qing_id, :right_side_type, :op, :value, :option_node_id, :option_set_id, :form_id, :conditionable_id, :conditionable_type, :operator_options has_many :refable_qings, serializer: TargetFormItemSerializer delegate :id, :conditionable_id, :value, to: :object def operator_options object.applicable_operator_names.map { |n| {name: I18n.t("condition.operators.select.#{n}"), id: n} } end def option_set_id object.left_qing&.option_set_id end end end
# frozen_string_literal: true module ConditionalLogicForm # Serializes Condition for use in condition form. class ConditionSerializer < ApplicationSerializer attributes :id, :left_qing_id, :right_qing_id, :right_side_type, :op, :value, :option_node_id, :option_set_id, :form_id, :conditionable_id, :conditionable_type, :operator_options delegate :id, :conditionable_id, :value, to: :object def operator_options object.applicable_operator_names.map { |n| {name: I18n.t("condition.operators.select.#{n}"), id: n} } end def option_set_id object.left_qing&.option_set_id end end end
Put CountDistinct in MiniFacet module
# Can be included in any class that responds to #each. # Such as Array. module CountDistinct def count_distinct(purge_smaller_than=0) h={} self.each {|e| h[e] ? h[e] += 1 : h[e] = 1 } h.extract{|k,v| v >= purge_smaller_than} end end Array.send :include, CountDistinct
# Can be included in any class that responds to #each. # Such as Array. module MiniFacet::CountDistinct def count_distinct(purge_smaller_than=0) h={} self.each {|e| h[e] ? h[e] += 1 : h[e] = 1 } h.extract{|k,v| v >= purge_smaller_than} end end Array.send :include, MiniFacet::CountDistinct
Use `column_exists?` to see if `:workflow_id` is present
class TidyUpBecauseOfBadException < ActiveRecord::Migration[4.2] def change if Hyrax::PermissionTemplate.column_names.include?('workflow_id') Hyrax::PermissionTemplate.all.each do |permission_template| workflow_id = permission_template.workflow_id next unless workflow_id Sipity::Workflow.find(workflow_id).update(active: true) end remove_column Hyrax::PermissionTemplate.table_name, :workflow_id end end end
class TidyUpBecauseOfBadException < ActiveRecord::Migration[4.2] def change if column_exists?(Hyrax::PermissionTemplate.table_name, :workflow_id) Hyrax::PermissionTemplate.all.each do |permission_template| workflow_id = permission_template.workflow_id next unless workflow_id Sipity::Workflow.find(workflow_id).update(active: true) end remove_column Hyrax::PermissionTemplate.table_name, :workflow_id end end end
Remove code coverage for 1.8
require 'simplecov' SimpleCov.start { add_filter '/test/' } require 'rbvmomi' VIM = RbVmomi::VIM require 'test/unit'
unless /^1.8/ =~ RUBY_VERSION require 'simplecov' SimpleCov.start { add_filter '/test/' } end require 'rbvmomi' VIM = RbVmomi::VIM require 'test/unit'
Add feature spec for vision
require 'rails_helper.rb' feature 'Vision' do scenario 'User can add a vision' do # given_i_am_on_the_homepage visit root_path # when_i_add_a_new_vision click_link "Add Your Vision", match: :first fill_in 'Describe Your Ideal World', with: "I want all humans to be happy" # and_choose_my_favorite_color 'Light blue' select('Light blue', from: 'vision_color') click_button 'Publish' # then_i_should_be_redirected_to_my_vision expect(page).to have_current_path(vision_path(Vision.last)) expect(page).to have_content("I want all humans to be happy") # and_the_color_scheme_of_the_page_should_be 'light-blue' expect(page).to have_css('body.color-scheme.primary-light-blue') end end
Use `secret_key_base` on Rails 5 or later
# Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. Dummy::Application.config.secret_token = 'c3a62b6e2236d66db4f1213324eb87df2889765d0b12c67ccb272c7c56f2d56b4ed07200100058aeb5f4d0ee94ea9cab8bad2044f21cac59b58dfb78f2886238'
# Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. secret_key_base = 'c3a62b6e2236d66db4f1213324eb87df2889765d0b12c67ccb272c7c56f2d56b4ed07200100058aeb5f4d0ee94ea9cab8bad2044f21cac59b58dfb78f2886238' if Rails.gem_version >= Gem::Version.new('5') Dummy::Application.config.secret_key_base = secret_key_base else Dummy::Application.config.secret_token = secret_key_base end
Add rake tasks for cloning and pulling METADATA.jl
namespace :metadata do metadata_directory = 'tmp/METADATA.jl' desc "clone metadata project" task clone: :environment do `git clone https://github.com/JuliaLang/METADATA.jl.git ./#{metadata_directory}` end desc "update local metadata project" task pull: :environment do `git -C #{metadata_directory} pull` end end
Reorder factory to appease JRuby's JSON parser
describe RspecApiHelpers::Strategies::JsonStrategy do before do User = Class.new { attr_accessor :name, :email } FactoryGirl.define do factory :user do name 'Mrs. Mock' email 'test@test.com' end end end subject { FactoryGirl.json :user } it 'should render user as json' do expect(subject).to eq '{"name":"Mrs. Mock","email":"test@test.com"}' end end
describe RspecApiHelpers::Strategies::JsonStrategy do before do User = Class.new { attr_accessor :name, :email } FactoryGirl.define do factory :user do email 'test@test.com' name 'Mrs. Mock' end end end subject { FactoryGirl.json :user } it 'should render user as json' do expect(subject).to eq '{"email":"test@test.com","name":"Mrs. Mock"}' end end
Add NilClass to uncloneable types
module Pakyow module Utils module Dup UNCLONEABLE = [Symbol, Fixnum] def self.deep(value) return value if UNCLONEABLE.include?(value.class) if value.is_a?(Hash) result = value.clone value.each { |k, v| result[deep(k)] = deep(v) } result elsif value.is_a?(Array) result = value.clone result.clear value.each{ |v| result << deep(v) } result else value.clone end end end end end
module Pakyow module Utils module Dup UNCLONEABLE = [Symbol, Fixnum, NilClass] def self.deep(value) return value if UNCLONEABLE.include?(value.class) if value.is_a?(Hash) result = value.clone value.each { |k, v| result[deep(k)] = deep(v) } result elsif value.is_a?(Array) result = value.clone result.clear value.each{ |v| result << deep(v) } result else value.clone end end end end end
Add spatial index on PhysicalRoads
class CreatePhysicalRoadsSpatialIndex < ActiveRecord::Migration def up add_index :physical_roads, :geometry, :spatial => true end def down remove_index :physical_roads, :geometry, :spatial => true end end
Add tests for multiple minutes
require 'rspec/given' require 'subtime/timer' describe Timer do let(:output) { double('output').as_null_object } describe "#start" do context "without messages" do let(:minutes) { 0 } let(:timer) { Timer.new(output, minutes) } it "outputs 'Starting timer for 0 minutes...'" do expect(output).to receive(:puts).with("Starting timer for #{minutes} minutes...") timer.start end it "says 'timer done' when finished" do expect(timer).to receive(:`).with("say timer done") timer.start end end end end
require 'rspec/given' require 'subtime/timer' module Kernel def sleep(seconds) end end describe Timer do let(:output) { double('output').as_null_object } describe "#start" do context "without messages" do let(:minutes) { 0 } let(:timer) { Timer.new(output, minutes) } it "outputs 'Starting timer for 0 minutes...'" do expect(output).to receive(:puts).with("Starting timer for #{minutes} minutes...") timer.start end it "says 'timer done' when finished" do expect(timer).to receive(:`).with("say timer done") timer.start end end context "for 10 minutes" do let(:minutes) { 10 } let(:messages) { { 5 => "something", 2 => "something else" } } let(:timer) { Timer.new(output, minutes, messages) } it "outputs 'Starting timer for 10 minutes...'" do expect(output).to receive(:puts).with("Starting timer for #{minutes} minutes...") timer.start end it "outputs each minute from 10 down to 1" do 10.downto(1) do |minute| expect(output).to receive(:puts).with(minute) end timer.start end context "with message 'something' at 5" do it "says 'something'" do expect(output).to receive(:`).with("say 'something'") timer.start end end context "with message 'something else' at 2" do it "says 'something else'" do expect(output).to receive(:`).with("say something else") timer.start end end end end end
Check database permissions across different users.
require 'sinatra/base' require 'json' require 'pg' class PostgresqlSmoketest < Sinatra::Base get '/' do connection.exec("SELECT 'ok'").values.first.first end private def credentials JSON.parse(ENV['VCAP_SERVICES'])['postgresql-db'].first['credentials'] end def connection @conn ||= PG.connect(host: credentials['hostname'], user: credentials['username'], port: credentials['port'], dbname: credentials['db_name']) end end
require 'sinatra/base' require 'json' require 'pg' class PostgresqlSmoketest < Sinatra::Base get '/' do connection.exec("SELECT 'ok'").values.first.first end put '/create-database/:db_name' do |db_name| connection.exec("CREATE DATABASE #{db_name}") connection.exec("REVOKE ALL ON DATABASE #{db_name} FROM public") end put '/create-user/:username/for/:db_name' do |username, db_name| connection.exec("CREATE USER #{username} WITH PASSWORD '#{username}'") connection.exec("GRANT ALL PRIVILEGES ON DATABASE #{db_name} TO #{username}") end get '/select-ok/on/:db_name/as/:username' do |db_name, username| conn = PG.connect(host: credentials['hostname'], port: credentials['port'], dbname: db_name, user: username) conn.exec("SELECT 'ok'").values.first.first end private def credentials JSON.parse(ENV['VCAP_SERVICES'])['postgresql-db'].first['credentials'] end def connection @conn ||= PG.connect(host: credentials['hostname'], user: credentials['username'], port: credentials['port'], dbname: credentials['db_name']) end end
Add - Add twitter SEO
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :prepare_meta_tags private def prepare_meta_tags opts={} title = opts[:title] || I18n.t('title') site = opts[:site] || '' description = opts[:description] keywords = opts[:keywords] defaults = { # common title: title, site: site, description: description, keywords: keywords, # facebook og: { title: site.present? ? "#{site} | #{title}" : title, description: description, url: request.original_url, site_name: title, type: opts[:type] || 'website', image: opts[:image] } } set_meta_tags defaults end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :prepare_meta_tags private def prepare_meta_tags(opts = {}) title = opts[:title] || I18n.t('title') site = opts[:site] || '' description = opts[:description] keywords = opts[:keywords] defaults = { # common title: title, site: site, description: description, keywords: keywords, # facebook og: { title: site.present? ? "#{site} | #{title}" : title, description: description, url: request.original_url, site_name: title, type: opts[:type] || 'website', image: opts[:image] }, twitter: { card: 'summary', title: site.present? ? "#{site} | #{title}" : title, description: description, url: request.original_url, image: { src: opts[:image] } } } set_meta_tags defaults end end
Fix broken test due to missing selector.
require 'rails_helper' describe "Search form" do before do visit '/' end it "checks if a specific word can be found in the posts title" do @post = FactoryGirl.create(:internal_post, title: 'something about rails') fill_in 'Search', with: 'rails' find('.submit-search').click expect(page).to have_content 'something about rails' end end
require 'rails_helper' describe "Search form" do before do visit '/' end it "checks if a specific word can be found in the posts title" do @post = FactoryGirl.create(:internal_post, title: 'something about rails') fill_in 'Search', with: 'rails' click_button 'Search' expect(page).to have_content 'something about rails' end end
Refactor mdTranslator html writer module 'domainItem'
# HTML writer # domain item # History: # Stan Smith 2017-04-05 refactored for mdTranslator 2.0 # Stan Smith 2015-03-26 original script module ADIWG module Mdtranslator module Writers module Html class Html_DomainItem def initialize(html) @html = html end def writeHtml(hItem) @html.text!('Nothing Yet') # # domain member - common name # s = hItem[:itemName] # if !s.nil? # @html.em('Common name: ') # @html.text!(s) # @html.br # end # # # domain member - value # s = hItem[:itemValue] # if !s.nil? # @html.em('Domain value: ') # @html.text!(s) # @html.br # end # # # domain member - definition # s = hItem[:itemDefinition] # if !s.nil? # @html.em('Definition: ') # @html.section(:class => 'block') do # @html.text!(s) # end # end end # writeHtml end # Html_DomainItem end end end end
# HTML writer # domain item # History: # Stan Smith 2017-04-05 refactored for mdTranslator 2.0 # Stan Smith 2015-03-26 original script module ADIWG module Mdtranslator module Writers module Html class Html_DomainItem def initialize(html) @html = html end def writeHtml(hItem) # domain member - common name unless hItem[:itemName].nil? @html.em('Name: ') @html.text!(hItem[:itemName]) @html.br end # domain member - value unless hItem[:itemValue].nil? @html.em('Value: ') @html.text!(hItem[:itemValue]) @html.br end # domain member - definition unless hItem[:itemDefinition].nil? @html.em('Definition: ') @html.section(:class => 'block') do @html.text!(hItem[:itemDefinition]) end end end # writeHtml end # Html_DomainItem end end end end
Add timezone env variable (for CI)
require 'rspec/rails' require 'shoulda-matchers' require 'timecop' Time.zone = 'Europe/London' # path relative to the Dummy app, which is by convention at spec/dummy Dir[Rails.root.join('./../support/**/*.rb')].each { |f| require f } Dir[Rails.root.join('./../factories/**/*.rb')].each { |f| require f } RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods if defined?(FactoryGirl) config.include Devise::TestHelpers, :type => :controller if defined?(Devise) config.include Rails.application.routes.url_helpers config.use_transactional_fixtures = true if defined?(ActiveRecord) config.infer_base_class_for_anonymous_controllers = false config.order = 'random' config.treat_symbols_as_metadata_keys_with_true_values = true config.run_all_when_everything_filtered = true config.filter_run :focus config.before(:each) do I18n.locale = :en end config.after(:each) do Timecop.return end end
require 'rspec/rails' require 'shoulda-matchers' require 'timecop' # this seems to be required for the CI to work properly ENV['TZ'] = 'Europe/London' Time.zone = 'London' # path relative to the Dummy app, which is by convention at spec/dummy Dir[Rails.root.join('./../support/**/*.rb')].each { |f| require f } Dir[Rails.root.join('./../factories/**/*.rb')].each { |f| require f } RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods if defined?(FactoryGirl) config.include Devise::TestHelpers, :type => :controller if defined?(Devise) config.include Rails.application.routes.url_helpers config.use_transactional_fixtures = true if defined?(ActiveRecord) config.infer_base_class_for_anonymous_controllers = false config.order = 'random' config.treat_symbols_as_metadata_keys_with_true_values = true config.run_all_when_everything_filtered = true config.filter_run :focus config.before(:each) do I18n.locale = :en end config.after(:each) do Timecop.return end end
Add pmap reference in pod description
Pod::Spec.new do |s| s.name = "ConcurrentCollectionOperations" s.version = "0.0.2" s.summary = "Concurrent map and filter on NSArray, NSDictionary, NSSet using GCD." s.description = <<-DESC This is a set of categories for performing concurrent map and filter operations on Foundation data structures, currently NSArray, NSDictionary, NSSet. Concurrency is achieved using Grand Central Dispatch's (GCD) dispatch_apply. By default, operations are run on the default priority global concurrent queue. The operations can be performed on any concurrent queue. DESC s.homepage = "https://github.com/kastiglione/ConcurrentCollectionOperations" s.license = 'MIT' s.authors = { "Dave Lee" => "dave@kastiglione.com", "Eloy Durán" => "eloy.de.enige@gmail.com", "Mateus Armando" => "seanlilmateus@yahoo.de" } s.source = { :git => "https://github.com/kastiglione/ConcurrentCollectionOperations.git", :tag => "v#{s.version}" } s.source_files = 'ConcurrentCollectionOperations' s.requires_arc = true end
Pod::Spec.new do |s| s.name = "ConcurrentCollectionOperations" s.version = "0.0.2" s.summary = "Concurrent map and filter on NSArray, NSDictionary, NSSet using GCD." s.description = <<-DESC This is a set of categories for performing concurrent map and filter operations on Foundation data structures, currently NSArray, NSDictionary, NSSet. Concurrency is achieved using Grand Central Dispatch's (GCD) dispatch_apply. By default, operations are run on the default priority global concurrent queue. The operations can be performed on any concurrent queue. This library provides similar functionality to `pmap` as found in other languages. DESC s.homepage = "https://github.com/kastiglione/ConcurrentCollectionOperations" s.license = 'MIT' s.authors = { "Dave Lee" => "dave@kastiglione.com", "Eloy Durán" => "eloy.de.enige@gmail.com", "Mateus Armando" => "seanlilmateus@yahoo.de" } s.source = { :git => "https://github.com/kastiglione/ConcurrentCollectionOperations.git", :tag => "v#{s.version}" } s.source_files = 'ConcurrentCollectionOperations' s.requires_arc = true end
Remove hacky heroku debugging entirely
class SessionsController < ApplicationController def create auth = request.env["omniauth.auth"] if params[:email] and params[:password] puts "<<<<<------ Auth via Email" user = User.authenticate(params[:email], params[:password]) else puts "<<<<<------ Auth via Twitter" user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth) end if user if user.email.blank? and user.profile.blank? puts "<<<<<------ Creating profile from #{user} - #{user.profile}" Profile.create_with_omniauth(user.id, auth) end session[:user_id] = user.id puts "<<<<<------ Session set to User ID" redirect_to problems_path, :notice => "Logged in successfully" else flash.now[:alert] = "Invalid login/password. Try again!" render :action => 'new' end end def destroy reset_session redirect_to root_path, :notice => "You successfully logged out" end private end
class SessionsController < ApplicationController def create auth = request.env["omniauth.auth"] if params[:email] and params[:password] user = User.authenticate(params[:email], params[:password]) else user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth) end if user if user.email.blank? and user.profile.blank? Profile.create_with_omniauth(user.id, auth) end session[:user_id] = user.id redirect_to problems_path, :notice => "Logged in successfully" else flash.now[:alert] = "Invalid login/password. Try again!" render :action => 'new' end end def destroy reset_session redirect_to root_path, :notice => "You successfully logged out" end private end
Rename param to avoid mass-assignment warning
# Controller used for simple tracking with GET requests class TrackingController < ApplicationController before_filter :authenticate_with_token before_filter :find_track def track coordinate = @track.coordinates.build params coordinate.time = Time.at(params[:millis].to_i / 1000) if params[:millis] coordinate.user_id = @user.id if coordinate.save head :ok else head :unprocessable_entity end end private def authenticate_with_token @user = User.find_by_token params[:token] head :unauthorized unless @user end def find_track @track = Track.find_by_name params[:track] unless @track @track = Track.new :name => params[:track] @track.user = @user head :unprocessable_entity unless @track.save end end end
# Controller used for simple tracking with GET requests class TrackingController < ApplicationController before_filter :authenticate_with_token before_filter :find_track def track coordinate = @track.coordinates.build params coordinate.time = Time.at(params[:millis].to_i / 1000) if params[:millis] coordinate.user_id = @user.id if coordinate.save head :ok else head :unprocessable_entity end end private def authenticate_with_token @user = User.find_by_token params[:token] head :unauthorized unless @user end def find_track @track = Track.find_by_name params[:trackname] unless @track @track = Track.new :name => params[:trackname] @track.user = @user head :unprocessable_entity unless @track.save end end end
Change MxCommonColumnSet to be commentable
class MxCommonColumnSet < ActiveRecord::Base unloadable belongs_to :table_list, class_name: 'MxTableList', foreign_key: :table_list_id has_many :header_columns, class_name: 'MxCommonHeaderColumn', order: :position, dependent: :destroy has_many :footer_columns, class_name: 'MxCommonFooterColumn', order: :position, dependent: :destroy end
class MxCommonColumnSet < ActiveRecord::Base include MxCommentable unloadable belongs_to :table_list, class_name: 'MxTableList', foreign_key: :table_list_id has_many :header_columns, class_name: 'MxCommonHeaderColumn', order: :position, dependent: :destroy has_many :footer_columns, class_name: 'MxCommonFooterColumn', order: :position, dependent: :destroy end
Add a bang for extra safety reasons
class FillInDateTransition def perform entries.find_each { |entry| set_date(entry) } end private def set_date(entry) entry.update_attribute(:date, entry.created_at.to_date) end def entries Entry.where(date: nil) end end
class FillInDateTransition def perform entries.find_each { |entry| set_date(entry) } end private def set_date(entry) entry.update_attributes!(date: entry.created_at.to_date) end def entries Entry.where(date: nil) end end
Refactor EventsHelper and remove unused code.
module EventsHelper def make_event_split_id_array(event_id, splits) event_split_id_array = [] splits.each do |split| @event_split = AidStation.find_by(event_id: event_id, split_id: split.id) event_split_id_array << @event_split.id end event_split_id_array end def make_suggested_match_id_hash(efforts) id_hash = {} efforts.each do |effort| id_hash[effort.id] = effort.suggested_match.id if effort.suggested_match end id_hash end def suggested_match_count(efforts) make_suggested_match_id_hash(efforts).count end def data_status(status_int) Effort.data_statuses.key(status_int) end end
module EventsHelper def suggested_match_id_hash(efforts) efforts.select(&:suggested_match).map { |effort| [effort.id, effort.suggested_match.id] }.to_h end def suggested_match_count(efforts) suggested_match_id_hash(efforts).count end def data_status(status_int) Effort.data_statuses.key(status_int) end end
Update visually hidden text to share links
module Organisations class WhatWeDoPresenter attr_reader :org def initialize(organisation) @org = organisation end def has_share_links? org.social_media_links.present? end def share_links links = [] org.social_media_links.each do |link| links << { href: link["href"], text: link["title"], icon: link["service_type"], } end { stacked: true, brand: org.brand, links: links, } end end end
module Organisations class WhatWeDoPresenter attr_reader :org def initialize(organisation) @org = organisation end def has_share_links? org.social_media_links.present? end def share_links links = [] org.social_media_links.each do |link| links << { href: link["href"], text: link["title"], hidden_text: "Follow on", icon: link["service_type"], } end { stacked: true, brand: org.brand, links: links, } end end end
Simplify loop & counting invites
class Task::Notifications::InvitationEmail < Mutations::Command required do model :task model :current_user, class: User string :type end def execute invite_count = 0 volunteers.each do |user| next unless user.email.present? invite_count = invite_count + 1 token = Token.task_invitation.create! context: { user_id: user.id, task_id: task.id } TaskMailer.task_invitation(task, user, token).deliver_now end Task::Comments::Invited.run(task: task, message: 'invited', user: current_user, invite_count: invite_count) OpenStruct.new(volunteers: volunteers) end private def volunteers @volunteers ||= begin volunteers = (type == "circle" ? task.circle.volunteers : task.working_group.users) volunteers.active.to_a.reject { |u| u == current_user || task.volunteers.include?(u) } end end end
class Task::Notifications::InvitationEmail < Mutations::Command required do model :task model :current_user, class: User string :type end def execute invitees = volunteers.select { |user| user.email.present? } invitees.each do |user| token = Token.task_invitation.create! context: { user_id: user.id, task_id: task.id } TaskMailer.task_invitation(task, user, token).deliver_now end Task::Comments::Invited.run(task: task, message: 'invited', user: current_user, invite_count: invitees.count) OpenStruct.new(volunteers: volunteers) end private def volunteers @volunteers ||= begin volunteers = (type == "circle" ? task.circle.volunteers : task.working_group.users) volunteers.active.to_a.reject { |u| u == current_user || task.volunteers.include?(u) } end end end
Fix test/unpack_strategy/zstd for Ubuntu 22.04
# typed: false # frozen_string_literal: true require_relative "shared_examples" describe UnpackStrategy::Zstd do let(:path) { TEST_FIXTURE_DIR/"cask/container.tar.zst" } include_examples "UnpackStrategy::detect" end
# typed: false # frozen_string_literal: true require_relative "shared_examples" describe UnpackStrategy::Zstd do let(:path) { TEST_FIXTURE_DIR/"cask/container.tar.zst" } it "is correctly detected" do # UnpackStrategy.detect(path) for a .tar.XXX file returns either UnpackStrategy::Tar if # the host's tar is able to extract that compressed file or UnpackStrategy::XXX otherwise, # such as UnpackStrategy::Zstd. On macOS UnpackStrategy.detect("container.tar.zst") # returns UnpackStrategy::Zstd, and on ubuntu-22.04 it returns UnpackStrategy::Tar, # because the host's version of tar is recent enough and zstd is installed. expect(UnpackStrategy.detect(path)).to(be_a(described_class).or(be_a(UnpackStrategy::Tar))) end end
Allow configuration of multiple actions at the same time
module Arrthorizer module Rails class ControllerConfiguration Error = Class.new(Arrthorizer::ArrthorizerException) def initialize(&block) yield self rescue LocalJumpError raise Error, "No builder block provided to ContextBuilder.new" end def defaults(&block) self.defaults_block = block end def for_action(action, &block) add_action_block(action, &block) end def block_for(action) action_blocks.fetch(action) { defaults_block } end private attr_accessor :defaults_block def add_action_block(action, &block) action_blocks[action] = block end def action_blocks @action_blocks ||= HashWithIndifferentAccess.new end end end end
module Arrthorizer module Rails class ControllerConfiguration Error = Class.new(Arrthorizer::ArrthorizerException) def initialize(&block) yield self rescue LocalJumpError raise Error, "No builder block provided to ContextBuilder.new" end def defaults(&block) self.defaults_block = block end def for_action(*actions, &block) actions.each do |action| add_action_block(action, &block) end end alias_method :for_actions, :for_action def block_for(action) action_blocks.fetch(action) { defaults_block } end private attr_accessor :defaults_block def add_action_block(action, &block) action_blocks[action] = block end def action_blocks @action_blocks ||= HashWithIndifferentAccess.new end end end end
Remove a superfluous transport test.
RSpec.describe NanomsgTransport do let(:host) { 'tcp://127.0.0.1:6000' } let(:message) { SecureRandom.hex } it 'should work' do server = NanomsgTransport.server(host) { |rec| @rec = rec }.start client = NanomsgTransport.client host client.post message server.stop client.close_socket expect(@rec).to eq message end it 'should allow multiple clients' do count = 50 server = NanomsgTransport.server(host) { |req| req }.start clients = count.times.map { NanomsgTransport.client(host) } res = clients.each_with_index { |client, i| client.post i.to_s } server.stop clients.map(&:close_socket) expect(res.length).to eq 50 end end
RSpec.describe NanomsgTransport do let(:host) { 'tcp://127.0.0.1:6000' } let(:message) { SecureRandom.hex } it 'should work' do server = NanomsgTransport.server(host) { |rec| @rec = rec }.start client = NanomsgTransport.client host client.post message server.stop client.close_socket expect(@rec).to eq message end end
Remove the workaround for already fixed Rails bug
require 'active_record' require 'globalize3' module EasyGlobalize3Accessors def globalize_accessors(options = {}) # Temporary workaround for bug: https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/5522-model-classes-are-loaded-before-i18n-is-set-when-running-tests default_locales = defined?(Rails) ? Rails.configuration.i18n.available_locales : I18n.available_locales options.reverse_merge!(:locales => default_locales, :attributes => translated_attribute_names) each_attribute_and_locale(options) do |attr_name, locale| define_accessors(attr_name, locale) end end private def define_accessors(attr_name, locale) define_getter(attr_name, locale) define_setter(attr_name, locale) end def define_getter(attr_name, locale) define_method :"#{attr_name}_#{locale}" do read_attribute(attr_name, :locale => locale) end end def define_setter(attr_name, locale) define_method :"#{attr_name}_#{locale}=" do |value| write_attribute(attr_name, value, :locale => locale) end end def each_attribute_and_locale(options) options[:attributes].each do |attr_name| options[:locales].each do |locale| yield attr_name, locale end end end end ActiveRecord::Base.extend EasyGlobalize3Accessors
require 'globalize3' module EasyGlobalize3Accessors def globalize_accessors(options = {}) options.reverse_merge!(:locales => I18n.available_locales, :attributes => translated_attribute_names) each_attribute_and_locale(options) do |attr_name, locale| define_accessors(attr_name, locale) end end private def define_accessors(attr_name, locale) define_getter(attr_name, locale) define_setter(attr_name, locale) end def define_getter(attr_name, locale) define_method :"#{attr_name}_#{locale}" do read_attribute(attr_name, :locale => locale) end end def define_setter(attr_name, locale) define_method :"#{attr_name}_#{locale}=" do |value| write_attribute(attr_name, value, :locale => locale) end end def each_attribute_and_locale(options) options[:attributes].each do |attr_name| options[:locales].each do |locale| yield attr_name, locale end end end end ActiveRecord::Base.extend EasyGlobalize3Accessors
Use respond_to?(:before_filter) to make it Rails version agnostic
# -*- encoding : utf-8 -*- module Mongoid module Userstamp class Railtie < Rails::Railtie # Include Mongoid::Userstamp::User into User class, if not already done config.to_prepare do Mongoid::Userstamp.user_classes.each do |user_class| unless user_class.included_modules.include?(Mongoid::Userstamp::User) user_class.send(:include, Mongoid::Userstamp::User) end end end # Add userstamp to models where Mongoid::Userstamp was included, but # mongoid_userstamp was not explicitly called config.to_prepare do Mongoid::Userstamp.model_classes.each do |model_class| unless model_class.included_modules.include?(Mongoid::Userstamp::Model) model_class.send(:include, Mongoid::Userstamp::Model) end end end # Set current_user from controller reader method ActiveSupport.on_load :action_controller do before_action do |c| Mongoid::Userstamp.user_classes.each do |user_class| begin user_class.current = c.send(user_class.mongoid_userstamp_user.reader) rescue end end end end end end end
# -*- encoding : utf-8 -*- module Mongoid module Userstamp class Railtie < Rails::Railtie # Include Mongoid::Userstamp::User into User class, if not already done config.to_prepare do Mongoid::Userstamp.user_classes.each do |user_class| unless user_class.included_modules.include?(Mongoid::Userstamp::User) user_class.send(:include, Mongoid::Userstamp::User) end end end # Add userstamp to models where Mongoid::Userstamp was included, but # mongoid_userstamp was not explicitly called config.to_prepare do Mongoid::Userstamp.model_classes.each do |model_class| unless model_class.included_modules.include?(Mongoid::Userstamp::Model) model_class.send(:include, Mongoid::Userstamp::Model) end end end # Set current_user from controller reader method ActiveSupport.on_load :action_controller do set_current = Proc.new do |c| Mongoid::Userstamp.user_classes.each do |user_class| begin user_class.current = c.send(user_class.mongoid_userstamp_user.reader) rescue end end end if respond_to?(:before_filter) before_filter { |c| set_current.call(c)} else before_action { |c| set_current.call(c)} end end end end end
Add starred and links columns to quotes db
Sequel.migration do up do add_column :quotes, :starred, TrueClass add_column :quotes, :links, String, :text => true end down do drop_column :quotes, :starred drop_column :quotes, :links end end
Write integration tests for time zone
require 'test_helper' class TimeZoneFlowsTest < ActionDispatch::IntegrationTest # test "the truth" do # assert true # end end
require 'test_helper' class TimeZoneFlowsTest < ActionDispatch::IntegrationTest test "should get time zones" do get(timezones_path) assert_response(:success) end end
Debug scanner, please use TokenKinds.
module CodeRay module Scanners # = Debug Scanner # # Interprets the output of the Encoders::Debug encoder. class Debug < Scanner register_for :debug title 'CodeRay Token Dump Import' protected def scan_tokens encoder, options opened_tokens = [] until eos? if match = scan(/\s+/) encoder.text_token match, :space elsif match = scan(/ (\w+) \( ( [^\)\\]* ( \\. [^\)\\]* )* ) \)? /x) kind = self[1].to_sym match = self[2].gsub(/\\(.)/, '\1') unless Tokens::AbbreviationForKind.has_key? kind kind = :error match = matched end encoder.text_token match, kind elsif match = scan(/ (\w+) ([<\[]) /x) kind = self[1].to_sym opened_tokens << kind case self[2] when '<' encoder.begin_group kind when '[' encoder.begin_line kind else raise 'CodeRay bug: This case should not be reached.' end elsif !opened_tokens.empty? && match = scan(/ > /x) encoder.end_group opened_tokens.pop elsif !opened_tokens.empty? && match = scan(/ \] /x) encoder.end_line opened_tokens.pop else encoder.text_token getch, :space end end encoder.end_group opened_tokens.pop until opened_tokens.empty? encoder end end end end
module CodeRay module Scanners # = Debug Scanner # # Interprets the output of the Encoders::Debug encoder. class Debug < Scanner register_for :debug title 'CodeRay Token Dump Import' protected def scan_tokens encoder, options opened_tokens = [] until eos? if match = scan(/\s+/) encoder.text_token match, :space elsif match = scan(/ (\w+) \( ( [^\)\\]* ( \\. [^\)\\]* )* ) \)? /x) kind = self[1].to_sym match = self[2].gsub(/\\(.)/m, '\1') unless TokenKinds.has_key? kind kind = :error match = matched end encoder.text_token match, kind elsif match = scan(/ (\w+) ([<\[]) /x) kind = self[1].to_sym opened_tokens << kind case self[2] when '<' encoder.begin_group kind when '[' encoder.begin_line kind else raise 'CodeRay bug: This case should not be reached.' end elsif !opened_tokens.empty? && match = scan(/ > /x) encoder.end_group opened_tokens.pop elsif !opened_tokens.empty? && match = scan(/ \] /x) encoder.end_line opened_tokens.pop else encoder.text_token getch, :space end end encoder.end_group opened_tokens.pop until opened_tokens.empty? encoder end end end end
Fix issue with Telnet login
require 'net/telnet' module Net module Ops module Transport # class Telnet # Open a Telnet session to the specified host using net/ssh. # # @param host [String] the destination host. # @param options [Hash] # @param credentials [Hash] credentials to use to connect. def self.open(host, options, credentials) session = nil session = Net::Telnet.new('Host' => host, 'Timeout' => options[:timeout], 'Prompt' => options[:prompt]) session.cmd('String' => credentials[:username], 'Match' => /.+assword.+/) session.cmd(credentials[:password]) return session rescue Errno::ECONNREFUSED => e session = nil rescue Net::OpenTimeout => e session = nil rescue Exception => e session = nil return session end end end end end
require 'net/telnet' module Net module Ops module Transport # class Telnet # Open a Telnet session to the specified host using net/ssh. # # @param host [String] the destination host. # @param options [Hash] # @param credentials [Hash] credentials to use to connect. def self.open(host, options, credentials) session = nil session = Net::Telnet.new('Host' => host, 'Timeout' => options[:timeout], 'Prompt' => options[:prompt]) output = '' session.cmd('String' => '', 'Match' => /.+/) { |c| output += c } if /[Uu]sername:/.match(output) then session.cmd('String' => credentials[:username], 'Match' => /.+/) session.cmd(credentials[:password]) end if /[Pp]assword:/.match(output) then session.cmd(credentials[:password]) end return session rescue Errno::ECONNREFUSED => e session = nil rescue Net::OpenTimeout => e session = nil rescue Exception => e session = nil return session end end end end end
Create JSON Serializer according to Riak API.
module Ork::Encryption module Serializers # Implements the {Riak::Serializer} API for the purpose of # encrypting/decrypting Ork documents as JSON. # # @see Encryption class Json # The Content-Type of the internal format def self.content_type 'application/x-json-encrypted' end # Register the serializer into Riak def self.register! Riak::Serializers[content_type] = self end # Serializes and encrypts the Ruby hash using the assigned # cipher and Content-Type. # # data - Hash representing persisted_data to serialize/encrypt. # def self.dump(data) json_attributes = data.to_json(Riak.json_options) encrypted_object = { iv: Base64.encode64(cipher.random_iv!), data: Base64.encode64(cipher.encrypt json_attributes), version: Ork::Encryption::VERSION } encrypted_object.to_json(Riak.json_options) end # Decrypts and deserializes the blob using the assigned cipher # and Content-Type. # # blob - String of the original content from Riak # def self.load(blob) encrypted_object = Riak::JSON.parse(blob) cipher.iv = Base64.decode64 encrypted_object['iv'] decoded_data = Base64.decode64 encrypted_object['data'] # this serializer now only supports the v2 (0.0.2 - 0.0.4) format Riak::JSON.parse(cipher.decrypt decoded_data) end private def self.cipher @cipher ||= Cipher.new(Ork::Encryption.encryption_config) end end end end
Update Module Proposal spec to use new title
require 'spec_helper' RSpec.feature "Module Proposal Management" do feature "Module Proposal Creation" do scenario "new module proposal" do #we need this for time fields below time = Time.now visit "/module-proposals/new" fill_in "First Name", with: "Tanner" fill_in "Last Name", with: "Jones" fill_in "Email", with: "jonesjoe@example" fill_in "University", with: "East Carolina University" fill_in "Department", with: "English" fill_in "Proposed Module Title", with: "My Module Idea" fill_in "description of the proposed content", with: "My description" fill_in "estimated start date", with: "#{time.year}-#{time.month}-#{time.day}" time += 86400 fill_in "estimated completion date", with: "#{time.year}-#{time.month}-#{time.day}" click_button "Submit Module Proposal" expect(page).to have_text("Module Proposal Received") end end end
require 'spec_helper' RSpec.feature "Module Proposal Management" do feature "Module Proposal Creation" do scenario "new module proposal" do #we need this for time fields below time = Time.now visit "/module-proposals/new" fill_in "First Name", with: "Tanner" fill_in "Last Name", with: "Jones" fill_in "Email", with: "jonesjoe@example" fill_in "University", with: "East Carolina University" fill_in "Department", with: "English" fill_in "Proposed Title", with: "My Module Idea" fill_in "description of the proposed content", with: "My description" fill_in "estimated start date", with: "#{time.year}-#{time.month}-#{time.day}" time += 86400 fill_in "estimated completion date", with: "#{time.year}-#{time.month}-#{time.day}" click_button "Submit Module Proposal" expect(page).to have_text("Module Proposal Received") end end end
Add spec for create new object with hash
require "spec_helper" module Scanny::Checks describe MassAssignmentCheck do before do @runner = Scanny::Runner.new(MassAssignmentCheck.new) @message = "Create objects without defense against mass assignment" + "can cause dangerous errors in the database" @issue = issue(:high, @message, 642) end it "reports \"User.new(params[:user])\" correctly" do @runner.should check("User.new(params[:user])").with_issue(@issue) end it "reports \"User.create(params[:user])\" correctly" do @runner.should check("User.create(params[:user])").with_issue(@issue) end it "reports \"@user.update_attributes(params[:user])\" correctly" do @runner.should check("@user.update_attributes(params[:user])").with_issue(@issue) end end end
require "spec_helper" module Scanny::Checks describe MassAssignmentCheck do before do @runner = Scanny::Runner.new(MassAssignmentCheck.new) @message = "Create objects without defense against mass assignment" + "can cause dangerous errors in the database" @issue = issue(:high, @message, 642) end it "reports \"User.new(params[:user])\" correctly" do @runner.should check("User.new(params[:user])").with_issue(@issue) end it "reports \"User.new(:email => params[:input])\" correctly" do @runner.should check("User.new(:email => params[:input])").with_issue(@issue) @runner.should check("User.new(params[:input] => :value)").without_issues end it "reports \"User.create(params[:user])\" correctly" do @runner.should check("User.create(params[:user])").with_issue(@issue) end it "reports \"@user.update_attributes(params[:user])\" correctly" do @runner.should check("@user.update_attributes(params[:user])").with_issue(@issue) end end end
Update data_encryption_key_id foreign key to bigint
class ChangeDataEncryptionKeyIdToBigint < ActiveRecord::Migration[6.0] def up change_column :encrypted_fields, :data_encryption_key_id, :bigint end def down change_column :encrypted_fields, :data_encryption_key_id, :integer end end
Set requried ruby version to 1.9+
# -*- encoding: utf-8 -*- require File.expand_path('../lib/snoo/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Jeff Sandberg"] gem.email = ["paradox460@gmail.com"] gem.description = %q{Snoo is yet another reddit API wrapper. I wrote it because I tried all the other ones, and they were either too difficult to use, too cumbersome, or obsolete. This is designed to be comprehensive, but if you see something its missing, let me know!} gem.summary = %q{A simple reddit api wrapper. ALPHA} gem.homepage = "http://paradox.gd" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "snoo" gem.require_paths = ["lib"] gem.version = Snoo::VERSION ['httparty'].each do |dependency| gem.add_runtime_dependency dependency end end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/snoo/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Jeff Sandberg"] gem.email = ["paradox460@gmail.com"] gem.description = %q{Snoo is yet another reddit API wrapper. I wrote it because I tried all the other ones, and they were either too difficult to use, too cumbersome, or obsolete. This is designed to be comprehensive, but if you see something its missing, let me know!} gem.summary = %q{A simple reddit api wrapper. ALPHA} gem.homepage = "http://paradox.gd" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "snoo" gem.require_paths = ["lib"] gem.version = Snoo::VERSION gem.required_ruby_version = '>= 1.9' ['httparty'].each do |dependency| gem.add_runtime_dependency dependency end ['rspec'].each do |dependency| gem.add_development_dependency dependency end end
Use lower() in index for urls
class AddSearchIndexes < ActiveRecord::Migration[5.1] def up execute <<-SQL CREATE EXTENSION pg_trgm; CREATE INDEX notes_text_gin on notes using GIN(to_tsvector('english', text)); CREATE INDEX notes_title_gin on notes using GIN(to_tsvector('english', title)); CREATE INDEX url_entries_url on url_entries using GIN(url gin_trgm_ops); SQL end def down %w(notes_text_gin notes_title_gin url_entries_url).each do |index| remove_index index end end end
class AddSearchIndexes < ActiveRecord::Migration[5.1] def up execute <<-SQL CREATE EXTENSION IF NOT EXISTS pg_trgm; CREATE INDEX notes_text_gin on notes using GIN(to_tsvector('english', text)); CREATE INDEX notes_title_gin on notes using GIN(to_tsvector('english', title)); CREATE INDEX url_entries_url on url_entries using GIN(lower(url) gin_trgm_ops); SQL end def down remove_index :notes, name: 'notes_text_gin' remove_index :notes, name: 'notes_title_gin' remove_index :url_entries, name: 'url_entries_url' end end
Sort people on welcome controller
module GobiertoPeople class WelcomeController < GobiertoPeople::ApplicationController include PoliticalGroupsHelper before_action :check_active_submodules def index @people = current_site.people.active.politician.government.last(10) @posts = current_site.person_posts.active.sorted.last(10) @political_groups = get_political_groups @home_text = load_home_text set_events end private def check_active_submodules if active_submodules.size == 1 redirect_to submodule_path_for(active_submodules.first) end end def set_events @events = GobiertoCalendars::Event.by_site(current_site).person_events.by_person_party(Person.parties[:government]).limit(10) @events = @events.upcoming.sorted if @events.empty? @no_upcoming_events = true @events = @events.past.sorted_backwards end end def load_home_text current_site.gobierto_people_settings && current_site.gobierto_people_settings.send("home_text_#{I18n.locale}") end end end
module GobiertoPeople class WelcomeController < GobiertoPeople::ApplicationController include PoliticalGroupsHelper before_action :check_active_submodules def index @people = current_site.people.active.politician.government.sorted.last(10) @posts = current_site.person_posts.active.sorted.last(10) @political_groups = get_political_groups @home_text = load_home_text set_events end private def check_active_submodules if active_submodules.size == 1 redirect_to submodule_path_for(active_submodules.first) end end def set_events @events = GobiertoCalendars::Event.by_site(current_site).person_events.by_person_party(Person.parties[:government]).limit(10) @events = @events.upcoming.sorted if @events.empty? @no_upcoming_events = true @events = @events.past.sorted_backwards end end def load_home_text current_site.gobierto_people_settings && current_site.gobierto_people_settings.send("home_text_#{I18n.locale}") end end end
Clean up digest migration script
# Encoding: utf-8 # Change hash to digest class ChangeHashToDigest < ActiveRecord::Migration def self.up rename_column :submissions, :hash, :digest end def self.down rename_column :submissions, :digest, :hash end end
# Encoding: utf-8 # Change hash to digest class ChangeHashToDigest < ActiveRecord::Migration def self.up rename_column :submissions, :hash, :digest end def self.down rename_column :submissions, :digest, :hash end end
Improve the query of unfetched pixiv cards
# frozen_string_literal: true class PixivCardUpdateWorker include Sidekiq::Worker sidekiq_options queue: 'pull', retry: false def perform(status_id) status = Status.find(status_id) unfetched_pixiv_cards = status.pixiv_cards.reject(&:image_url?) return if unfetched_pixiv_cards.empty? unfetched_pixiv_cards.each do |pixiv_card| begin pixiv_card.fetch_image_url pixiv_card.save! pixiv_card.destroy unless pixiv_card.image_url? rescue OpenURI::HTTPError, ActiveRecord::RecordInvalid pixiv_card.destroy end end end end
# frozen_string_literal: true class PixivCardUpdateWorker include Sidekiq::Worker sidekiq_options queue: 'pull', retry: false def perform(status_id) status = Status.find(status_id) unfetched_pixiv_cards = status.pixiv_cards.where(image_url: nil) return if unfetched_pixiv_cards.empty? unfetched_pixiv_cards.each do |pixiv_card| begin pixiv_card.fetch_image_url pixiv_card.save! pixiv_card.destroy unless pixiv_card.image_url? rescue OpenURI::HTTPError, ActiveRecord::RecordInvalid pixiv_card.destroy end end end end
Add active link to menu
module BlueberryCMS module MenusHelper def render_menu(slug) menu = BlueberryCMS::Menu.find_by(slugs: slug) safe_join(menu_links(menu.links)) if menu.links.any? end private def link(link) if link.page link_to link.page.name, anchored_link(link.page.to_path, link.anchor.presence), class: link.css_class.presence else link_to link.name, anchored_link(link.url, link.anchor.presence), class: link.css_class.presence end end def menu_links(links) links.map do |link| content_tag(:li, link(link)) end end def anchored_link(link, anchor) [link, anchor.presence].compact.join('#') end end end
module BlueberryCMS module MenusHelper def render_menu(slug) menu = BlueberryCMS::Menu.find_by(slugs: slug) safe_join(menu_links(menu.links)) if menu.links.any? end private def link(link) if link.page active_link_to link.page.name, anchored_link(link.page.to_path, link.anchor.presence), class: link.css_class.presence, active: :exclusive else active_link_to link.name, anchored_link(link.url, link.anchor.presence), class: link.css_class.presence, active: :exclusive end end def menu_links(links) links.map do |link| content_tag(:li, link(link)) end end def anchored_link(link, anchor) [link, anchor.presence].compact.join('#') end end end
Fix statement so setting dotenv_role works
Capistrano::Configuration.instance(:must_exist).load do _cset(:dotenv_path){ "#{shared_path}/.env" } symlink_args = (role = fetch(:dotenv_role, nil) ? {:roles => role} : {}) namespace :dotenv do desc "Symlink shared .env to current release" task :symlink, symlink_args do run "ln -nfs #{dotenv_path} #{release_path}/.env" end end end
Capistrano::Configuration.instance(:must_exist).load do _cset(:dotenv_path){ "#{shared_path}/.env" } symlink_args = (role = fetch(:dotenv_role, nil)) ? {:roles => role} : {} namespace :dotenv do desc "Symlink shared .env to current release" task :symlink, symlink_args do run "ln -nfs #{dotenv_path} #{release_path}/.env" end end end
Test address should respond to directions
require 'spec_helper' describe Address do subject(:address) { Fabricate.build(:address) } it { should respond_to(:sponsor) } it { should respond_to(:flat) } it { should respond_to(:street) } it { should respond_to(:postal_code) } end
require 'spec_helper' describe Address do subject(:address) { Fabricate.build(:address) } it { should respond_to(:sponsor) } it { should respond_to(:flat) } it { should respond_to(:street) } it { should respond_to(:city) } it { should respond_to(:latitude) } it { should respond_to(:longitude) } it { should respond_to(:postal_code) } it { should respond_to(:directions) } end
Add script & script type in mocks for advanced usage.
class CreateDuckrailsMocks < ActiveRecord::Migration def change create_table :mocks do |t| t.string :name, null: false t.text :description t.integer :status, null: false t.string :content_type, null: false t.string :method, null: false t.string :route_path, null: false t.string :body_type t.text :body_content t.timestamps null: false end add_index :mocks, :route_path, unique: true add_index :mocks, :name, unique: true end end
class CreateDuckrailsMocks < ActiveRecord::Migration def change create_table :mocks do |t| t.string :name, null: false t.text :description t.integer :status, null: false t.string :content_type, null: false t.string :method, null: false t.string :route_path, null: false t.string :body_type t.text :body_content t.string :script_type t.text :script t.timestamps null: false end add_index :mocks, :route_path, unique: true add_index :mocks, :name, unique: true end end
Add .rb extension to generated migration file
require 'rails/generators' require 'rails/generators/migration' module Markable class MigrationGenerator < Rails::Generators::Base include Rails::Generators::Migration desc "Generates migration for Mark model" def self.orm Rails::Generators.options[:rails][:orm] end def self.source_root File.join(File.dirname(__FILE__), 'templates', (orm.to_s unless orm.class.eql?(String)) ) end def self.orm_has_migration? [:active_record].include? orm end def self.next_migration_number(dirname) if ActiveRecord::Base.timestamped_migrations migration_number = Time.now.utc.strftime("%Y%m%d%H%M%S").to_i migration_number += 1 migration_number.to_s else "%.3d" % (current_migration_number(dirname) + 1) end end def create_migration_file if self.class.orm_has_migration? migration_template 'migration.rb', 'db/migrate/markable_migration' end end end end
require 'rails/generators' require 'rails/generators/migration' module Markable class MigrationGenerator < Rails::Generators::Base include Rails::Generators::Migration desc "Generates migration for Mark model" def self.orm Rails::Generators.options[:rails][:orm] end def self.source_root File.join(File.dirname(__FILE__), 'templates', (orm.to_s unless orm.class.eql?(String)) ) end def self.orm_has_migration? [:active_record].include? orm end def self.next_migration_number(dirname) if ActiveRecord::Base.timestamped_migrations migration_number = Time.now.utc.strftime("%Y%m%d%H%M%S").to_i migration_number += 1 migration_number.to_s else "%.3d" % (current_migration_number(dirname) + 1) end end def create_migration_file if self.class.orm_has_migration? migration_template 'migration.rb', 'db/migrate/markable_migration.rb' end end end end
Refactor a bit placeholder for mapping input (text only)
module SimpleForm module Inputs # Uses MapType to handle basic input types. class MappingInput < Base extend MapType map_type :password, :to => :password_field map_type :text, :to => :text_area map_type :file, :to => :file_field def input @builder.send(input_method, attribute_name, input_html_options) end def input_html_options input_options = super input_options[:placeholder] ||= placeholder if has_placeholder? and text? input_options end private def input_method self.class.mappings[input_type] or raise("Could not find method for #{input_type.inspect}") end def text? input_type == :text end end end end
module SimpleForm module Inputs # Uses MapType to handle basic input types. class MappingInput < Base extend MapType map_type :password, :to => :password_field map_type :text, :to => :text_area map_type :file, :to => :file_field def input @builder.send(input_method, attribute_name, input_html_options) end def input_html_options input_options = super input_options[:placeholder] ||= placeholder if has_placeholder? input_options end private def input_method self.class.mappings[input_type] or raise("Could not find method for #{input_type.inspect}") end def has_placeholder? text? && super end def text? input_type == :text end end end end
Disable SQL logging when setting user API token
require 'open-uri' class AuthenticationController < ApplicationController before_action :authenticate_user! def status puts AppConfig @config = AppConfig["stack_exchange"] end def redirect_target config = AppConfig["stack_exchange"] request_params = { "client_id" => config["client_id"], "client_secret" => config["client_secret"], "code" => params[:code], "redirect_uri" => config["redirect_uri"] } resp = Net::HTTP.post_form(URI.parse('https://stackexchange.com/oauth/access_token'), request_params) # Possibly fragile, but I *think* it's fine token = nil begin token = resp.body.scan(/access_token=(.*)&/).first.first rescue end puts access_token_info = JSON.parse(open("https://api.stackexchange.com/2.2/access-tokens/#{token}?key=#{config["key"]}").read)["items"][0] puts current_user.stack_exchange_account_id = access_token_info["account_id"] current_user.update_chat_ids begin current_user.api_token = token if access_token_info["scope"].include? "write_access" rescue end current_user.save! redirect_to authentication_status_path end end
require 'open-uri' class AuthenticationController < ApplicationController before_action :authenticate_user! def status puts AppConfig @config = AppConfig["stack_exchange"] end def redirect_target config = AppConfig["stack_exchange"] request_params = { "client_id" => config["client_id"], "client_secret" => config["client_secret"], "code" => params[:code], "redirect_uri" => config["redirect_uri"] } resp = Net::HTTP.post_form(URI.parse('https://stackexchange.com/oauth/access_token'), request_params) # Possibly fragile, but I *think* it's fine token = nil begin token = resp.body.scan(/access_token=(.*)&/).first.first rescue end puts access_token_info = JSON.parse(open("https://api.stackexchange.com/2.2/access-tokens/#{token}?key=#{config["key"]}").read)["items"][0] puts current_user.stack_exchange_account_id = access_token_info["account_id"] current_user.update_chat_ids begin current_user.api_token = token if access_token_info["scope"].include? "write_access" rescue end # temporarily disable SQL logging. http://stackoverflow.com/a/7760140/1849664 old_logger = ActiveRecord::Base.logger ActiveRecord::Base.logger = nil current_user.save! ActiveRecord::Base.logger = old_logger redirect_to authentication_status_path end end
Revert "Use existing Gem name."because it forces the user to pass a different :require option.
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = "actionmailer-with-request" s.version = "0.3.0" s.platform = Gem::Platform::RUBY s.authors = "Simone Carletti" s.email = "weppos@weppos.net" s.homepage = "http://github.com/weppos/actionmailer_with_request" s.summary = "Let's ActionMailer know about the website." s.description = "Let's ActionMailer know about the request context to avoid having to set a number of defaults manually." s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_dependency "rails", ">= 3" s.rdoc_options << "--main" << "README" end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = "actionmailer_with_request" s.version = "0.3.0" s.platform = Gem::Platform::RUBY s.authors = "Simone Carletti" s.email = "weppos@weppos.net" s.homepage = "http://github.com/weppos/actionmailer_with_request" s.summary = "Let's ActionMailer know about the website." s.description = "Let's ActionMailer know about the request context to avoid having to set a number of defaults manually." s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_dependency "rails", ">= 3" s.rdoc_options << "--main" << "README" end
Add .pre for next release
module EY module Serverside class Adapter VERSION = "2.0.5" # For backwards compatibility, the serverside version default will be maintained until 2.1 # It is recommended that you supply a serverside_version to engineyard-serverside-adapter # rather than relying on the default version here. This default will go away soon. ENGINEYARD_SERVERSIDE_VERSION = ENV['ENGINEYARD_SERVERSIDE_VERSION'] || "2.0.1" end end end
module EY module Serverside class Adapter VERSION = "2.0.6.pre" # For backwards compatibility, the serverside version default will be maintained until 2.1 # It is recommended that you supply a serverside_version to engineyard-serverside-adapter # rather than relying on the default version here. This default will go away soon. ENGINEYARD_SERVERSIDE_VERSION = ENV['ENGINEYARD_SERVERSIDE_VERSION'] || "2.0.1" end end end
Remove explicit (and unnecessary) `nil` from Etc.groupname and Etc.username
require 'etc' Etc.instance_eval do def groupname(gid) Etc.group { |e| return e.name if gid == e.gid } nil end def username(uid) Etc.passwd { |e| return e.name if uid == e.uid } nil end end
require 'etc' Etc.instance_eval do def groupname(gid) Etc.group { |e| return e.name if gid == e.gid } end def username(uid) Etc.passwd { |e| return e.name if uid == e.uid } end end
Rewrite query to remove watcher duplicates in reinforcewatcheruniqueness migration.
class Reinforcewatcheruniqueness < ActiveRecord::Migration def self.up remove_index :watchers, {:name => 'uniqueness_index'} Watcher.connection.execute <<-EOF DELETE #{Watcher.table_name} FROM #{Watcher.table_name} LEFT OUTER JOIN ( SELECT MIN(id) as id, user_id, watchable_id, watchable_type FROM #{Watcher.table_name} GROUP BY user_id, watchable_id, watchable_type) as KeepRows ON #{Watcher.table_name}.id = KeepRows.id WHERE KeepRows.id IS NULL EOF add_index :watchers, [:user_id, :watchable_id, :watchable_type], :name => 'watchers_uniqueness_index', :unique => true end def self.down remove_index :watchers, {:name => 'watchers_uniqueness_index'} add_index :watchers, [:user_id, :watchable_id, :watchable_type], :name => 'uniqueness_index', :unique => true end end
class Reinforcewatcheruniqueness < ActiveRecord::Migration def self.up if index_exists?(:watchers, [:user_id, :watchable_id, :watchable_type], :name => 'watchers_uniqueness_index', :unique => true) remove_index :watchers, {:name => 'watchers_uniqueness_index'} end Watcher.connection.execute <<-EOF DELETE #{Watcher.table_name} FROM #{Watcher.table_name}, (SELECT MAX(id) as dupid, COUNT(id) as dupcnt, user_id, watchable_id, watchable_type FROM #{Watcher.table_name} GROUP BY user_id, watchable_id, watchable_type HAVING dupcnt > 1) as duplicates WHERE #{Watcher.table_name}.id = duplicates.dupid EOF unless index_exists?(:watchers, [:user_id, :watchable_id, :watchable_type], :name => 'watchers_uniqueness_index', :unique => true) add_index :watchers, [:user_id, :watchable_id, :watchable_type], :name => 'watchers_uniqueness_index', :unique => true end end def self.down unless index_exists?(:watchers, [:user_id, :watchable_id, :watchable_type], :name => 'watchers_uniqueness_index', :unique => true) add_index :watchers, [:user_id, :watchable_id, :watchable_type], :name => 'watchers_uniqueness_index', :unique => true end end end
Make triple crown eligible winner / no winner logic readable
module BaseballStats module Calculators class TripleCrownEligible include Calculators def calculate al_winner = find_winner(AMERICAN_LEAGUE) nl_winner = find_winner(NATIONAL_LEAGUE) { 'American League' => al_winner[PLAYER_ID], 'National League' => nl_winner[PLAYER_ID] } end private def find_winner(league) players = select_eligible_players(league) max_RBI = get_max_stat(players, RBI) max_HR = get_max_stat(players, HOMERUNS) rbi_matches = players.select { |p| p[RBI] == max_RBI } hr_matches = rbi_matches.select { |p| p[HOMERUNS] == max_HR } hr_matches.max_by { |p| batting_average(p) } || { PLAYER_ID => 0 } end def batting_average(stats) ImprovedBattingAverage.formula(stats) end def get_max_stat(collection, stat) collection.max_by { |p| p[stat] }[stat] rescue 0 end def select_eligible_players(league) eligible_players.select { |p| p[LEAGUE] == league } end def eligible_players select_from_csv do |player| player[AT_BATS] > 399 && player[YEAR_ID] == year end end end end end
module BaseballStats module Calculators class TripleCrownEligible include Calculators def calculate al_winner = find_winner(AMERICAN_LEAGUE) nl_winner = find_winner(NATIONAL_LEAGUE) { 'American League' => al_winner[PLAYER_ID], 'National League' => nl_winner[PLAYER_ID] } end private def find_winner(league) players = select_eligible_players(league) max_RBI = get_max_stat(players, RBI) max_HR = get_max_stat(players, HOMERUNS) rbi_matches = players.select { |p| p[RBI] == max_RBI } hr_matches = rbi_matches.select { |p| p[HOMERUNS] == max_HR } winner = hr_matches.max_by { |p| batting_average(p) } winner || no_winner end def no_winner { PLAYER_ID => 0 } end def batting_average(stats) ImprovedBattingAverage.formula(stats) end def get_max_stat(collection, stat) collection.max_by { |p| p[stat] }[stat] rescue 0 end def select_eligible_players(league) eligible_players.select { |p| p[LEAGUE] == league } end def eligible_players select_from_csv do |player| player[AT_BATS] > 399 && player[YEAR_ID] == year end end end end end
Rename 'scores' table to 'answers' table, and rename 'score' field to 'answer' field
class RenameScoresTableToAnswers < ActiveRecord::Migration def self.up rename_table :scores, :answers rename_column :answers, :score, :answer end def self.down rename_column :answers, :answer, :score rename_table :answers, :scores end end