Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix for new_cop rake task
# frozen_string_literal: true module RuboCop module Cop class Generator # A class that injects a require directive into the root RuboCop file. # It looks for other directives that require files in the same (cop) # namespace and injects the provided one in alpha class ConfigurationInjector TEMPLATE = <<-YAML.strip_indent %<badge>s: Description: 'TODO: Write a description of the cop.' Enabled: true VersionAdded: '%<version_added>s' YAML def initialize(configuration_file_path:, badge:, version_added:) @configuration_file_path = configuration_file_path @badge = badge @version_added = version_added @output = output end def inject configuration_entries.insert(find_target_line, new_configuration_entry) File.write(configuration_file_path, configuration_entries.join) yield if block_given? end private attr_reader :configuration_file_path, :badge, :version_added, :output def configuration_entries @configuration_entries ||= File.readlines(configuration_file_path) end def new_configuration_entry format(TEMPLATE, badge: badge, version_added: version_added) end def find_target_line configuration_entries.find.with_index do |line, index| next if comment?(line) break index if badge.to_s < line end end def comment?(yaml) yaml =~ /^[\s#]/ end end end end end
# frozen_string_literal: true module RuboCop module Cop class Generator # A class that injects a require directive into the root RuboCop file. # It looks for other directives that require files in the same (cop) # namespace and injects the provided one in alpha class ConfigurationInjector TEMPLATE = <<-YAML.strip_indent %<badge>s: Description: 'TODO: Write a description of the cop.' Enabled: true VersionAdded: '%<version_added>s' YAML def initialize(configuration_file_path:, badge:, version_added:) @configuration_file_path = configuration_file_path @badge = badge @version_added = version_added @output = output end def inject configuration_entries.insert(find_target_line, new_configuration_entry) File.write(configuration_file_path, configuration_entries.join) yield if block_given? end private attr_reader :configuration_file_path, :badge, :version_added, :output def configuration_entries @configuration_entries ||= File.readlines(configuration_file_path) end def new_configuration_entry format(TEMPLATE, badge: badge, version_added: version_added) end def find_target_line last_line = 0 configuration_entries.find.with_index do |line, index| next if comment?(line) last_line = index break index if badge.to_s < line end last_line end def comment?(yaml) yaml =~ /^[\s#]/ end end end end end
Add class method for fetching latest SimpleDesktop
require 'nokogiri' require 'desktop/http' require 'desktop/image' module Desktop class SimpleDesktops def latest_image @latest_image ||= Image.new(thumbnail.match(full_image_regex).to_s) end private def url 'http://simpledesktops.com' end def html Nokogiri::HTML HTTP.get(url).body end def thumbnail html.css('.desktop a img').first['src'] end # http://rubular.com/r/UHYgmPJoQM def full_image_regex /http.*?png/ end end end
require 'nokogiri' require 'desktop/http' require 'desktop/image' module Desktop class SimpleDesktops def self.latest_image self.new.latest_image end def latest_image @latest_image ||= Image.new(thumbnail.match(full_image_regex).to_s) end private def url 'http://simpledesktops.com' end def html Nokogiri::HTML HTTP.get(url).body end def thumbnail html.css('.desktop a img').first['src'] end # http://rubular.com/r/UHYgmPJoQM def full_image_regex /http.*?png/ end end end
Fix for PR 945745. Update switch style value for QFX device based on Junos software version to either VLAN_L2NG or VLAN
Junos::Ez::Facts::Keeper.define( :switch_style ) do |ndev, facts| f_persona = uses :personality facts[:switch_style] = case f_persona when :SWITCH, :SRX_BRANCH case facts[:hardwaremodel] when /junosv-firefly/i :NONE when /^(ex9)|(ex43)/i :VLAN_L2NG else :VLAN end when :MX, :SRX_HIGHEND :BRIDGE_DOMAIN else :NONE end end
Junos::Ez::Facts::Keeper.define( :switch_style ) do |ndev, facts| f_persona = uses :personality facts[:switch_style] = case f_persona when :SWITCH, :SRX_BRANCH case facts[:hardwaremodel] when /junosv-firefly/i :NONE when /^(ex9)|(ex43)/i :VLAN_L2NG when /^(qfx5)|(qfx3)/i if facts[:version][0..3].to_f >= 13.2 :VLAN_L2NG else :VLAN end else :VLAN end when :MX, :SRX_HIGHEND :BRIDGE_DOMAIN else :NONE end end
Install unzip only on linux
package 'unzip' unless platform?('windows') dirs = %w(config drivers server) dirs.push('bin', 'log') if platform?('windows') dirs.each do |dir| directory "#{selenium_home}/#{dir}" do recursive true action :create end end
package 'unzip' unless platform?('windows', 'mac_os_x') dirs = %w(config drivers server) dirs.push('bin', 'log') if platform?('windows') dirs.each do |dir| directory "#{selenium_home}/#{dir}" do recursive true action :create end end
Change event_callback to eliminate connection argument
#-- # Copyright (C)2007 Tony Arcieri # You can redistribute this under the terms of the Ruby license # See file LICENSE for details #++ require File.dirname(__FILE__) + '/../rev' module Rev class Watcher # Use an alternate watcher with the attach/detach/enable/disable methods # if it is presently assigned. This is useful if you are waiting for # an event to occur before the current watcher can be used in earnest, # such as making an outgoing TCP connection. def self.watcher_delegate(proxy_var) %w{attach detach enable disable}.each do |method| module_eval <<-EOD def #{method}(*args) if #{proxy_var} #{proxy_var}.#{method}(*args) return self end super end EOD end end # Define callbacks whose behavior can be changed on-the-fly per instance. # This is done by giving a block to the callback method, which is captured # as a proc and stored for later. If the method is called without a block, # the stored block is executed if present, otherwise it's a noop. def self.event_callback(*methods) methods.each do |method| module_eval <<-EOD def #{method}(*args, &block) if block @#{method}_callback = block return end @#{method}_callback.(*([self] + args)) if @#{method}_callback end EOD end end end end
#-- # Copyright (C)2007 Tony Arcieri # You can redistribute this under the terms of the Ruby license # See file LICENSE for details #++ require File.dirname(__FILE__) + '/../rev' module Rev class Watcher # Use an alternate watcher with the attach/detach/enable/disable methods # if it is presently assigned. This is useful if you are waiting for # an event to occur before the current watcher can be used in earnest, # such as making an outgoing TCP connection. def self.watcher_delegate(proxy_var) %w{attach detach enable disable}.each do |method| module_eval <<-EOD def #{method}(*args) if #{proxy_var} #{proxy_var}.#{method}(*args) return self end super end EOD end end # Define callbacks whose behavior can be changed on-the-fly per instance. # This is done by giving a block to the callback method, which is captured # as a proc and stored for later. If the method is called without a block, # the stored block is executed if present, otherwise it's a noop. def self.event_callback(*methods) methods.each do |method| module_eval <<-EOD def #{method}(*args, &block) if block @#{method}_callback = block return end instance_exec(*args, &@#{method}_callback) if @#{method}_callback end EOD end end end end
Update middleware registry for Faraday 0.9
require 'faraday_middleware/response_middleware' require 'faraday_middleware/request/encode_json' module FaradayMiddleware module MultiJson class ParseJson < FaradayMiddleware::ResponseMiddleware dependency 'multi_json' def parse(body) ::MultiJson.load(body, @options) rescue body end end class EncodeJson < FaradayMiddleware::EncodeJson dependency 'multi_json' def initialize(app, *) super(app) end def encode(data) ::MultiJson.dump data end end end end Faraday.register_middleware :response, :multi_json => FaradayMiddleware::MultiJson::ParseJson Faraday.register_middleware :request, :multi_json => FaradayMiddleware::MultiJson::EncodeJson
require 'faraday_middleware/response_middleware' require 'faraday_middleware/request/encode_json' module FaradayMiddleware module MultiJson class ParseJson < FaradayMiddleware::ResponseMiddleware dependency 'multi_json' def parse(body) ::MultiJson.load(body, @options) rescue body end end class EncodeJson < FaradayMiddleware::EncodeJson dependency 'multi_json' def initialize(app, *) super(app) end def encode(data) ::MultiJson.dump data end end end end Faraday::Response.register_middleware :multi_json => FaradayMiddleware::MultiJson::ParseJson Faraday::Request.register_middleware :multi_json => FaradayMiddleware::MultiJson::EncodeJson
Add log message for each modified file
# import some logic/helpers from lib/*.rb include NanoBox::Engine include NanoBox::Output logtap.print(bullet("Running dev-prepare hook..."), 'debug') # By this point, engine should be set in the registry engine = registry('engine') case payload[:dev_config] when 'none' logtap.print(bullet("Config 'none' detected, exiting now..."), 'debug') exit 0 when 'mount' logtap.print(bullet("Config 'mount' detected, running now..."), 'debug') # look for the 'config_files' node within the 'boxfile' payload, and # bind mount each of the entries (boxfile[:config_files] || []).each do |f| execute "mount #{f}" do command %Q(mount --bind /mnt/build/#{f} /code/#{f}) end end when 'copy' logtap.print(bullet("Config 'copy' detected, running now..."), 'debug') # copy each of the values in the 'config_files' node into the raw source (boxfile[:config_files] || []).each do |f| execute "copy #{f}" do command %Q(cp -f /mnt/build/#{f} /code/#{f}) end end else logtap.print(bullet("Config not detected, exiting now..."), 'debug') exit Hookit::Exit::ABORT end
# import some logic/helpers from lib/*.rb include NanoBox::Engine include NanoBox::Output logtap.print(bullet("Running dev-prepare hook..."), 'debug') # By this point, engine should be set in the registry engine = registry('engine') case payload[:dev_config] when 'none' logtap.print(bullet("Config 'none' detected, exiting now..."), 'debug') exit 0 when 'mount' logtap.print(bullet("Config 'mount' detected, running now..."), 'debug') # look for the 'config_files' node within the 'boxfile' payload, and # bind mount each of the entries (boxfile[:config_files] || []).each do |f| execute "mount #{f}" do logtap.print(bullet("Temporarily overwriting #{f}...")) command %Q(mount --bind /mnt/build/#{f} /code/#{f}) end end when 'copy' logtap.print(bullet("Config 'copy' detected, running now..."), 'debug') # copy each of the values in the 'config_files' node into the raw source (boxfile[:config_files] || []).each do |f| execute "copy #{f}" do logtap.print(bullet("Permanently overwriting #{f}...")) command %Q(cp -f /mnt/build/#{f} /code/#{f}) end end else logtap.print(bullet("Config not detected, exiting now..."), 'debug') exit Hookit::Exit::ABORT end
Add logout function and change error message for invalid login attempt
module Api class SessionsController < ApplicationController skip_before_action :authenticate_user_from_token! # POST /user/login def create @user = User.find_for_database_authentication(email: params[:username]) return invalid_login_attempt unless @user if @user.valid_password?(params[:password]) sign_in :user, @user render json: @user, serializer: SessionSerializer, root: nil else invalid_login_attempt end end private def invalid_login_attempt warden.custom_failure! render json: {error: t('sessions_controller.invalid_login_attempt')}, status: :unprocessable_entity end end end
module Api class SessionsController < ApplicationController skip_before_action :authenticate_user_from_token! # POST /user/login def create @user = User.find_for_database_authentication(email: params[:username]) return invalid_login_attempt unless @user if @user.valid_password?(params[:password]) sign_in :user, @user render json: @user, serializer: SessionSerializer, root: nil else invalid_login_attempt end end def destroy warden.logout render json: {} end private def invalid_login_attempt warden.custom_failure! render json: {error: ('Incorrect username/password')}, status: :unprocessable_entity end end end
Add a 404 test for top level app
require 'spec_helper' require 'rack_spec_helper' require 'tic_tac_toe/rack_shell' describe TicTacToe::RackShell do include Rack::Test::Methods def app TicTacToe::RackShell.new_shell end it 'can receive an index/root GET request' do get '/' expect(last_response).to be_successful expect(last_response.body).to include("Tic-Tac-Toe") end it 'can receive an new game GET request' do get '/new-game' expect(last_response).to be_successful expect(last_response.body).to include("<table>") end end
require 'spec_helper' require 'rack_spec_helper' require 'tic_tac_toe/rack_shell' describe TicTacToe::RackShell do include Rack::Test::Methods def app TicTacToe::RackShell.new_shell end it 'can receive an index/root GET request' do get '/' expect(last_response).to be_successful expect(last_response.body).to include("Tic-Tac-Toe") end it 'can receive an new game GET request' do get '/new-game' expect(last_response).to be_successful expect(last_response.body).to include("<table>") end it 'returns 404 for unknown routes' do get '/totally-wacky' expect(last_response).to be_not_found end end
Fix command for non-gzipped pages
module ManBook class HtmlFormatter < Formatter def convert(file_name) # pipe through gunzip if gzipped if man_page_file =~ /\.gz$/ cmd = "gunzip -c #{man_page_file} | groff -mandoc -T html > #{file_name}" else cmd = puts "groff -mandoc #{man_page_file} -T html > #{file_name}" end ManBook.logger.debug("Executing #{cmd}") execute(cmd) ManBook.logger.info "Written man page for '#{man_page}' to '#{file_name}'" end end end
module ManBook class HtmlFormatter < Formatter def convert(file_name) # pipe through gunzip if gzipped if man_page_file =~ /\.gz$/ cmd = "gunzip -c #{man_page_file} | groff -mandoc -T html > #{file_name}" else cmd = "groff -mandoc #{man_page_file} -T html > #{file_name}" end ManBook.logger.debug("Executing #{cmd}") execute(cmd) ManBook.logger.info "Written man page for '#{man_page}' to '#{file_name}'" end end end
Change API to be more flexible.
module Metacrunch class Transformer require_relative "./transformer/step" require_relative "./transformer/helper" attr_reader :source, :target, :options def initialize(source:, target:, options: {}) @source = source @target = target @options = options end def transform(step_class = nil, &block) if block_given? Step.new(self).instance_eval(&block) # TODO: Benchmark this else raise ArgumentError, "You need to provide a STEP or a block" if step_class.nil? step_class.new(self).perform end end def helper @helper ||= Helper.new(self) end def register_helper(helper_module) helper.class.send(:include, helper_module) # TODO: Benchmark this end end end
module Metacrunch class Transformer require_relative "./transformer/step" require_relative "./transformer/helper" attr_accessor :source, :target, :options def initialize(source:nil, target:nil, options: {}) @source = source @target = target @options = options end def transform(step_class = nil, &block) if block_given? Step.new(self).instance_eval(&block) # TODO: Benchmark this else raise ArgumentError, "You need to provide a STEP or a block" if step_class.nil? step_class.new(self).perform end end def helper @helper ||= Helper.new(self) end def register_helper(helper_module) raise ArgumentError, "Must be a module" unless helper_module.is_a?(Module) helper.class.send(:include, helper_module) # TODO: Benchmark this end end end
Expand CA cert test to include ca_cert property
RSpec.describe "certificates" do def get_all_cas_usages(o) return o.flat_map { |v| get_all_cas_usages(v) } if o.is_a? Array if o.is_a? Hash return o.values.flat_map { |v| get_all_cas_usages(v) } unless o.key? 'ca' # Match checks if it is a usage ("name.value") or a variable ("name") return [o['ca']] if o['ca'].match?(/[.]/) end [] end context "ca certificates" do let(:manifest) { manifest_with_defaults } let(:ca_usages) do get_all_cas_usages(manifest.fetch('.')).map do |usage| usage.gsub(/[()]/, '') # delete surrounding parens end end it "should use .ca for every usage of a ca certificate" do ca_usages.each do |ca_usage| expect(ca_usage).to match(/[.]ca$/), "Usage of CA #{ca_usage} should be cert_name.ca not ca_name.certificate, otherwise credhub rotation will fail" end end end end
RSpec.describe "certificates" do def get_all_cas_usages(o) return o.flat_map { |v| get_all_cas_usages(v) } if o.is_a? Array if o.is_a? Hash # Match checks if it is a usage ("name.value") or a variable ("name") return [o['ca']] if o['ca']&.match?(/[.]/) return [o['ca_cert']] if o['ca_cert']&.match?(/[.]/) return o.values.flat_map { |v| get_all_cas_usages(v) } end [] end context "ca certificates" do let(:manifest) { manifest_with_defaults } let(:ca_usages) do get_all_cas_usages(manifest.fetch('.')).map do |usage| usage.gsub(/[()]/, '') # delete surrounding parens end end it "should detect some ca certificate usages" do expect(ca_usages).not_to eq([]) end it "should use .ca for every usage of a ca certificate" do ca_usages.each do |ca_usage| expect(ca_usage).to match(/[.]ca$/), "Usage of CA #{ca_usage} should be cert_name.ca not ca_name.certificate, otherwise credhub rotation will fail" end end end end
Fix a test failure when svn is not installed
require "utils/svn" describe Utils do describe "#self.svn_available?" do before(:each) do described_class.clear_svn_version_cache end it "returns svn version if svn available" do expect(described_class.svn_available?).to be_truthy end end describe "#self.svn_remote_exists" do it "returns true when svn is not available" do allow(Utils).to receive(:svn_available?).and_return(false) expect(described_class.svn_remote_exists("blah")).to be_truthy end context "when svn is available" do before do allow(Utils).to receive(:svn_available?).and_return(true) end it "returns false when remote does not exist" do expect(described_class.svn_remote_exists(HOMEBREW_CACHE/"install")).to be_falsey end it "returns true when remote exists", :needs_network do remote = "http://github.com/Homebrew/install" svn = HOMEBREW_SHIMS_PATH/"scm/svn" HOMEBREW_CACHE.cd { system svn, "checkout", remote } expect(described_class.svn_remote_exists(HOMEBREW_CACHE/"install")).to be_truthy end end end end
require "utils/svn" describe Utils do describe "#self.svn_available?" do before(:each) do described_class.clear_svn_version_cache end it "returns svn version if svn available" do if File.executable? "/usr/bin/svn" expect(described_class.svn_available?).to be_truthy else expect(described_class.svn_available?).to be_falsey end end end describe "#self.svn_remote_exists" do it "returns true when svn is not available" do allow(Utils).to receive(:svn_available?).and_return(false) expect(described_class.svn_remote_exists("blah")).to be_truthy end context "when svn is available" do before do allow(Utils).to receive(:svn_available?).and_return(true) end it "returns false when remote does not exist" do expect(described_class.svn_remote_exists(HOMEBREW_CACHE/"install")).to be_falsey end it "returns true when remote exists", :needs_network do remote = "http://github.com/Homebrew/install" svn = HOMEBREW_SHIMS_PATH/"scm/svn" HOMEBREW_CACHE.cd { system svn, "checkout", remote } expect(described_class.svn_remote_exists(HOMEBREW_CACHE/"install")).to be_truthy end end end end
Switch away from PUT DELETE cause lulz HTML.
require "sinatra/base" require "httparty" require "pry" require "myhub/version" require "myhub/github" module Myhub class App < Sinatra::Base set :logging, true # Your code here ... get "/" do api = Github.new # get stuff from github erb :index, locals: { issues: stuff } end put "/issue/:id" do api = Github.new api.reopen_issue(params["id"].to_i) "Cool cool cool" end delete "/issue/:id" do api = Github.new api.close_issue(params["id"].to_i) "Cool cool cool" end run! if app_file == $0 end end
require "sinatra/base" require "httparty" require "pry" require "myhub/version" require "myhub/github" module Myhub class App < Sinatra::Base set :logging, true # Your code here ... get "/" do api = Github.new # get stuff from github erb :index, locals: { issues: stuff } end post "/issue/reopen/:id" do api = Github.new api.reopen_issue(params["id"].to_i) "Cool cool cool" end post "/issue/close/:id" do api = Github.new api.close_issue(params["id"].to_i) "Cool cool cool" end run! if app_file == $0 end end
Use the root_object instead of @line_item.
object @line_item cache [I18n.locale, @line_item] attributes *line_item_attributes node(:single_display_amount) { |li| li.single_display_amount.to_s } node(:display_amount) { |li| li.display_amount.to_s } node(:total) { |li| li.total } child :variant do extends "spree/api/variants/small" attributes :product_id child(:images => :images) { extends "spree/api/images/show" } end child :adjustments => :adjustments do extends "spree/api/adjustments/show" end
object @line_item cache [I18n.locale, root_object] attributes *line_item_attributes node(:single_display_amount) { |li| li.single_display_amount.to_s } node(:display_amount) { |li| li.display_amount.to_s } node(:total) { |li| li.total } child :variant do extends "spree/api/variants/small" attributes :product_id child(:images => :images) { extends "spree/api/images/show" } end child :adjustments => :adjustments do extends "spree/api/adjustments/show" end
Fix iOS version dependency in podspec
Pod::Spec.new do |s| s.name = "Fountain" s.version = "1.0.2" s.summary = "An open source implementation of the Fountain screenplay formatting language." s.homepage = "http://fountain.io" s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { "Nima Yousefi" => "inbox@nimayousefi.com" } s.source = { :git => "https://github.com/nyousefi/Fountain.git", :tag => "v#{s.version}" } s.source_files = "Fountain/FN*.{h,m}", "Fountain/Fountain*.{h,m}", "Fountain/FastFountainParser.{h,m}", "RegexKitLite/*.{h,m}" s.frameworks = 'cocoa' s.libraries = 'icucore' s.ios.deployment_target = '7.0' s.osx.deployment_target = '10.7' end
Pod::Spec.new do |s| s.name = "Fountain" s.version = "1.0.2" s.summary = "An open source implementation of the Fountain screenplay formatting language." s.homepage = "http://fountain.io" s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { "Nima Yousefi" => "inbox@nimayousefi.com" } s.source = { :git => "https://github.com/nyousefi/Fountain.git", :tag => "v#{s.version}" } s.source_files = "Fountain/FN*.{h,m}", "Fountain/Fountain*.{h,m}", "Fountain/FastFountainParser.{h,m}", "RegexKitLite/*.{h,m}" s.frameworks = 'cocoa' s.libraries = 'icucore' s.ios.deployment_target = '6.0' s.osx.deployment_target = '10.7' end
Add "homepage" (github repo page) to gemspec
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'vagrant-reverse-proxy/version' Gem::Specification.new do |spec| spec.name = "vagrant-reverse-proxy" spec.version = VagrantPlugins::ReverseProxy::VERSION spec.authors = ["Peter Bex"] spec.email = ["peter@codeyellow.nl"] spec.summary = %q{A vagrant plugin that adds reverse proxies for your VMs} spec.description = %q{This plugin manages reverse proxy configuration (currently nginx-only) so you can reach your Vagrant VM's web servers externally without having to set up bridge networking.} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'vagrant-reverse-proxy/version' Gem::Specification.new do |spec| spec.name = "vagrant-reverse-proxy" spec.version = VagrantPlugins::ReverseProxy::VERSION spec.authors = ["Peter Bex"] spec.email = ["peter@codeyellow.nl"] spec.summary = %q{A vagrant plugin that adds reverse proxies for your VMs} spec.description = %q{This plugin manages reverse proxy configuration (currently nginx-only) so you can reach your Vagrant VM's web servers externally without having to set up bridge networking.} spec.homepage = "https://github.com/CodeYellowBV/vagrant-reverse-proxy" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" end
Make changes to @fallback stick.
module Rack class Offline class Config attr_reader :cached, :network, :fallback def initialize(root, &block) @cached = [] @network = [] @fallback = {} @root = root instance_eval(&block) if block_given? end def cache(*names) @cached.concat(names) end def network(*names) @network.concat(names) end def fallback(hash = {}) @fallback.merge(hash) end def root @root end end end end
module Rack class Offline class Config attr_reader :cached, :network, :fallback def initialize(root, &block) @cached = [] @network = [] @fallback = {} @root = root instance_eval(&block) if block_given? end def cache(*names) @cached.concat(names) end def network(*names) @network.concat(names) end def fallback(hash = {}) @fallback.merge!(hash) end def root @root end end end end
Use query params for non-bodied requests.
class Sliver::Rails::Action include Sliver::Action def self.expose(name, options = {}, &block) define_method "#{name}_without_caching", &block define_method(name) do @exposed_methods ||= {} @exposed_methods[name] ||= send "#{name}_without_caching" end private "#{name}_without_caching" unless options[:public] private name unless options[:public] locals << name end def self.locals @locals ||= [] end def self.template @template end def self.use_template(template) @template = template end def call # end def locals self.class.locals.inject({}) do |hash, name| hash[name] = send name hash end end private def content_type_header environment['Content-Type'] || environment['HTTP_CONTENT_TYPE'] || environment['CONTENT_TYPE'] end def content_types content_type_header.split(/;\s?/) end def json_request? content_types.include? 'application/json' end def params ActionController::Parameters.new request_params end def request_params @request_params ||= json_request? ? JSON.parse(request.body.read) : request.params end def set_response(status, body = nil) response.status = status response.body = body unless body.nil? end end
class Sliver::Rails::Action include Sliver::Action BODIED_METHODS = %w( post put patch ) def self.expose(name, options = {}, &block) define_method "#{name}_without_caching", &block define_method(name) do @exposed_methods ||= {} @exposed_methods[name] ||= send "#{name}_without_caching" end private "#{name}_without_caching" unless options[:public] private name unless options[:public] locals << name end def self.locals @locals ||= [] end def self.template @template end def self.use_template(template) @template = template end def call # end def locals self.class.locals.inject({}) do |hash, name| hash[name] = send name hash end end private def bodied_request? BODIED_METHODS.include? environment['REQUEST_METHOD'].downcase end def content_type_header environment['Content-Type'] || environment['HTTP_CONTENT_TYPE'] || environment['CONTENT_TYPE'] end def content_types content_type_header.split(/;\s?/) end def json_request? content_types.include? 'application/json' end def params ActionController::Parameters.new request_params end def request_params @request_params ||= if bodied_request? && json_request? JSON.parse(request.body.read) else request.params end end def set_response(status, body = nil) response.status = status response.body = body unless body.nil? end end
Remove unneeded line (replaced by init_lights)
#! /usr/bin/env ruby require 'sinatra' require 'haml' class TrafficLightPiServer < Sinatra::Base def self.init_lights @@lines = Hash.new @@line_map.each_key do |line| @@lines[line] = Hash.new @@line_map[line].each_key do |light| @@lines[line][light] = 0 end end end # Put a default page get '/' do @lines = @@lines @line_map = @@line_map haml :index, :format => :html5 end # Get current status for one light/color in one line get '/:line/:color' do line = params[:line].to_i color = params[:color].to_sym pin = @@line_map[line][color] state = @@lines[line][color.to_sym] "#{pin}:#{state}" end # Set status of one light/color in one line get '/:line/:color/:state' do line = params[:line].to_i color = params[:color].to_sym state = params[:state] @@lines[line] = Hash.new unless @@lines.has_key? line @@lines[line][color] = Hash.new unless @@lines[line].has_key? color @@lines[line][color] = state pin = @@line_map[line][color.to_sym] "#{pin}:#{state}" end end
#! /usr/bin/env ruby require 'sinatra' require 'haml' class TrafficLightPiServer < Sinatra::Base def self.init_lights @@lines = Hash.new @@line_map.each_key do |line| @@lines[line] = Hash.new @@line_map[line].each_key do |light| @@lines[line][light] = 0 end end end # Put a default page get '/' do @lines = @@lines @line_map = @@line_map haml :index, :format => :html5 end # Get current status for one light/color in one line get '/:line/:color' do line = params[:line].to_i color = params[:color].to_sym pin = @@line_map[line][color] state = @@lines[line][color.to_sym] "#{pin}:#{state}" end # Set status of one light/color in one line get '/:line/:color/:state' do line = params[:line].to_i color = params[:color].to_sym state = params[:state] @@lines[line][color] = state pin = @@line_map[line][color.to_sym] "#{pin}:#{state}" end end
Create Namespace to hold mappers
require 'spec_helper' module SteppingStone describe TextMapper do def build_mapper(name) from = :"from_#{name}" to = :"to_#{name}" Module.new do extend TextMapper def_map from => to define_method(to) { to } end end context "with one mapper" do before { build_mapper(:mapper_a) } describe "#all_mappings" do it "exports mappings" do subject.all_mappings.collect(&:name).should == [:from_mapper_a] end end it "exports the helper module" it "exports hooks" end context "with many mappers" do it "exports mappings" it "exports the helper module" it "exports hooks" end end end
require 'spec_helper' module SteppingStone module TextMapper module Namespace def self.root Module.new do def self.mappers @mappers ||= [] end def self.all_mappings mappers.inject([]) do |acc, mapper| acc << mapper.mappings end.flatten end def self.extended(mapper) mapper.extend(Dsl) mappers << mapper end end end end describe Namespace do describe ".root" do it "builds a unique namespace" do ns1 = Namespace.root ns2 = Namespace.root ns1.should_not be(ns2) end it "returns a module" do Namespace.root.should be_an_instance_of(Module) end end describe "enclosing mappers within a namespace" do subject { Namespace.root } def build_mapper(name, namespace) from = :"from_#{name}" to = :"to_#{name}" Module.new do extend namespace def_map from => to define_method(to) { to } end end context "with one mapper" do before { build_mapper(:mapper_a, subject) } describe "#all_mappings" do it "exports mappings" do subject.all_mappings.collect(&:name).should == [:from_mapper_a] end end it "exports the helper module" it "exports hooks" end context "with many mappers" do before do build_mapper(:mapper_a) build_mapper(:mapper_b) end describe "#all_mappings" do xit "exports mappings" do subject.all_mappings.collect(&:name).should == [:from_mapper_a, :from_mapper_b] end end it "exports mappings" it "exports the helper module" it "exports hooks" end end end end end
Add migration for industry CCS slider
require 'etengine/scenario_migration' class CcsSlider < ActiveRecord::Migration[5.2] include ETEngine::ScenarioMigration NEW_INDUSTRY_INPUTS = %w[ share_of_industry_chemicals_fertilizers_captured_combustion_co2 share_of_industry_steel_captured_co2 share_of_industry_other_paper_captured_co2 share_of_industry_other_food_captured_co2 share_of_industry_chemicals_fertilizers_captured_processes_co2 ].freeze def up migrate_scenarios do |scenario| if scenario.user_values.key?('industry_ccs_in_industry') old_value = scenario.user_values['industry_ccs_in_industry'] NEW_INDUSTRY_INPUTS.each do |key| scenario.user_values[key] = old_value end end end end end
Fix call Module.prepend for ruby-2.0
module ActiveModel::Associations module Hooks def self.init ActiveSupport.on_load(:active_record) do require 'active_model/associations/association_scope_extension' ActiveRecord::Associations::AssociationScope.prepend ActiveModel::Associations::AssociationScopeExtension end end end end
module ActiveModel::Associations module Hooks def self.init ActiveSupport.on_load(:active_record) do require 'active_model/associations/association_scope_extension' ActiveRecord::Associations::AssociationScope.send(:prepend, ActiveModel::Associations::AssociationScopeExtension) end end end end
Fix has_and_belongs_to_many scope primary key
module Surus module JSON class HasAndBelongsToManyScopeBuilder < AssociationScopeBuilder def scope s = association .klass .joins("JOIN #{join_table} ON #{join_table}.#{association_foreign_key}=#{association_table}.#{association_primary_key}") .where("#{outside_class.quoted_table_name}.#{association_primary_key}=#{join_table}.#{foreign_key}") s = s.instance_eval(&association.scope) if association.scope s end def join_table connection.quote_table_name association.join_table end def association_foreign_key connection.quote_column_name association.association_foreign_key end def foreign_key connection.quote_column_name association.foreign_key end def association_table connection.quote_table_name association.klass.table_name end def association_primary_key connection.quote_column_name association.association_primary_key end end end end
module Surus module JSON class HasAndBelongsToManyScopeBuilder < AssociationScopeBuilder def scope s = association .klass .joins("JOIN #{join_table} ON #{join_table}.#{association_foreign_key}=#{association_table}.#{association_primary_key}") .where("#{outside_class.quoted_table_name}.#{primary_key}=#{join_table}.#{foreign_key}") s = s.instance_eval(&association.scope) if association.scope s end def join_table connection.quote_table_name association.join_table end def primary_key connection.quote_table_name association.active_record_primary_key end def association_foreign_key connection.quote_column_name association.association_foreign_key end def foreign_key connection.quote_column_name association.foreign_key end def association_table connection.quote_table_name association.klass.table_name end def association_primary_key connection.quote_column_name association.association_primary_key end end end end
Fix selector in line comment reply tests
RSpec.shared_examples 'a page with line comment replies' do context 'when clicking on the reply icon of a line comment', reply: true do let(:comment_field) do # Sometimes there is more than one textarea with the same id driver.find_elements( :css, "textarea[id$='_diff-780594414fe50c0ffbb11dfe104c53e4_1']" ).find(&:displayed?) end before do driver.find_element(:css, "div[id$='r55945068'] .epr-reply-button").click end it 'fills in a new comment field with quoted text' do expect(comment_field.attribute('value')).to eq( "\n\n> Mac still doesn't come with Python 3" ) end it 'focuses on the newly opened comment field' do expect(comment_field).to eq(driver.switch_to.active_element) end end end
RSpec.shared_examples 'a page with line comment replies' do context 'when clicking on the reply icon of a line comment', reply: true do let(:comment_field) do # Sometimes there is more than one textarea with the same id driver.find_elements( :id, 'new_inline_comment_diff_diff-780594414fe50c0ffbb11dfe104c53e4_55945068_1' ).find(&:displayed?) end before do driver.find_element(:css, "div[id$='r55945068'] .epr-reply-button").click end it 'fills in a new comment field with quoted text' do expect(comment_field.attribute('value')).to eq( "\n\n> Mac still doesn't come with Python 3" ) end it 'focuses on the newly opened comment field' do expect(comment_field).to eq(driver.switch_to.active_element) end end end
Add view encoding settings. Set utf-8 encoding as default
require "tilt" class Cuba module Rendering def self.setup(app) app.plugin Cuba::Settings app.set :template_engine, "erb" app.set :views, File.expand_path("views", Dir.pwd) end def view(template, locals = {}) partial("layout", { content: partial(template, locals) }.merge(locals)) end def partial(template, locals = {}) render("#{settings.views}/#{template}.#{settings.template_engine}", locals) end # Render any type of template file supported by Tilt. # # @example # # # Renders home, and is assumed to be HAML. # render("home.haml") # # # Renders with some local variables # render("home.haml", site_name: "My Site") # # # Renders with HAML options # render("home.haml", {}, ugly: true, format: :html5) # # # Renders in layout # render("layout.haml") { render("home.haml") } # def render(template, locals = {}, options = {}, &block) _cache.fetch(template, locals) { Tilt.new(template, 1, options) }.render(self, locals, &block) end end end
require "tilt" class Cuba module Rendering def self.setup(app) app.plugin Cuba::Settings app.set :template_engine, "erb" app.set :views, File.expand_path("views", Dir.pwd) app.set :encoding, Encoding::UTF_8 end def view(template, locals = {}) partial("layout", { content: partial(template, locals) }.merge(locals)) end def partial(template, locals = {}) render("#{settings.views}/#{template}.#{settings.template_engine}", locals, default_encoding: settings.encoding) end # Render any type of template file supported by Tilt. # # @example # # # Renders home, and is assumed to be HAML. # render("home.haml") # # # Renders with some local variables # render("home.haml", site_name: "My Site") # # # Renders with HAML options # render("home.haml", {}, ugly: true, format: :html5) # # # Renders in layout # render("layout.haml") { render("home.haml") } # def render(template, locals = {}, options = {}, &block) _cache.fetch(template, locals) { Tilt.new(template, 1, options) }.render(self, locals, &block) end end end
Initialize Query with an empty set of params, and merge the default ones in before executing; add a reset() method which resets the parameters
module ContentfulModel class Query attr_accessor :parameters def initialize(reference_class, parameters=nil) @parameters = parameters || { 'content_type' => reference_class.content_type_id } @client = reference_class.client end def <<(parameters) @parameters.merge!(parameters) end def execute @client.entries(@parameters) end end end
module ContentfulModel class Query attr_accessor :parameters def initialize(referenced_class, parameters=nil) @parameters = parameters || {} @client = referenced_class.send(:client) @referenced_class = referenced_class end def <<(parameters) @parameters.merge!(parameters) end def default_parameters { 'content_type' => @referenced_class.send(:content_type_id) } end def execute query = @parameters.merge!(default_parameters) return @client.entries(query) end def reset @parameters = default_parameters end end end
Correct name of test variable
require 'spec_helper' describe TicTacToe::Human do describe 'when validating input' do let(:shell) { mock_shell } let(:console_shell) { TicTacToe::Human.new(shell) } def mock_shell instance_double("TicTacToe::ConsoleShell").tap do |shell| allow(shell).to receive(:show_invalid_move_message) allow(shell).to receive(:show_move_error_message) end end def with(input:, expecting:) allow(shell).to receive(:prompt_move).and_return("#{input}\n") expect(console_shell.get_move).to eq expecting end def ignores(input:) allow(shell).to receive(:prompt_move).and_return("#{input}\n", "1\n") expect(console_shell.get_move).to eq 1 end it 'keeps reading until it gets a number' do allow(shell).to receive(:prompt_move).and_return("abcd\n", "def\n", "{1a\n", "1\n") expect(console_shell.get_move).to eq 1 end it 'should only return a number between 0 and 8' do ignores(input: "-10") ignores(input: "-1") ignores(input: "9") ignores(input: "15") with(input: "0", expecting: 0) with(input: "4", expecting: 4) with(input: "8", expecting: 8) end end end
require 'spec_helper' describe TicTacToe::Human do describe 'when validating input' do let(:shell) { mock_shell } let(:human) { TicTacToe::Human.new(shell) } def mock_shell instance_double("TicTacToe::ConsoleShell").tap do |shell| allow(shell).to receive(:show_invalid_move_message) allow(shell).to receive(:show_move_error_message) end end def with(input:, expecting:) allow(shell).to receive(:prompt_move).and_return("#{input}\n") expect(human.get_move).to eq expecting end def ignores(input:) allow(shell).to receive(:prompt_move).and_return("#{input}\n", "1\n") expect(human.get_move).to eq 1 end it 'keeps reading until it gets a number' do allow(shell).to receive(:prompt_move).and_return("abcd\n", "def\n", "{1a\n", "1\n") expect(human.get_move).to eq 1 end it 'should only return a number between 0 and 8' do ignores(input: "-10") ignores(input: "-1") ignores(input: "9") ignores(input: "15") with(input: "0", expecting: 0) with(input: "4", expecting: 4) with(input: "8", expecting: 8) end end end
Swap the subject() and let() methods around
require 'rails_helper' describe Section do let(:course) { double("Course", :id => 1) } subject(:section) { Section.new( :title => "test section", :title_url => "testsection.url.com", :description => "some test description", :position => 2, :course_id => course.id )} it { is_expected.to respond_to(:title) } it { is_expected.to respond_to(:title_url) } it { is_expected.to respond_to(:description) } it { is_expected.to respond_to(:position) } it { is_expected.to respond_to(:course_id) } it { is_expected.to respond_to(:course) } it { is_expected.to respond_to(:lessons) } # Associations it { is_expected.to belong_to(:course) } it { is_expected.to have_many(:lessons) } # Validations it { is_expected.to validate_uniqueness_of(:position).with_message('Section position has already been taken') } it { is_expected.to be_valid } end
require 'rails_helper' describe Section do subject(:section) { Section.new( :title => "test section", :title_url => "testsection.url.com", :description => "some test description", :position => 2, :course_id => course.id )} let(:course) { double("Course", :id => 1) } it { is_expected.to respond_to(:title) } it { is_expected.to respond_to(:title_url) } it { is_expected.to respond_to(:description) } it { is_expected.to respond_to(:position) } it { is_expected.to respond_to(:course_id) } it { is_expected.to respond_to(:course) } it { is_expected.to respond_to(:lessons) } # Associations it { is_expected.to belong_to(:course) } it { is_expected.to have_many(:lessons) } # Validations it { is_expected.to validate_uniqueness_of(:position).with_message('Section position has already been taken') } it { is_expected.to be_valid } end
Add fields to generated project
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :project do name { FFaker::Product.product_name } association :submitter, factory: :user trait :accepted do after(:create) { |record| record.accept! } end trait :rejected do after(:create) { |record| record.reject! } end end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :project do name { FFaker::Product.product_name } association :submitter, factory: :user mentor_name { FFaker::Product.product_name } mentor_github_handle { FFaker::Internet.user_name } mentor_email { FFaker::Internet.email } url { FFaker::Internet.http_url } description { FFaker::HipsterIpsum.paragraph } issues_and_features { FFaker::Internet.email } beginner_friendly true trait :accepted do after(:create) { |record| record.accept! } end trait :rejected do after(:create) { |record| record.reject! } end end end
Add test to ensure that bundle install --force doesn't leave any old code on gem reinstall
require "spec_helper" describe "bundle install" do describe "with --force" do before :each do gemfile <<-G source "file://#{gem_repo1}" gem "rack" G end it "re-installs installed gems" do bundle "install" bundle "install --force" expect(out).to include "Installing rack 1.0.0" should_be_installed "rack 1.0.0" expect(exitstatus).to eq(0) if exitstatus end it "doesn't reinstall bundler" do bundle "install" bundle "install --force" expect(out).to_not include "Installing bundler 1.10.4" expect(out).to include "Using bundler 1.10.4" end end end
require "spec_helper" describe "bundle install" do describe "with --force" do before :each do gemfile <<-G source "file://#{gem_repo1}" gem "rack" G end it "re-installs installed gems" do bundle "install" bundle "install --force" expect(out).to include "Installing rack 1.0.0" should_be_installed "rack 1.0.0" expect(exitstatus).to eq(0) if exitstatus end it "overwrites old gem code" do bundle "install" default_bundle_path("gems/rack-1.0.0/lib/rack.rb").open('w'){|f| f.write("blah blah blah") } bundle "install --force" expect(default_bundle_path("gems/rack-1.0.0/lib/rack.rb").open{|f| f.read }).to eq("RACK = '1.0.0'\n") end it "doesn't reinstall bundler" do bundle "install" bundle "install --force" expect(out).to_not include "Installing bundler 1.10.4" expect(out).to include "Using bundler 1.10.4" end end end
Add passing spec for answer
require 'spec_helper' describe Answer do before(:each) do @answer = Answer.new @answer.content = "Help for you" end context "with valid attributes" do it "should be save-able" do @answer.should be_valid end end context "with invalid attributes" do before(:each) do @answer.content = '' end it "should not be save-able" do @answer.should_not be_valid end end end
Fix intermittent spec failure caused by unrealistic timing
require 'spec_helper' describe 'Single Granule Data Access', reset: false do downloadable_dataset_id = 'C183451156-GSFCS4PA' context 'when the user is not logged in' do before(:each) do load_page :search, project: [downloadable_dataset_id], view: :project wait_for_xhr first_project_dataset.click first_granule_list_item.click_link "Retrieve data" end after :each do Capybara.reset_sessions! end it 'forces the user to login before showing data access page' do expect(page).to have_content('EOSDIS User Registration System') end end context 'when the user is logged in' do before :all do load_page :search, project: [downloadable_dataset_id], view: :project login wait_for_xhr first_project_dataset.click first_granule_list_item.click_link "Retrieve data" wait_for_xhr end after :all do Capybara.reset_sessions! end it 'only configures one granule' do expect(page).to have_content "1 Granule" end it 'limits the data access to only the selected granule' do click_link 'Expand List' expect(page).to have_content 'AIRS3STM.005:AIRS.2014.05.01.L3.RetStd_IR031.v5.0.14.0.G14153132853.hdf' end end end
require 'spec_helper' describe 'Single Granule Data Access', reset: false do downloadable_dataset_id = 'C183451156-GSFCS4PA' context 'when the user is not logged in' do before(:each) do load_page :search, focus: downloadable_dataset_id wait_for_xhr first_granule_list_item.click_link "Retrieve data" end after :each do Capybara.reset_sessions! end it 'forces the user to login before showing data access page' do expect(page).to have_content('EOSDIS User Registration System') end end context 'when the user is logged in' do before :all do load_page :search, focus: downloadable_dataset_id login wait_for_xhr first_granule_list_item.click_link "Retrieve data" wait_for_xhr end after :all do Capybara.reset_sessions! end it 'only configures one granule' do expect(page).to have_content "1 Granule" end it 'limits the data access to only the selected granule' do click_link 'Expand List' expect(page).to have_content 'AIRS3STM.005:AIRS.2014.05.01.L3.RetStd_IR031.v5.0.14.0.G14153132853.hdf' end end end
Add extra checks for ci_id migration
# frozen_string_literal: true # See http://doc.gitlab.com/ce/development/migration_style_guide.html # for more information on how to write migrations for GitLab. class DropProjectsCiId < ActiveRecord::Migration[5.1] include Gitlab::Database::MigrationHelpers # Set this constant to true if this migration requires downtime. DOWNTIME = false disable_ddl_transaction! def up if index_exists?(:projects, :ci_id) remove_concurrent_index :projects, :ci_id end if column_exists?(:projects, :ci_id) remove_column :projects, :ci_id end end def down add_column :projects, :ci_id, :integer add_concurrent_index :projects, :ci_id end end
# frozen_string_literal: true # See http://doc.gitlab.com/ce/development/migration_style_guide.html # for more information on how to write migrations for GitLab. class DropProjectsCiId < ActiveRecord::Migration[5.1] include Gitlab::Database::MigrationHelpers # Set this constant to true if this migration requires downtime. DOWNTIME = false disable_ddl_transaction! def up if index_exists?(:projects, :ci_id) remove_concurrent_index :projects, :ci_id end if column_exists?(:projects, :ci_id) remove_column :projects, :ci_id end end def down unless column_exists?(:projects, :ci_id) add_column :projects, :ci_id, :integer end unless index_exists?(:projects, :ci_id) add_concurrent_index :projects, :ci_id end end end
Return array starting at 1 and ending with number it was initialized with
class OddEven def initialize (user_number) @user_number = user_number end def makearray numbers = 1.upto(@user_number).to_a end end
Store config in a Struct
module Whoopsie class Railtie < Rails::Railtie config.whoopsie = ActiveSupport::OrderedOptions.new initializer "whoopsie.configure_middleware" do Rails.application.middleware.insert_before ActiveRecord::ConnectionAdapters::ConnectionManagement, ExceptionNotification::Rack ExceptionNotification.configure do |config| # Ignore additional exception types. # ActiveRecord::RecordNotFound, AbstractController::ActionNotFound and ActionController::RoutingError are already added. # config.ignored_exceptions += %w{ActionView::TemplateError CustomError} # Adds a condition to decide when an exception must be ignored or not. # The ignore_if method can be invoked multiple times to add extra conditions. config.ignore_if do |exception, options| ! Rails.application.config.whoopsie.enable end end end end end ExceptionNotifier.module_eval do def self.handle_exception(exception, *extra) if Rails.application.config.whoopsie.enable notify_exception(exception, *extra) else raise exception end end end
module Whoopsie class Railtie < Rails::Railtie Config = Struct.new(:enable) config.whoopsie = Config.new initializer "whoopsie.configure_middleware" do Rails.application.middleware.insert_before ActiveRecord::ConnectionAdapters::ConnectionManagement, ExceptionNotification::Rack ExceptionNotification.configure do |config| # Ignore additional exception types. # ActiveRecord::RecordNotFound, AbstractController::ActionNotFound and ActionController::RoutingError are already added. # config.ignored_exceptions += %w{ActionView::TemplateError CustomError} # Adds a condition to decide when an exception must be ignored or not. # The ignore_if method can be invoked multiple times to add extra conditions. config.ignore_if do |exception, options| ! Rails.application.config.whoopsie.enable end end end end end ExceptionNotifier.module_eval do def self.handle_exception(exception, *extra) if Rails.application.config.whoopsie.enable notify_exception(exception, *extra) else raise exception end end end
Add controller test to payment profile connect to check for stored keys
require 'spec_helper' describe PaymentProfilesController do let!(:user) { FactoryGirl.create(:user) } before do stub_login user end context '#connect' do it 'should add a row to payment profiles table' do binding.pry expect { post :connect, code: "some_api_code" }.to change{ PaymentProfile.count }.by(1) binding.pry end end context '#index' do end end
require 'spec_helper' describe PaymentProfilesController do let!(:user) { FactoryGirl.create(:user) } before(:each) do stub_login user end context '#connect' do let(:publishable_key) { "a_pk" } let(:access_token) { "a_at" } let(:code) { "some_api_code"} before(:each) do PaymentProfile.stubs(:get_client_info).returns({'stripe_publishable_key' => publishable_key, 'access_token' => access_token}) end it 'should add a row to payment profiles table' do expect { post :connect, code: code }.to change{ PaymentProfile.count }.by(1) end it 'should have the access_token and publishable_key' do post :connect, code: code expect(PaymentProfile.last.publishable_key).to eq publishable_key expect(PaymentProfile.last.access_token).to eq access_token end end context '#index' do let!(:payment_profile) { FactoryGirl.create(:payment_profile, user: user) } before do PaymentProfilesController.any_instance.stubs(:username).returns() get :index end it 'should store user instance' it 'should store connected instance' it 'should store payments instance' end end
Undo previous tests, does not fix the issue
def mkdir_p(path) complete_path = '.' path.split(/\/|\\/).each do |folder| complete_path = File.join(complete_path, folder) FileUtils.mkdir(complete_path) unless Dir.exist?(complete_path) end end def write_file(path, content) mkdir_p(File.dirname(path)) File.open(path, 'w') { |file| file.write(content) } end
def write_file(path, content) FileUtils.mkdir_p(File.dirname(path)) File.open(path, 'w') { |file| file.write(content) } end
Add require on tests and prepare constants with response status
require 'simplecov' # $: << File.expand_path("../../lib", __FILE__) $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'organic-sitemap' require 'redis' SimpleCov.start RSpec.configure do |config| config.filter_run_excluding broken: true end
require 'simplecov' # $: << File.expand_path("../../lib", __FILE__) $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'organic-sitemap' require 'redis' SimpleCov.start require 'fakeredis/rspec' RSpec.configure do |config| config.filter_run_excluding broken: true end OrganicSitemap.configure OK_STATUS_CODES = 200..207 REDIRECT_STATUS_CODES = 300..307 CLIENT_ERROR_STATUS_CODES = 400..429 ERROR_STATUS_CODE = 500..509 ALL_STATUS = [*OK_STATUS_CODES, *REDIRECT_STATUS_CODES, *CLIENT_ERROR_STATUS_CODES, *ERROR_STATUS_CODE]
Fix generators for spree 2.3.0
module SpreeIpay88 module Generators class InstallGenerator < Rails::Generators::Base class_option :auto_run_migrations, :type => :boolean, :default => false def add_javascripts append_file 'app/assets/javascripts/store/all.js', "//= require store/spree_ipay88\n" append_file 'app/assets/javascripts/admin/all.js', "//= require admin/spree_ipay88\n" end def add_stylesheets inject_into_file 'app/assets/stylesheets/store/all.css', " *= require store/spree_ipay88\n", :before => /\*\//, :verbose => true inject_into_file 'app/assets/stylesheets/admin/all.css', " *= require admin/spree_ipay88\n", :before => /\*\//, :verbose => true end def add_migrations run 'bundle exec rake railties:install:migrations FROM=spree_ipay88' end def run_migrations run_migrations = options[:auto_run_migrations] || ['', 'y', 'Y'].include?(ask 'Would you like to run the migrations now? [Y/n]') if run_migrations run 'bundle exec rake db:migrate' else puts 'Skipping rake db:migrate, don\'t forget to run it!' end end end end end
module SpreeIpay88 module Generators class InstallGenerator < Rails::Generators::Base class_option :auto_run_migrations, :type => :boolean, :default => false def add_javascripts append_file 'vendor/assets/javascripts/frontend/all.js', "//= require store/spree_ipay88\n" append_file 'vendor/assets/javascripts/backend/all.js', "//= require admin/spree_ipay88\n" end def add_stylesheets inject_into_file 'vendor/assets/stylesheets/frontend/all.css', " *= require store/spree_ipay88\n", :before => /\*\//, :verbose => true inject_into_file 'vendor/assets/stylesheets/backend/all.css', " *= require admin/spree_ipay88\n", :before => /\*\//, :verbose => true end def add_migrations run 'bundle exec rake railties:install:migrations FROM=spree_ipay88' end def run_migrations run_migrations = options[:auto_run_migrations] || ['', 'y', 'Y'].include?(ask 'Would you like to run the migrations now? [Y/n]') if run_migrations run 'bundle exec rake db:migrate' else puts 'Skipping rake db:migrate, don\'t forget to run it!' end end end end end
Add tool to list all classes and their inheritance.
require 'set' include Helpers::ModuleHelper MANIFEST_FILENAME = 'coverage.manifest'.freeze def init list_all_classes end def all_objects run_verifier(Registry.all) end def class_objects run_verifier(Registry.all(:class)) end def namespace_definition(object) return if object.root? definition = "#{object.type} #{object.path}" if object.type == :class && object.superclass.name != :Object definition << " < #{object.superclass.path}" end output = StringIO.new # output.puts generate_docstring(object) output.puts definition output.string end def generate_mixins(object, scope) output = StringIO.new mixin_type = (scope == :class) ? 'extend' : 'include' mixins = run_verifier(object.mixins(scope)) mixins = stable_sort_by(mixins, &:path) mixins.each { |mixin| output.puts " #{mixin_type} #{mixin.path}" } output.string end def list_all_classes # versions = Set.new klasses = [] class_objects.each { |object| # version_tag = object.tag(:version) # versions << version_tag.text if version_tag klasses << namespace_definition(object) } # puts klasses.sort.join("\n") puts klasses.sort.join exit # Avoid the YARD summary end
Fix typo--the correct spelling is "around", not "arond".
require "spec_helper" module RSpec::Core describe Hooks do describe "#around" do context "when not running the example within the arond block" do it "does not run the example" do examples = [] group = ExampleGroup.describe do around do |example| end it "foo" do examples << self end end group.run_all examples.should have(0).example end end context "when running the example within the around block" do it "runs the example" do examples = [] group = ExampleGroup.describe do around do |example| example.run end it "foo" do examples << self end end group.run_all examples.should have(1).example end end context "when running the example within a block passed to a method" do it "runs the example" do examples = [] group = ExampleGroup.describe do def yielder yield end around do |example| yielder { example.run } end it "foo" do examples << self end end group.run_all examples.should have(1).example end end end end end
require "spec_helper" module RSpec::Core describe Hooks do describe "#around" do context "when not running the example within the around block" do it "does not run the example" do examples = [] group = ExampleGroup.describe do around do |example| end it "foo" do examples << self end end group.run_all examples.should have(0).example end end context "when running the example within the around block" do it "runs the example" do examples = [] group = ExampleGroup.describe do around do |example| example.run end it "foo" do examples << self end end group.run_all examples.should have(1).example end end context "when running the example within a block passed to a method" do it "runs the example" do examples = [] group = ExampleGroup.describe do def yielder yield end around do |example| yielder { example.run } end it "foo" do examples << self end end group.run_all examples.should have(1).example end end end end end
Add updated_at in updated_all since this will not be updated by default
class DocumentCollectionOrder def initialize(event_id) @event_id = event_id end def show Document. joins('LEFT JOIN languages ON languages.id = documents.language_id'). joins('LEFT JOIN proposal_details ON proposal_details.document_id = documents.id'). select( "documents.id AS id, title, proposal_details.proposal_number AS proposal_number, type, languages.iso_code1 AS language, sort_index" ). where(event_id: @event_id). where('primary_language_document_id IS NULL OR primary_language_document_id = documents.id'). order(:sort_index) end def update(id_sort_index_hash) id_sort_index_hash.each do |id, sort_index| Document.update_all( {sort_index: sort_index}, ['id = :id OR primary_language_document_id = :id', id: id] ) end DocumentSearch.clear_cache end end
class DocumentCollectionOrder def initialize(event_id) @event_id = event_id end def show Document. joins('LEFT JOIN languages ON languages.id = documents.language_id'). joins('LEFT JOIN proposal_details ON proposal_details.document_id = documents.id'). select( "documents.id AS id, title, proposal_details.proposal_number AS proposal_number, type, languages.iso_code1 AS language, sort_index" ). where(event_id: @event_id). where('primary_language_document_id IS NULL OR primary_language_document_id = documents.id'). order(:sort_index) end def update(id_sort_index_hash) id_sort_index_hash.each do |id, sort_index| Document.update_all( {sort_index: sort_index, updated_at: DateTime.now}, ['id = :id OR primary_language_document_id = :id', id: id] ) end DocumentSearch.clear_cache end end
Discard DeviantArt.new what was for backward compatibility
require 'deviantart/version' require 'deviantart/client' require 'deviantart/base' require 'deviantart/deviation' require 'deviantart/user' require 'deviantart/status' module DeviantArt # Bypass args and block to DeviantArt::Client # ...for backward compatibility def self.new(*args, &block) DeviantArt::Client.new(*args, &block) end end
require 'deviantart/version' require 'deviantart/client' require 'deviantart/base' require 'deviantart/deviation' require 'deviantart/user' require 'deviantart/status' module DeviantArt end
Add EXCLUDE_EMBEDDED so that JRuby users can just connect to the server without needing neo4j-community/neo4j-enterprise
require 'ext/kernel' require 'ostruct' require 'forwardable' require 'fileutils' require 'neo4j-core/version' require 'neo4j/property_validator' require 'neo4j/property_container' require 'neo4j-core/active_entity' require 'neo4j-core/helpers' require 'neo4j-core/query_find_in_batches' require 'neo4j-core/query' require 'neo4j/entity_equality' require 'neo4j/node' require 'neo4j/label' require 'neo4j/session' require 'neo4j/ansi' require 'neo4j/relationship' require 'neo4j/transaction' require 'neo4j-server' require 'rake' require 'neo4j/rake_tasks' if RUBY_PLATFORM == 'java' require 'neo4j-embedded' else # just for the tests module Neo4j module Embedded end end end
require 'ext/kernel' require 'ostruct' require 'forwardable' require 'fileutils' require 'neo4j-core/version' require 'neo4j/property_validator' require 'neo4j/property_container' require 'neo4j-core/active_entity' require 'neo4j-core/helpers' require 'neo4j-core/query_find_in_batches' require 'neo4j-core/query' require 'neo4j/entity_equality' require 'neo4j/node' require 'neo4j/label' require 'neo4j/session' require 'neo4j/ansi' require 'neo4j/relationship' require 'neo4j/transaction' require 'neo4j-server' require 'rake' require 'neo4j/rake_tasks' if RUBY_PLATFORM == 'java' && !ENV['EXCLUDE_EMBEDDED'] require 'neo4j-embedded' else # just for the tests module Neo4j module Embedded end end end
Add missing require for Thing
require 'opal' module Yeah module Web end end require 'yeah/image' require 'yeah/asset_loader' require 'yeah/display' require 'yeah/keyboard' require 'yeah/mouse' require 'yeah/game' require 'yeah/space' require 'yeah/look' require 'yeah/fill_look' require 'yeah/image_look' require 'yeah/sprite_look' Yeah::AssetLoader.load_all do require 'game' Yeah::Game.subclasses.last.new end
require 'opal' module Yeah module Web end end require 'yeah/image' require 'yeah/asset_loader' require 'yeah/display' require 'yeah/keyboard' require 'yeah/mouse' require 'yeah/game' require 'yeah/space' require 'yeah/thing' require 'yeah/look' require 'yeah/fill_look' require 'yeah/image_look' require 'yeah/sprite_look' Yeah::AssetLoader.load_all do require 'game' Yeah::Game.subclasses.last.new end
Add userinfo.email to default scopes
# frozen_string_literal: true module Kubeclient # Get a bearer token from the Google's application default credentials. class GoogleApplicationDefaultCredentials class GoogleDependencyError < LoadError # rubocop:disable Lint/InheritException end class << self def token begin require 'googleauth' rescue LoadError => e raise GoogleDependencyError, 'Error requiring googleauth gem. Kubeclient itself does not include the ' \ 'googleauth gem. To support auth-provider gcp, you must include it in your ' \ "calling application. Failed with: #{e.message}" end scopes = ['https://www.googleapis.com/auth/cloud-platform'] authorization = Google::Auth.get_application_default(scopes) authorization.apply({}) authorization.access_token end end end end
# frozen_string_literal: true module Kubeclient # Get a bearer token from the Google's application default credentials. class GoogleApplicationDefaultCredentials class GoogleDependencyError < LoadError # rubocop:disable Lint/InheritException end class << self def token begin require 'googleauth' rescue LoadError => e raise GoogleDependencyError, 'Error requiring googleauth gem. Kubeclient itself does not include the ' \ 'googleauth gem. To support auth-provider gcp, you must include it in your ' \ "calling application. Failed with: #{e.message}" end scopes = [ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/userinfo.email' ] authorization = Google::Auth.get_application_default(scopes) authorization.apply({}) authorization.access_token end end end end
Add Brian to gem authors
# -*- encoding: utf-8 -*- require File.expand_path('../lib/vagrant-libvirt/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ['Lukas Stanek','Dima Vasilets'] gem.email = ['ls@elostech.cz','pronix.service@gmail.com'] gem.license = 'MIT' gem.description = %q{Vagrant provider for libvirt.} gem.summary = %q{Vagrant provider for libvirt.} gem.homepage = "https://github.com/pradels/vagrant-libvirt" 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 = 'vagrant-libvirt' gem.require_paths = ['lib'] gem.version = VagrantPlugins::ProviderLibvirt::VERSION gem.add_runtime_dependency 'fog', '~> 1.15' gem.add_runtime_dependency 'ruby-libvirt', '~> 0.4.0' gem.add_runtime_dependency 'nokogiri', '~> 1.5.9' gem.add_development_dependency 'rake' end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/vagrant-libvirt/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ['Lukas Stanek','Dima Vasilets','Brian Pitts'] gem.email = ['ls@elostech.cz','pronix.service@gmail.com','brian@polibyte.com'] gem.license = 'MIT' gem.description = %q{Vagrant provider for libvirt.} gem.summary = %q{Vagrant provider for libvirt.} gem.homepage = "https://github.com/pradels/vagrant-libvirt" 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 = 'vagrant-libvirt' gem.require_paths = ['lib'] gem.version = VagrantPlugins::ProviderLibvirt::VERSION gem.add_runtime_dependency 'fog', '~> 1.15' gem.add_runtime_dependency 'ruby-libvirt', '~> 0.4.0' gem.add_runtime_dependency 'nokogiri', '~> 1.5.9' gem.add_development_dependency 'rake' end
Improve test descriptions for io listener
require 'spec_helper' module ActivityBroker describe IOListener do class FakeListener def forwarding_follow_event end end let!(:fake_listener) { FakeListener.new } let!(:io_listener) { IOListener.new(fake_listener, :forwarding_follow_event) } it 'is equal to other io listener when listener and event match' do expect(io_listener).to eq IOListener.new(fake_listener, :forwarding_follow_event) end it 'is not equal to another io listener when event does not match' do expect(io_listener).not_to eq IOListener.new(fake_listener, :forwarding_status_update) end it 'is not equal to anoother io listener when registered listener does not match' do another_fake_listener = FakeListener.new expect(io_listener).not_to eq IOListener.new(another_fake_listener, :forwarding_follow_event) end end end
require 'spec_helper' module ActivityBroker describe IOListener do class FakeListener def forwarding_follow_event end end let!(:fake_listener) { FakeListener.new } let!(:io_listener) { IOListener.new(fake_listener, :forwarding_follow_event) } it 'is equal to another io listener when listener and event match' do expect(io_listener).to eq IOListener.new(fake_listener, :forwarding_follow_event) end it 'is not equal to another io listener when registered events dont match' do expect(io_listener).not_to eq IOListener.new(fake_listener, :forwarding_status_update) end it 'is not equal to another io listener when registered listeners dont match' do another_fake_listener = FakeListener.new expect(io_listener).not_to eq IOListener.new(another_fake_listener, :forwarding_follow_event) end end end
Add test for context proc arity validation
require "spec_helper" describe Vault::EncryptedModel do let(:klass) do Class.new(ActiveRecord::Base) do include Vault::EncryptedModel end end describe ".vault_attribute" do it "raises an exception if a serializer and :encode is given" do expect { klass.vault_attribute(:foo, serializer: :json, encode: ->(r) { r }) }.to raise_error(Vault::Rails::ValidationFailedError) end it "raises an exception if a serializer and :decode is given" do expect { klass.vault_attribute(:foo, serializer: :json, decode: ->(r) { r }) }.to raise_error(Vault::Rails::ValidationFailedError) end it "defines a getter" do klass.vault_attribute(:foo) expect(klass.instance_methods).to include(:foo) end it "defines a setter" do klass.vault_attribute(:foo) expect(klass.instance_methods).to include(:foo=) end it "defines a checker" do klass.vault_attribute(:foo) expect(klass.instance_methods).to include(:foo?) end it "defines dirty attribute methods" do klass.vault_attribute(:foo) expect(klass.instance_methods).to include(:foo_change) expect(klass.instance_methods).to include(:foo_changed?) expect(klass.instance_methods).to include(:foo_was) end end end
require "spec_helper" describe Vault::EncryptedModel do let(:klass) do Class.new(ActiveRecord::Base) do include Vault::EncryptedModel end end describe ".vault_attribute" do it "raises an exception if a serializer and :encode is given" do expect { klass.vault_attribute(:foo, serializer: :json, encode: ->(r) { r }) }.to raise_error(Vault::Rails::ValidationFailedError) end it "raises an exception if a serializer and :decode is given" do expect { klass.vault_attribute(:foo, serializer: :json, decode: ->(r) { r }) }.to raise_error(Vault::Rails::ValidationFailedError) end it "raises an exception if a proc is passed to :context without an arity of 1" do expect { klass.vault_attribute(:foo, context: ->() { }) }.to raise_error(Vault::Rails::ValidationFailedError, /1 argument/i) end it "defines a getter" do klass.vault_attribute(:foo) expect(klass.instance_methods).to include(:foo) end it "defines a setter" do klass.vault_attribute(:foo) expect(klass.instance_methods).to include(:foo=) end it "defines a checker" do klass.vault_attribute(:foo) expect(klass.instance_methods).to include(:foo?) end it "defines dirty attribute methods" do klass.vault_attribute(:foo) expect(klass.instance_methods).to include(:foo_change) expect(klass.instance_methods).to include(:foo_changed?) expect(klass.instance_methods).to include(:foo_was) end end end
Add gsub to prevent Faker from creating numbers that start with 911, a condition that causes PhonyRails to declare the number invalid.
FactoryGirl.define do factory :user, class: "User" do name { Faker::Name.name } email { Faker::Internet.email } phone_number { Faker::PhoneNumber.phone_number } institution_pid { FactoryGirl.create(:institution).pid } factory :aptrust_user, class: "User" do institution_pid { relation = Institution.where(desc_metadata__name_tesim: 'APTrust') if relation.count == 1 relation.first.pid else FactoryGirl.create(:aptrust).pid end } end trait :admin do roles { [Role.where(name: 'admin').first] } end trait :institutional_admin do roles { [Role.where(name: 'institutional_admin').first] } end trait :institutional_user do roles { [Role.where(name: 'institutional_user').first] } end end end
FactoryGirl.define do factory :user, class: "User" do name { Faker::Name.name } email { Faker::Internet.email } phone_number { Faker::PhoneNumber.phone_number.gsub(/911/, '811') } institution_pid { FactoryGirl.create(:institution).pid } factory :aptrust_user, class: "User" do institution_pid { relation = Institution.where(desc_metadata__name_tesim: 'APTrust') if relation.count == 1 relation.first.pid else FactoryGirl.create(:aptrust).pid end } end trait :admin do roles { [Role.where(name: 'admin').first] } end trait :institutional_admin do roles { [Role.where(name: 'institutional_admin').first] } end trait :institutional_user do roles { [Role.where(name: 'institutional_user').first] } end end end
Update put.io adder to 2.7
class PutioAdder < Cask version '2.6.1' sha256 'd89aed7a40de99ad3e75ca05995c088c5147282cb387beaaa5c496c5fc9b2307' url 'https://github.com/nicoSWD/put.io-adder/releases/download/v2.6.1/put.io.adder.zip' homepage 'https://github.com/nicoSWD/put.io-adder' link 'put.io adder.app' end
class PutioAdder < Cask version '2.7' sha256 'b4ac5fc97da0a8b83e56bd5cac0e1795ce7102aae3a69fb77fa64d9ed2f22c14' url 'https://github.com/nicoSWD/put.io-adder/releases/download/v2.7/put.io-adder-v2.7.zip' homepage 'https://github.com/nicoSWD/put.io-adder' link 'put.io adder.app' end
Update QuickSilver to version 1.1.3
class Quicksilver < Cask url 'http://cdn.qsapp.com/com.blacktree.Quicksilver__16390.dmg' homepage 'http://qsapp.com/' version '1.1.2' sha1 '1957b38994afaf3da54b8eb547395dd407b28698' link 'Quicksilver.app' end
class Quicksilver < Cask url 'http://cdn.qsapp.com/com.blacktree.Quicksilver__16391.dmg' homepage 'http://qsapp.com/' version '1.1.3' sha1 '87054e36d98b1158f0eea7fd4c87e801b96aee6b' link 'Quicksilver.app' end
Add pending specs for testing when debug bar shouldn't show
require "rails_helper" describe HomeController do render_views describe "GET index" do it "renders booze debug bar" do get :index expect(response.body).to match /booze_debug_bar/ end end end
require "rails_helper" describe HomeController do render_views describe "GET index" do it "renders booze debug bar" do get :index expect(response.body).to match /booze_debug_bar/ end pending "doesn't render debug bar in JSON" pending "doesn't render debug bar if no closing body tag" end end
Update to use new fixture filename
require 'spec_helper' module MITS describe Document do subject { Document.new('./spec/fixtures/mits.xml', version: 4.1) } describe '#properties' do it 'will return the properties' do companies = subject.properties.reduce([]) { |arr, property| arr.push(property) } expect(companies.first).to be_a V4_1::Property expect(companies.size).to eq 2 end end describe '#companies' do it 'will return the companies' do companies = subject.companies.reduce([]) { |arr, company| arr.push(company) } expect(companies.first).to be_a V4_1::Company expect(companies.size).to eq 1 end end end end
require 'spec_helper' module MITS describe Document do subject { Document.new('./spec/fixtures/MITS_4.1_Sample.xml', version: 4.1) } describe '#properties' do it 'will return the properties' do companies = subject.properties.reduce([]) { |arr, property| arr.push(property) } expect(companies.first).to be_a V4_1::Property expect(companies.size).to eq 2 end end describe '#companies' do it 'will return the companies' do companies = subject.companies.reduce([]) { |arr, company| arr.push(company) } expect(companies.first).to be_a V4_1::Company expect(companies.size).to eq 1 end end end end
Remove comment in spec file
require 'spec_helper' module Spree describe Api::VariantsController, type: :controller do render_views let(:variants){create_list(:master_variant, 2)} before(:each) do stub_authentication! variants.each do |v| v.fulfillment_subsidy = 1+rand(2) v.save end end context 'as an admin' do # sign_in_as_admin! let!(:current_api_user) do user = double(Spree.user_class) allow(user).to receive_message_chain(:spree_roles, :pluck).and_return(["admin"]) allow(user).to receive(:has_spree_role?).with("admin").and_return(true) user end context '#show' do it 'includes fulfillment_subsidy in the view' do api_get :show, {id: variants[0].to_param} expect(json_response[:fulfillment_subsidy]).to eq(variants[0].fulfillment_subsidy.to_s) end end end end end
require 'spec_helper' module Spree describe Api::VariantsController, type: :controller do render_views let(:variants){create_list(:master_variant, 2)} before(:each) do stub_authentication! variants.each do |v| v.fulfillment_subsidy = 1+rand(2) v.save end end context 'as an admin' do let!(:current_api_user) do user = double(Spree.user_class) allow(user).to receive_message_chain(:spree_roles, :pluck).and_return(["admin"]) allow(user).to receive(:has_spree_role?).with("admin").and_return(true) user end context '#show' do it 'includes fulfillment_subsidy in the view' do api_get :show, {id: variants[0].to_param} expect(json_response[:fulfillment_subsidy]).to eq(variants[0].fulfillment_subsidy.to_s) end end end end end
Update content to test change
require "simple_mvc/version" module SimpleMVC class Application def call(env) [200, {"Content-Type" => "text/html"}, ['Hey, there! Its SimpleMVC']] end end end
require "simple_mvc/version" module SimpleMVC class Application def call(env) [200, {"Content-Type" => "text/html"}, ['Hello, there! Its SimpleMVC']] end end end
Fix another typo with class 2 exercise 4
# 5 points # # Write a program that asks for a person's first name, then middle name, and # then last name. Finally, it greets the person using their full name. # # Here's how the program must work: # # $ ruby exercise4.rb # What's your first name? # Samuel # What's your middle name? # Leroy # What's your last name? # Jackson # Nice to meet you, Samuel Leroy Jackson.
# 5 points # # Write a program that asks for a person's first name, then middle name, # then last name, and then greets the person using their full name. # # Here's how the program must work: # # $ ruby exercise4.rb # What's your first name? # Samuel # What's your middle name? # Leroy # What's your last name? # Jackson # Nice to meet you, Samuel Leroy Jackson.
Add migration for choice_users table
class CreateChoiceUsersTable < ActiveRecord::Migration def change create_table :choice_users do |t| t.references :choice, null: false t.references :user, null: false end end end
Fix Users model to comply with updated request parameter set
require 'fog/core/collection' require 'fog/aws/models/iam/user' module Fog module AWS class IAM class Users < Fog::Collection model Fog::AWS::IAM::User def all data = connection.list_users.body['Users'] load(data) # data is an array of attribute hashes end def get(identity) data = connection.get_user('UserName' => identity).body['User'] new(data) # data is an attribute hash rescue Fog::AWS::IAM::NotFound nil end end end end end
require 'fog/core/collection' require 'fog/aws/models/iam/user' module Fog module AWS class IAM class Users < Fog::Collection model Fog::AWS::IAM::User def all data = connection.list_users.body['Users'] load(data) # data is an array of attribute hashes end def get(identity) data = connection.get_user(identity).body['User'] new(data) # data is an attribute hash rescue Fog::AWS::IAM::NotFound nil end end end end end
Rename :leaders attribute to :leader_names
class Record attr_accessor :created_at, :meeting_date, :club_name, :leaders, :attendance, :notes def initialize(created_at, meeting_date, club_name, leaders, attendance, notes) @created_at = created_at @meeting_date = meeting_date @club_name = club_name @leaders = leaders @attendance = attendance @notes = notes end def self.csv_title ['Check In Completion Timestamp', 'Meeting Date', 'Club Name', 'Leaders', 'Attendance', 'Notes'] end def csv_contents [created_at, meeting_date, club_name, leaders.join(', '), attendance, notes] end end desc 'Generate a report of all check ins' task check_ins: :environment do csv_string = CSV.generate do |csv| csv << Record.csv_title ::CheckIn.all.each do |check_in| r = Record.new( check_in.created_at, check_in.meeting_date, check_in.club.name, check_in.club.leaders.all.map(&:name).uniq, check_in.attendance, check_in.notes ) csv << r.csv_contents end end puts csv_string end
class Record attr_accessor :created_at, :meeting_date, :club_name, :leader_names, :attendance, :notes def initialize(created_at, meeting_date, club_name, leader_names, attendance, notes) @created_at = created_at @meeting_date = meeting_date @club_name = club_name @leader_names = leader_names @attendance = attendance @notes = notes end def self.csv_title ['Check In Completion Timestamp', 'Meeting Date', 'Club Name', 'Leaders', 'Attendance', 'Notes'] end def csv_contents [created_at, meeting_date, club_name, leader_names.join(', '), attendance, notes] end end desc 'Generate a report of all check ins' task check_ins: :environment do csv_string = CSV.generate do |csv| csv << Record.csv_title ::CheckIn.all.each do |check_in| r = Record.new( check_in.created_at, check_in.meeting_date, check_in.club.name, check_in.club.leaders.all.map(&:name).uniq, check_in.attendance, check_in.notes ) csv << r.csv_contents end end puts csv_string end
Check the AttachmentData is non-nil before trying to mutate it
class AssetManagerCreateWhitehallAssetWorker < WorkerBase include AssetManagerWorkerHelper sidekiq_options queue: 'asset_manager' def perform(file_path, legacy_url_path, draft = false, model_class = nil, model_id = nil) return unless File.exist?(file_path) file = File.open(file_path) asset_options = { file: file, legacy_url_path: legacy_url_path } asset_options[:draft] = true if draft if model_class && model_id model = model_class.constantize.find(model_id) if model.respond_to?(:access_limited?) if model.access_limited? authorised_user_uids = AssetManagerAccessLimitation.for(model) asset_options[:access_limited] = authorised_user_uids end end end asset_manager.create_whitehall_asset(asset_options) if model # sadly we can't just search for url, because it's a magic # carrierwave thing not in our model Attachment.where(attachable: model.attachables).where.not(attachment_data: nil).find_each do |attachment| if attachment.attachment_data.url == legacy_url_path attachment.attachment_data.uploaded_to_asset_manager! end end end FileUtils.rm(file) FileUtils.rmdir(File.dirname(file)) end end
class AssetManagerCreateWhitehallAssetWorker < WorkerBase include AssetManagerWorkerHelper sidekiq_options queue: 'asset_manager' def perform(file_path, legacy_url_path, draft = false, model_class = nil, model_id = nil) return unless File.exist?(file_path) file = File.open(file_path) asset_options = { file: file, legacy_url_path: legacy_url_path } asset_options[:draft] = true if draft if model_class && model_id model = model_class.constantize.find(model_id) if model.respond_to?(:access_limited?) if model.access_limited? authorised_user_uids = AssetManagerAccessLimitation.for(model) asset_options[:access_limited] = authorised_user_uids end end end asset_manager.create_whitehall_asset(asset_options) if model # sadly we can't just search for url, because it's a magic # carrierwave thing not in our model Attachment.where(attachable: model.attachables).where.not(attachment_data: nil).find_each do |attachment| # 'attachment.attachment_data' can still be nil even with the # check above, because if the 'attachment_data_id' is non-nil # but invalid, the 'attachment_data' will be nil - and the # generated SQL only checks if the 'attachment_data_id' is # nil. if attachment.attachment_data && attachment.attachment_data.url == legacy_url_path attachment.attachment_data.uploaded_to_asset_manager! end end end FileUtils.rm(file) FileUtils.rmdir(File.dirname(file)) end end
Rename Model from users to vip_clients
require 'sinatra' require 'data_mapper' require './helpers/birthday' require './models/users.rb' require './models/invitations.rb' DataMapper.setup(:default, ENV['DATABASE_URL']) get '/' do @vip_clients = VipClients.all send_invitations end def send_invitations return greetings if @vip_clients.any? end
require 'sinatra' require 'data_mapper' require './helpers/birthday' require './models/vip_clients.rb' require './models/invitations.rb' DataMapper.setup(:default, ENV['DATABASE_URL']) get '/' do @vip_clients = VipClients.all send_invitations end def send_invitations return greetings if @vip_clients.any? end
Enforce GUID being present for notifications
# frozen_string_literal: true class ChangeNotificationsGuidNotNull < ActiveRecord::Migration[5.2] def up Notification.where(guid: nil).find_in_batches do |batch| batch.each do |notification| notification.save!(validate: false, touch: false) end end change_column :notifications, :guid, :string, null: false end def down change_column :notifications, :guid, :string, null: true end end
Fix for typo in gemspec.
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "browser-timezone-rails/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "browser-timezone-rails" gem.version = '1.0.4' s.version = BrowserTimezoneRails::VERSION s.authors = ["kbaum"] s.email = ["karl.baum@gmail.com"] s.homepage = "https://github.com/kbaum/browser-timezone-rails" s.summary = "Sets the browser timezone within rails" s.description = "The browser timezone is set on the Time#zone" s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", ">= 3.1" s.add_dependency "js_cookie_rails" s.add_dependency "jstz-rails3-plus" s.add_development_dependency "rspec-rails" s.add_development_dependency "capybara" s.add_development_dependency "launchy" s.add_development_dependency "sqlite3" end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "browser-timezone-rails/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "browser-timezone-rails" s.version = '1.0.4' s.version = BrowserTimezoneRails::VERSION s.authors = ["kbaum"] s.email = ["karl.baum@gmail.com"] s.homepage = "https://github.com/kbaum/browser-timezone-rails" s.summary = "Sets the browser timezone within rails" s.description = "The browser timezone is set on the Time#zone" s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", ">= 3.1" s.add_dependency "js_cookie_rails" s.add_dependency "jstz-rails3-plus" s.add_development_dependency "rspec-rails" s.add_development_dependency "capybara" s.add_development_dependency "launchy" s.add_development_dependency "sqlite3" end
Correct index for song at specified rank
require 'nokogiri' require 'open-uri' module Cinch module Plugins class Mnet include Cinch::Plugin match /(mnet)$/ match /(mnet) (.+)/, method: :with_num match /(help mnet)$/, method: :help def execute(m) num = 1 page = Nokogiri::HTML(open("http://www.mnet.com/chart/top100/")) title = page.css('a.MMLI_Song')[num].text artist = page.css('div.MMLITitle_Info')[num].css('a.MMLIInfo_Artist').text date = page.css('ul.date li.day span.num_set2').text m.reply "Mnet Rank #{num}: #{artist} - #{title} | #{date}" end def with_num(m, prefix, mnet, num) return m.reply 'invalid num bru' if num.to_i < 1 return m.reply 'less than 51 bru' if num.to_i > 50 page = Nokogiri::HTML(open("http://www.mnet.com/chart/top100/")) title = page.css('a.MMLI_Song')[num.to_i].text artist = page.css('div.MMLITitle_Info')[num.to_i].css('a.MMLIInfo_Artist').text date = page.css('ul.date li.day span.num_set2').text m.reply "Mnet Rank #{num}: #{artist} - #{title} | #{date}" end def help(m) m.reply 'returns current song at specified mnet rank' end end end end
require 'nokogiri' require 'open-uri' module Cinch module Plugins class Mnet include Cinch::Plugin match /(mnet)$/ match /(mnet) (.+)/, method: :with_num match /(help mnet)$/, method: :help def execute(m) with_num(m, '.', 'mnet', 1) end def with_num(m, prefix, mnet, num) return m.reply 'invalid num bru' if num.to_i < 1 return m.reply 'less than 51 bru' if num.to_i > 50 page = Nokogiri::HTML(open("http://www.mnet.com/chart/top100/")) title = page.css('a.MMLI_Song')[num.to_i - 1].text artist = page.css('div.MMLITitle_Info')[num.to_i - 1].css('a.MMLIInfo_Artist').text date = page.css('ul.date li.day span.num_set2').text m.reply "Mnet Rank #{num}: #{artist} - #{title} | #{date}" end def help(m) m.reply 'returns current song at specified mnet rank' end end end end
Add tests for the user model
require 'lib/adauth' require 'yaml' ReturnDataForTest = [] class TestModel include Adauth::UserModel attr_accessor :login, :group_strings, :name, :ou_strings def self.create! @user = self.new yield(@user) return @user end def self.find_by_login(login) ReturnDataForTest.last end def save true end end describe TestModel, "creations" do before :each do @yaml = YAML::load(File.open('spec/test_data.yml')) Adauth.configure do |c| c.domain = @yaml["domain"]["domain"] c.server = @yaml["domain"]["server"] c.port = @yaml["domain"]["port"] c.base = @yaml["domain"]["base"] end @user = Adauth.authenticate(@yaml["user"]["login"], @yaml["user"]["password"]) end it "should create a new user for method `create_user_with_adauth`" do TestModel.create_user_with_adauth(@user).should be_a TestModel end it "should return a user for method `return_and_create_with_adauth`, if no user exists in the db" do ReturnDataForTest.push nil TestModel.return_and_create_with_adauth(@user).should be_a TestModel end it "should return a user for method `return_and_create_with_adauth`, if the user does exist" do ReturnDataForTest.push TestModel.create_user_with_adauth(@user) TestModel.return_and_create_with_adauth(@user).should be_a TestModel end end describe TestModel, "methods" do before :each do @yaml = YAML::load(File.open('spec/test_data.yml')) Adauth.configure do |c| c.domain = @yaml["domain"]["domain"] c.server = @yaml["domain"]["server"] c.port = @yaml["domain"]["port"] c.base = @yaml["domain"]["base"] end @user = Adauth.authenticate(@yaml["user"]["login"], @yaml["user"]["password"]) @model = TestModel.create_user_with_adauth(@user) end it "should return an array of groups for .groups" do @model.groups.should be_a Array end it "should return an array of ous for .ous" do @model.ous.should be_a Array end it "should update from adauth" do @model.name = "Adauth Testing user that should be different" @model.name.should_not eq(@user.name) @model.update_from_adauth(@user) @model.name.should eq(@user.name) end end
Add convert body with redcarpet markdown and tent markdown
require_dependency "tent/application_controller" module Tent class PagesController < ApplicationController def show site_path = params.fetch :site_path page_path = params.fetch :page_path, :index site = Site.where(path: site_path).first page = Page.where(site_id: site.id, path: page_path).first if page raise "#{site_path}/#{page_path} found" else raise "#{site_path}/#{page_path} not found" end end end end
require_dependency "tent/application_controller" require "html/pipeline" module Tent class PagesController < ApplicationController def show site_path = params.fetch :site_path page_path = params.fetch :page_path, :index site = Site.where(path: site_path).first page = Page.where(site_id: site.id, path: page_path).first unless page raise "#{site_path}/#{page_path} not found" end page.body = '##あいうえお tent tentですね。 ' @body = convert_body page.body end private def convert_body(body) pipeline = HTML::Pipeline.new [ Tent::Markdown::Filters::Redcarpet, Tent::Markdown::Filters::Tent ] result = pipeline.call(body) result[:output].to_s end end end
Backup database tables in a pre defined order.
namespace :db do desc 'Creates a database independent backup' task :export do Zen.database.tables.each do |table| handle = File.open( File.expand_path('../../tmp/%s' % table, __FILE__), 'w' ) handle.write(Marshal.dump([table, Zen.database[table].all])) handle.close end end desc 'Imports a database backup' task :import, :backup do |task, args| table, rows = Marshal.load(File.open(args[:backup], 'r').read) Zen.database[table].delete Zen.database[table].insert_multiple(rows) end end
namespace :db do table_order = [ :settings, :user_statuses, :users, :user_groups, :user_groups_users, :permissions, :sections, :section_entry_statuses, :section_entries, :comment_statuses, :comments, :category_groups, :categories, :category_groups_sections, :custom_field_methods, :custom_field_types, :custom_field_groups, :custom_fields, :custom_field_values, :custom_field_groups_sections, :menus, :menu_items, ] desc 'Creates a database independent backup' task :export do data = {} table_order.each do |table| data[table] = Zen.database[table].all end handle = File.open(File.expand_path('../../tmp/backup', __FILE__), 'w') handle.write(Marshal.dump(data)) handle.close end desc 'Imports a database backup' task :import, :backup do |task, args| data = Marshal.load(File.open(args[:backup], 'r').read) table_order.each do |table| Zen.database[table].delete Zen.database[table].insert_multiple(data[table]) end end end
Add a default paginator for api responses
JSONAPI.configure do |config| # built in paginators are :none, :offset, :paged config.default_paginator = :offset config.default_page_size = 10 config.maximum_page_size = 20 end
Use event created date time for RSS pubDate
xml.instruct! :xml, :version => "1.0" xml.rss :version => "2.0", "xmlns:atom" => "http://www.w3.org/2005/Atom" do xml.channel do xml.title "Startups of Puerto Rico" xml.description "A collection of Startup Events in Puerto Rico" xml.link events_url xml.tag! 'atom:link', :rel => 'self', :type => 'application/rss+xml', :href => events_url(format: :rss) for event in @events xml.item do xml.title event.name xml.description "At #{event.place} on #{event.date.strftime("%B %d @ %I:%M %p")}" xml.pubDate event.date.to_s(:rfc822) xml.link event.link xml.guid event.link end end end end
xml.instruct! :xml, :version => "1.0" xml.rss :version => "2.0", "xmlns:atom" => "http://www.w3.org/2005/Atom" do xml.channel do xml.title "Startups of Puerto Rico" xml.description "A collection of Startup Events in Puerto Rico" xml.link events_url xml.tag! 'atom:link', :rel => 'self', :type => 'application/rss+xml', :href => events_url(format: :rss) for event in @events xml.item do xml.title event.name xml.description "At #{event.place} on #{event.date.strftime("%B %d @ %I:%M %p")}" xml.pubDate event.created_at.to_s(:rfc822) xml.link event.link xml.guid event.link end end end end
Add call to task visitor
require 'digest' module GitCompound # Manifest # class Manifest < Node attr_accessor :name, :components, :tasks def initialize(contents, parent = nil) @contents = contents @parent = parent DSL::ManifestDSL.new(self, contents) end def process(*workers) workers.each { |worker| worker.visit_manifest(self) } components.each_value { |component| component.process(*workers) } end def ==(other) md5sum == other.md5sum end def md5sum Digest::MD5.hexdigest(@contents) end end end
require 'digest' module GitCompound # Manifest # class Manifest < Node attr_accessor :name, :components, :tasks def initialize(contents, parent = nil) @contents = contents @parent = parent DSL::ManifestDSL.new(self, contents) end def process(*workers) workers.each { |worker| worker.visit_manifest(self) } components.each_value { |component| component.process(*workers) } workers.each { |worker| tasks.each { |task| worker.visit_manifest(task) } } end def ==(other) md5sum == other.md5sum end def md5sum Digest::MD5.hexdigest(@contents) end end end
Use translated title to register with panopticon Introducing translation of the bank holiday calendar means that the translation key was being sent to panopticon instead of the translated title
require 'ostruct' # Takes a path and produces a calendar object for registering in # panopticon class RegisterableCalendar extend Forwardable attr_accessor :calendar, :slug, :live def_delegators :@calendar, :title, :description, :indexable_content def initialize(path) details = JSON.parse(File.read(path)) @calendar = OpenStruct.new(details) @slug = File.basename(path, '.json') end def state 'live' end def need_ids [@calendar.need_id.to_s] end def paths ["/#{@slug}.json"] end def prefixes ["/#{@slug}"] end end
require 'ostruct' # Takes a path and produces a calendar object for registering in # panopticon class RegisterableCalendar extend Forwardable attr_accessor :calendar, :slug, :live def_delegators :@calendar, :indexable_content def initialize(path) details = JSON.parse(File.read(path)) @calendar = OpenStruct.new(details) @slug = File.basename(path, '.json') end def title I18n.t(@calendar.title) end def description I18n.t(@calendar.description) end def state 'live' end def need_ids [@calendar.need_id.to_s] end def paths ["/#{@slug}.json"] end def prefixes ["/#{@slug}"] end end
Build extension files before testing
#!/usr/bin/env ruby require "test-unit" require "test/unit/notify" require "test/unit/rr" base_dir = File.expand_path(File.join(File.dirname(__FILE__), "..")) $LOAD_PATH.unshift(File.join(base_dir, "lib")) $LOAD_PATH.unshift(File.join(base_dir, "test")) exit Test::Unit::AutoRunner.run(true)
#!/usr/bin/env ruby require "test-unit" require "test/unit/notify" require "test/unit/rr" base_dir = File.expand_path(File.join(File.dirname(__FILE__), "..")) $LOAD_PATH.unshift(File.join(base_dir, "lib")) $LOAD_PATH.unshift(File.join(base_dir, "test")) ext_dir = File.join(base_dir, "ext") ext_osl_dir = File.join(ext_dir, "osl") $LOAD_PATH.unshift(ext_osl_dir) require "fileutils" FileUtils.cd(ext_osl_dir) do system("ruby", "extconf.rb") system("make") end exit Test::Unit::AutoRunner.run(true)
Add spec for dice roll service
require 'rails_helper' RSpec.describe RollDice, type: :service do let(:game_params) { { number_of_players: 2 } } let(:game) { Game.create!(game_params) } let(:user) { User.create!(username: "user") } let(:piece) { "wheelbarrow" } let(:player) { game.players.create!(user: user, piece: piece) } subject(:service) { RollDice.new(game: game, player: player) } context "when it is my turn" do # TODO how do we set up my turn?, override what game does describe "rolling the dice" do it "succeeds" do expect(service.call).to be_truthy end it "adds a dice roll" do expect { service.call }.to change(DiceRoll, :count).by(1) end it "adds the dice roll to the correct game" do service.call expect(DiceRoll.last.game).to eql game end it "adds the dice roll to the correct player" do service.call expect(DiceRoll.last.player).to eql player end it "has a valid dice roll" do service.call expect(DiceRoll.last.amount).to be_present expect(DiceRoll.last.amount).to be < 7 expect(DiceRoll.last.amount).to be > 0 end it "has no errors" do service.call expect(service.errors).not_to be_present end end end context "when it is not my turn" do # TODO how to set up?, this should fail end end
Use nokogiri + URI - much simpler now.
require 'hpricot' module ExtractUrls # Extract image URLs from HTML. def extract_image_urls(url, body) relative_url = url.gsub(/(https?:\/\/[^?]*)(\?.*)$*/, '\1'); if relative_url !~ /\/$/ then relative_url += "/" end url_head = relative_url.gsub(/(https?:\/\/[^\/]+\/).*/, '\1'); urls = [] doc = Hpricot(body) doc.search("a[@href]").each do |param| href = param.attributes["href"] if href.nil? then next end if href !~ /\.(png|jpg|jpeg)$/i then next end if href =~ /https?:\/\// then elsif href =~ /^\// then href = url_head + href elsif href !~ /https?:\/\// then href = relative_url + href end urls.push(href) end return urls end module_function :extract_image_urls end
require 'nokogiri' module ExtractUrls # Extract image URLs from HTML. def extract_image_urls(url, body) urls = [] Nokogiri::HTML(body).xpath('//a[@href]').each do |link| urls += [URI.join(url, link[:href]).to_s] if link[:href] =~ /\.(png|jpg|jpeg)\z/i end return urls end module_function :extract_image_urls end
Make sure there are any examples to pass.
Then /^the example(s)? should( all)? pass$/ do |_, _| step %q{the output should contain "0 failures"} step %q{the exit status should be 0} end
Then /^the example(s)? should( all)? pass$/ do |_, _| step %q{the output should match /^[^0][ 0-9]*examples?/} step %q{the output should contain "0 failures"} step %q{the exit status should be 0} end
Install haskell platform with GHC 7 from a PPA
# # Cookbook Name:: haskell # Recipe:: default # Copyright 2012, Travis CI development team # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. package "haskell-platform" do action :install end
# # Cookbook Name:: haskell # Recipe:: default # Copyright 2012, Travis CI development team # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. case node['platform'] when "ubuntu" apt_repository "mbeloborodiy_haskell_platform" do uri "http://ppa.launchpad.net/mbeloborodiy/ppa/ubuntu/" distribution node['lsb']['codename'] components ['main'] key "F6B6FC93" keyserver "keyserver.ubuntu.com" action :add end end package "haskell-platform" do action :install end
Enable javascript_driver on checkout address page
require 'spec_helper' RSpec.describe SolidusPageObjects::Pages::Checkout::Address do let(:order) { OrderWalkthrough.up_to(:address) } let(:user) { create(:user) } before do order.update_attribute(:user, user) allow_any_instance_of(Spree::CheckoutController).to receive_messages current_order: order, spree_current_user: user end it_behaves_like 'a page' do let(:page_path) { spree.checkout_state_path(:address) } end end
require 'spec_helper' RSpec.describe SolidusPageObjects::Pages::Checkout::Address, type: :feature, js: true do let(:order) { create(:order_with_line_items) } let(:user) { create(:user) } before do order.update_attribute(:user, user) allow_any_instance_of(Spree::CheckoutController).to receive_messages current_order: order, spree_current_user: user end it_behaves_like 'a page' do let(:page_path) { spree.checkout_state_path(:address) } end end
Remove useless to_a from full_matrix Levenshtein
# coding: utf-8 module StringMetric module Levenshtein class IterativeWithFullMatrix def self.distance(from, to, options = {}) return 0 if from == to return to.size if from.size.zero? return from.size if to.size.zero? max_distance = options[:max_distance] d = (0..to.size).map do |i| [0] * (from.size + 1) end (1..from.size).to_a.each { |j| d[0][j] = j } (1..to.size).to_a.each { |i| d[i][0] = i } (1..from.size).to_a.each do |j| (1..to.size).to_a.each do |i| if from[j-1] == to[i-1] d[i][j] = d[i -1][j-1] else d[i][j] = [d[i-1][j] + 1, # deletion d[i][j-1] + 1, # insertion d[i-1][j-1] + 1 # substitution ].min end end break if max_distance and d[j][j] > max_distance end x = d[to.size][from.size] if max_distance && x > max_distance max_distance else x end end end end end
# coding: utf-8 module StringMetric module Levenshtein class IterativeWithFullMatrix def self.distance(from, to, options = {}) return 0 if from == to return to.size if from.size.zero? return from.size if to.size.zero? max_distance = options[:max_distance] d = (0..to.size).map do |i| [0] * (from.size + 1) end (1..from.size).each { |j| d[0][j] = j } (1..to.size).each { |i| d[i][0] = i } (1..from.size).each do |j| (1..to.size).each do |i| if from[j-1] == to[i-1] d[i][j] = d[i -1][j-1] else d[i][j] = [d[i-1][j] + 1, # deletion d[i][j-1] + 1, # insertion d[i-1][j-1] + 1 # substitution ].min end end break if max_distance and d[j][j] > max_distance end x = d[to.size][from.size] if max_distance && x > max_distance max_distance else x end end end end end
Fix NameError when not connected
# rubocop:disable Style/FileName # By default, cql-rb grabs a random connection for each request. This is great for # keeping load distributed across the cluster. Unfortunately, it plays havoc with # the Solr integration where we often need to ensure that we're talking to the # Solr and Cassandra on the same node. For that reason, we cause the current # connection in use to stay fixed for 500 requests before rolling to the another. require 'cql' require 'cql/client/connection_manager' Cql::Client::ConnectionManager.class_eval do attr_reader :current_connection def random_connection fail NotConnectedError unless connected? @lock.synchronize do @count ||= 0 @count += 1 if @count > 500 @count = 0 @current_connection = nil end @current_connection ||= @connections.sample end end end require 'cql/client/client' Cql::Client::SynchronousClient.class_eval do def current_connection async.instance_variable_get(:@connection_manager).current_connection end end
# rubocop:disable Style/FileName # By default, cql-rb grabs a random connection for each request. This is great for # keeping load distributed across the cluster. Unfortunately, it plays havoc with # the Solr integration where we often need to ensure that we're talking to the # Solr and Cassandra on the same node. For that reason, we cause the current # connection in use to stay fixed for 500 requests before rolling to the another. require 'cql' require 'cql/client/connection_manager' Cql::Client::ConnectionManager.class_eval do attr_reader :current_connection def random_connection fail Cql::NotConnectedError unless connected? @lock.synchronize do @count ||= 0 @count += 1 if @count > 500 @count = 0 @current_connection = nil end @current_connection ||= @connections.sample end end end require 'cql/client/client' Cql::Client::SynchronousClient.class_eval do def current_connection async.instance_variable_get(:@connection_manager).current_connection end end
Exit with the number of failures
$:.unshift(ENV['JASMINE_GEM_PATH']) if ENV['JASMINE_GEM_PATH'] # for gem testing purposes require 'rubygems' require 'jasmine' require 'rspec' Jasmine.load_configuration_from_yaml config = Jasmine.config server = Jasmine::Server.new(config.port, Jasmine::Application.app(config)) driver = Jasmine::SeleniumDriver.new(config.browser, "#{config.host}:#{config.port}/") t = Thread.new do begin server.start rescue ChildProcess::TimeoutError end # # ignore bad exits end t.abort_on_exception = true Jasmine::wait_for_listener(config.port, 'jasmine server') puts 'jasmine server started.' reporter = Jasmine::Reporters::ApiReporter.new(driver, config.result_batch_size) raw_results = Jasmine::Runners::HTTP.new(driver, reporter).run results = Jasmine::Results.new(raw_results) config.formatters.each do |formatter_class| formatter = formatter_class.new(results) formatter.format() end
$:.unshift(ENV['JASMINE_GEM_PATH']) if ENV['JASMINE_GEM_PATH'] # for gem testing purposes require 'rubygems' require 'jasmine' require 'rspec' Jasmine.load_configuration_from_yaml config = Jasmine.config server = Jasmine::Server.new(config.port, Jasmine::Application.app(config)) driver = Jasmine::SeleniumDriver.new(config.browser, "#{config.host}:#{config.port}/") t = Thread.new do begin server.start rescue ChildProcess::TimeoutError end # # ignore bad exits end t.abort_on_exception = true Jasmine::wait_for_listener(config.port, 'jasmine server') puts 'jasmine server started.' reporter = Jasmine::Reporters::ApiReporter.new(driver, config.result_batch_size) raw_results = Jasmine::Runners::HTTP.new(driver, reporter).run results = Jasmine::Results.new(raw_results) config.formatters.each do |formatter_class| formatter = formatter_class.new(results) formatter.format() end exit results.failures.size
Replace initialize with @cards setter
class AddACardValue def initialize (cards) @cards = cards end def values {"Two" => 2, "Three" => 3, "Four" => 4, "Five" => 5, "Six" => 6, "Seven" => 7, "Eight" => 8, "Nine" => 9, "Ten" => 10, "Jack" => 10, "Queen" => 10, "King" => 10, "Ace" => 10} end def value @cards.reduce(0) do |sum_of_values, card| sum_of_values + values[card.rank] end end end
class AddACardValue def cards(c) @cards = c end def values {"Two" => 2, "Three" => 3, "Four" => 4, "Five" => 5, "Six" => 6, "Seven" => 7, "Eight" => 8, "Nine" => 9, "Ten" => 10, "Jack" => 10, "Queen" => 10, "King" => 10, "Ace" => 10} end def value @cards.reduce(0) do |sum_of_values, card| sum_of_values + values[card.rank] end end end
Fix spelling error in info sidebar.
module ArtifactsHelper def temportal_facet_path(params, low, high) artifacts_path(params.dup.update(low_date: low, high_date: high, page: 1)) end def temporal_facet_menu_item(params, low, high, text=nil) text = "#{low} &ndash; #{high}".html_safe unless text.present? if params[:low_date].present? && params[:low_date].to_i == low return "#{text}<i class=\"icon-ok\"></i>".html_safe else return link_to text, temportal_facet_path(params, low, high) end end def display_fields [ {field: 'accession_number', label: 'Accession Number'}, {field: 'origin', label: 'Origin'}, {field: 'prob_date', label: 'Probable Date'}, {field: 'artist', label: 'Artist'}, {field: 'school_period', label: 'School/Period'}, {field: 'materials', label: 'Materials'}, {field: 'measure', label: 'Measure'}, {field: 'weight', label: 'Weight'} ] end def return_link link_text, return_path = if request.referrer == root_url ['Return to Homepage', root_path] else ['Reture to Search', artifacts_path(session[:search_params])] end link_to link_text, return_path, class: 'btn btn-inverse', style: 'margin-top: 10px;' end end
module ArtifactsHelper def temportal_facet_path(params, low, high) artifacts_path(params.dup.update(low_date: low, high_date: high, page: 1)) end def temporal_facet_menu_item(params, low, high, text=nil) text = "#{low} &ndash; #{high}".html_safe unless text.present? if params[:low_date].present? && params[:low_date].to_i == low return "#{text}<i class=\"icon-ok\"></i>".html_safe else return link_to text, temportal_facet_path(params, low, high) end end def display_fields [ {field: 'accession_number', label: 'Accession Number'}, {field: 'origin', label: 'Origin'}, {field: 'prob_date', label: 'Probable Date'}, {field: 'artist', label: 'Artist'}, {field: 'school_period', label: 'School/Period'}, {field: 'materials', label: 'Materials'}, {field: 'measure', label: 'Measure'}, {field: 'weight', label: 'Weight'} ] end def return_link link_text, return_path = if request.referrer == root_url ['Return to Homepage', root_path] else ['Return to Search', artifacts_path(session[:search_params])] end link_to link_text, return_path, class: 'btn btn-inverse', style: 'margin-top: 10px;' end end
Add a Homebrew formula for Tinkey.
# A Homebrew formula for Tinkey on Linux and macOS. # Usage: # brew tap google/tink https://github.com/google/tink # brew install tinkey class Tinkey < Formula desc "A command line tool to generate and manipulate keysets for the Tink cryptography library" homepage "https://github.com/google/tink/tree/master/tools/tinkey" url "https://storage.googleapis.com/tinkey/tinkey-darwin-x86_64-1.4.0.tar.gz" sha256 "cd4a79a3c78084e6d0b4d82cc0e2f903cb0f18d6d75c7c897512f7804be50dba" on_linux do url "https://storage.googleapis.com/tinkey/tinkey-linux-x86_64-1.4.0.tar.gz" sha256 "b36521a05fc59b6541bd4119df9f1cc392a509ed914efe763b92c50b87f4159f" end bottle :unneeded def install bin.install "tinkey" bin.install "tinkey_deploy.jar" end end
Use debugger gem for ruby 1.9 in rails template
require 'alchemy/version' # This rails template installs Alchemy and all depending gems. # Installing Alchemy Gem gem 'alchemy_cms', "~> #{Alchemy::VERSION}" gem 'ruby-debug', :group => :development, :platform => :ruby_18 gem 'ruby-debug19', :group => :development, :platform => :ruby_19 if yes?("\nDo you want to use Capistrano for deployment? (y/N)") gem 'capistrano', :group => :development end run 'bundle install'
require 'alchemy/version' # This rails template installs Alchemy and all depending gems. # Installing Alchemy Gem gem 'alchemy_cms', "~> #{Alchemy::VERSION}" gem 'ruby-debug', :group => :development, :platform => :ruby_18 gem 'debugger', :group => :development, :platform => :ruby_19 if yes?("\nDo you want to use Capistrano for deployment? (y/N)") gem 'capistrano', :group => :development end run 'bundle install'
Scale down Unicorn worker count
preload_app true worker_processes 2 timeout 30 check_client_connection true listen '/u/apps/handy/shared/sockets/unicorn.sock', backlog: 2048 pid '/u/apps/handy/shared/pids/unicorn.pid' stderr_path '/u/apps/handy/shared/log/unicorn.log' stdout_path '/u/apps/handy/shared/log/unicorn.log' working_directory '/u/apps/handy/current' after_fork do |server, worker| ActiveRecord::Base.clear_all_connections! if defined?(ActiveRecord::Base) end
preload_app true worker_processes 1 timeout 30 check_client_connection true listen '/u/apps/handy/shared/sockets/unicorn.sock', backlog: 2048 pid '/u/apps/handy/shared/pids/unicorn.pid' stderr_path '/u/apps/handy/shared/log/unicorn.log' stdout_path '/u/apps/handy/shared/log/unicorn.log' working_directory '/u/apps/handy/current' after_fork do |server, worker| ActiveRecord::Base.clear_all_connections! if defined?(ActiveRecord::Base) end
Revert "Retrieve hooks for a given repo"
require "httparty" module GotFixed module Adapters class Github include HTTParty base_uri "https://api.github.com" def initialize(auth_token) @auth_token = auth_token end # Retrieve all issues of a given GitHub repository matching given labels # Labels must be comma separated, e.g. "public,foo,bar" # # Doc: http://developer.github.com/v3/issues/#list-issues-for-a-repository def issues(options) owner = options[:owner] repo = options[:repo] labels = options[:labels] opened = issues_with_state(owner, repo, labels, :open) closed = issues_with_state(owner, repo, labels, :closed) opened + closed end def hooks(owner, repo) self.class.get "/repos/#{owner}/#{repo}/hooks", :query => { :auth_token => @auth_token } end private def issues_with_state(owner, repo, labels, state) query = { :labels => labels, :auth_token => @auth_token } self.class.get "/repos/#{owner}/#{repo}/issues", :query => query.merge(:state => state) end end end end
require "httparty" module GotFixed module Adapters class Github include HTTParty base_uri "https://api.github.com" def initialize(auth_token) @auth_token = auth_token end # Retrieve all issues of a given GitHub repository matching given labels # Labels must be comma separated, e.g. "public,foo,bar" # # Doc: http://developer.github.com/v3/issues/#list-issues-for-a-repository def issues(options) owner = options[:owner] repo = options[:repo] labels = options[:labels] opened = issues_with_state(owner, repo, labels, :open) closed = issues_with_state(owner, repo, labels, :closed) opened + closed end private def issues_with_state(owner, repo, labels, state) query = { :labels => labels, :auth_token => @auth_token } self.class.get "/repos/#{owner}/#{repo}/issues", :query => query.merge(:state => state) end end end end
Change users' QR code size to 6
require "rqrcode" module Spree module Admin UsersController.class_eval do def qr user = User.find(params[:id]) code = { :profile => { :name => user.email, :server => request.host, :port => request.port, :key => user.api_key } } @qr = RQRCode::QRCode.new(code.to_json, :size => 8, :level => :m) respond_with { |format| format.html } end end end end
require "rqrcode" module Spree module Admin UsersController.class_eval do def qr user = User.find(params[:id]) code = { :profile => { :name => user.email, :server => request.host, :port => request.port, :key => user.api_key } } @qr = RQRCode::QRCode.new(code.to_json, :size => 6, :level => :l) respond_with { |format| format.html } end end end end
Fix login error when password_digest is nil.
module AwesomeAccess::ActionControllerConcern extend ActiveSupport::Concern included do end private def awesome_access_restrict redirect_to AwesomeAccess.configuration.redirect_restricted unless awesome_access_person end def awesome_access_authenticate(email, password) if person = Person.where(email: email).where(active: true).first.try(:authenticate, password) session[:awesome_access] = {} session[:awesome_access][:person_id] = person.id if person.password_token person.password_token = '' person.save end person.last_seen = DateTime.now person.save return true end false end def awesome_access_person return @awesome_access_person ||= Person.find(session[:awesome_access][:person_id]) if session[:awesome_access] end def awesome_access_person=(person) if session[:awesome_access] return session[:awesome_access][:person_id] = person.id end false end def awesome_access_destroy if session[:awesome_access] session[:awesome_access] = nil return true end false end end
module AwesomeAccess::ActionControllerConcern extend ActiveSupport::Concern included do end private def awesome_access_restrict redirect_to AwesomeAccess.configuration.redirect_restricted unless awesome_access_person end def awesome_access_authenticate(email, password) if person = Person.where(email: email).where(active: true).first if person.password_digest != nil if person.authenticate password session[:awesome_access] = {} session[:awesome_access][:person_id] = person.id if person.password_token person.password_token = '' end person.last_seen = DateTime.now person.save return true end end end false end def awesome_access_person return @awesome_access_person ||= Person.find(session[:awesome_access][:person_id]) if session[:awesome_access] end def awesome_access_person=(person) if session[:awesome_access] return session[:awesome_access][:person_id] = person.id end false end def awesome_access_destroy if session[:awesome_access] session[:awesome_access] = nil return true end false end end
Add review controller to api.
module ApiFlashcards module Api module V1 class ReviewController < ApiFlashcards::ApiController def index if params[:id] @card = current_user.cards.find(params[:id]) else @card = first_repeating_or_pending_card end render json: @card, status: :ok end def review_card @card = current_user.cards.find(params[:card_id]) check_result = @card.check_translation(review_params[:user_translation]) if check_result[:state] handle_correct_answer(check_result[:distance]) else flash[:alert] = t(:incorrect_translation_alert) render json: { message: 'Incorrect answer' }, status: :ok end end private def review_params params.permit(:user_translation) end def first_repeating_or_pending_card if current_user.current_block current_user.current_block.cards.first_repeating_or_pending_card else current_user.cards.first_repeating_or_pending_card end end def handle_correct_answer(distance) if distance == 0 render json: { message: 'Correct answer' }, status: :ok else render json: { message: "You entered translation from misprint. Please try again" }, status: :ok end end end end end end
Add chef-spec for backup recipe
require_relative '../spec_helper' describe 'backup_restore::backup' do let(:chef_run) do runner = ChefSpec::Runner.new( cookbook_path: %w(site-cookbooks cookbooks), platform: 'centos', version: '6.5' )do |node| node.set['backup_restore']['sources']['enabled'] = %w(directory mysql ruby) end runner.converge(described_recipe) end it 'run directory backup' do expect(chef_run).to include_recipe('backup_restore::backup_directory') end it 'run mysql backup' do expect(chef_run).to include_recipe('backup_restore::backup_mysql') end it 'run ruby backup' do expect(chef_run).to include_recipe('backup_restore::backup_ruby') end end
Add data migration to clean up blank outcomes
require 'benchmark' time = Benchmark.realtime do blank_outcomes = ConsultationOutcome.all.select {|co| co.summary.blank? && co.attachments.empty? } puts "Deleting #{blank_outcomes.size} blank consultation outcomes" blank_outcomes.each do |outcome| outcome.destroy print '.' end puts "\nAll done" end puts time
Add test for unauthorized bids.
require 'spec_helper' describe BidsController do before :all do @model = Bid @generator = Factory :auction_generator end before do @generator.bids.delete end context "as an admin" do before :all do @state = Factory :state end before do State.stubs(:find_by_game).returns(@state) login_as_admin end context "POST" do before :all do @data = Factory.attributes_for(:bid, :generator => @generator).update( Factory(:bid, :generator => @generator).attributes) end before do Generator.find(@data["generator_id"]).bids.each do |bid| bid.delete end end it_should_behave_like "standard successful POST create" def redirect_path generator_path assigns(:bid).generator end end end context "as a player" do before :all do login end context "POST for a generator not owned by this user" do it "should return not authorized" end end end
require 'spec_helper' describe BidsController do before :all do @model = Bid @generator = Factory :auction_generator end before do @generator.bids.delete end context "as an admin" do before :all do @state = Factory :state end before do State.stubs(:find_by_game).returns(@state) login_as_admin end context "POST" do before :all do @data = Factory.attributes_for(:bid, :generator => @generator).update( Factory(:bid, :generator => @generator).attributes) end before do Generator.find(@data["generator_id"]).bids.each do |bid| bid.delete end end it_should_behave_like "standard successful POST create" def redirect_path generator_path assigns(:bid).generator end end end context "as a player" do before :all do login end context "POST for a generator not owned by this user" do before do @generator.bids.each do |bid| bid.delete end end before :all do @generator.bids.each do |bid| bid.delete end @data = Factory.attributes_for(:bid, :generator => @generator).update( Factory(:bid, :generator => @generator).attributes) end it_should_behave_like "unauthorized POST create" end end end
Allow HTTP connections to codeclimate.com.
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'codeclimate-test-reporter' CodeClimate::TestReporter.start require 'sinclair' require 'webmock' def ignore_whitespace(str) str.gsub(/\s/, '') end def xml_fixture_for(file) File.read(File.join('spec', 'fixtures', "#{file}.xml")) end def stub_xml_request(options = {}) request = ignore_whitespace(xml_fixture_for(options[:request])) response = xml_fixture_for(options[:response]) WebMock.stub_request(:post, 'https://www.openair.com/api.pl').with do |r| ignore_whitespace(r.body) == request end.to_return(status: 200, body: response) end
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'codeclimate-test-reporter' CodeClimate::TestReporter.start require 'sinclair' require 'webmock' WebMock.disable_net_connect!(allow_localhost: true, allow: 'codeclimate.com') def ignore_whitespace(str) str.gsub(/\s/, '') end def xml_fixture_for(file) File.read(File.join('spec', 'fixtures', "#{file}.xml")) end def stub_xml_request(options = {}) request = ignore_whitespace(xml_fixture_for(options[:request])) response = xml_fixture_for(options[:response]) WebMock.stub_request(:post, 'https://www.openair.com/api.pl').with do |r| ignore_whitespace(r.body) == request end.to_return(status: 200, body: response) end
Revert "Show profiler info to mlandauer in production"
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_filter :authorize_miniprofiler def authorize_miniprofiler # Only show Miniprofiler stats in production to mlandauer if current_user && current_user.nickname == "mlandauer" Rack::MiniProfiler.authorize_request end end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception end
Make domain-name check use environment variable
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception include SessionsHelper before_action :check_domain def check_domain if Rails.env.production? && request.host.casecmp('j-scorer.com') != 0 redirect_to 'https://j-scorer.com' + request.fullpath, status: 301 end end private # Confirms that a user is logged in. def logged_in_user unless logged_in? store_location flash[:danger] = 'Please log in.' redirect_to login_url end end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception include SessionsHelper before_action :check_domain def check_domain # if Rails.env.production? && request.host.casecmp('j-scorer.com') != 0 if Rails.env.production? && request.host.casecmp(ENV['PROPER_DOMAIN']) != 0 url = "https://#{ENV['PROPER_DOMAIN']}#{request.fullpath}", status: 301 redirect_to url # redirect_to 'https://j-scorer.com' + request.fullpath, status: 301 end end private # Confirms that a user is logged in. def logged_in_user unless logged_in? store_location flash[:danger] = 'Please log in.' redirect_to login_url end end end
Add invitee email to invitations
class AddEmailToInvitations < ActiveRecord::Migration def self.up add_column :invitations, :invitee_email, :string end def self.down remove_column :invitations, :invitee_email end end
Update gir_ffi and gir_ffi-gtk to 0.12.0
# frozen_string_literal: true Gem::Specification.new do |s| s.name = 'atspi_app_driver' s.version = '0.2.0' s.summary = 'Test GirFFI-based applications using Atspi' s.required_ruby_version = '>= 2.3.0' s.authors = ['Matijs van Zuijlen'] s.email = ['matijs@matijs.net'] s.homepage = 'http://www.github.com/mvz/atspi_app_driver' s.files = [ 'lib/atspi_app_driver.rb', 'README.md', 'Changelog.md', 'LICENSE', 'Rakefile', 'Gemfile' ] s.add_dependency('gir_ffi', ['~> 0.11.0']) s.add_development_dependency('bundler') s.add_development_dependency('gir_ffi-gtk', ['~> 0.11.0']) s.add_development_dependency('minitest', ['~> 5.5']) s.add_development_dependency('rake', ['~> 12.0']) end
# frozen_string_literal: true Gem::Specification.new do |s| s.name = 'atspi_app_driver' s.version = '0.2.0' s.summary = 'Test GirFFI-based applications using Atspi' s.required_ruby_version = '>= 2.3.0' s.authors = ['Matijs van Zuijlen'] s.email = ['matijs@matijs.net'] s.homepage = 'http://www.github.com/mvz/atspi_app_driver' s.files = [ 'lib/atspi_app_driver.rb', 'README.md', 'Changelog.md', 'LICENSE', 'Rakefile', 'Gemfile' ] s.add_dependency('gir_ffi', ['~> 0.12.0']) s.add_development_dependency('bundler') s.add_development_dependency('gir_ffi-gtk', ['~> 0.12.0']) s.add_development_dependency('minitest', ['~> 5.5']) s.add_development_dependency('rake', ['~> 12.0']) end
Load user configuration from ~/.config vs ~/config.
# lib/frecon/configuration_file.rb # # Copyright (C) 2015 Christopher Cooper, Sam Craig, Tiger Huang, Vincent Mai, Sam Mercier, and Kristofer Rye # # This file is part of FReCon, an API for scouting at FRC Competitions, which is # licensed under the MIT license. You should have received a copy of the MIT # license with this program. If not, please see # <http://opensource.org/licenses/MIT>. require "yaml" require "frecon/configuration" module FReCon class ConfigurationFile attr_accessor :filename def initialize(filename) @filename = filename end def read begin data = open(@filename, "rb") do |io| io.read end Configuration.new(YAML.load(data)) rescue Errno::ENOENT nil end end def self.default self.new(File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "config", "default.yml"))) end def self.system self.new(File.join("", "etc", "frecon", "config.yml")) end def self.user self.new(File.join(Dir.home, "config", "frecon.yml")) end end end
# lib/frecon/configuration_file.rb # # Copyright (C) 2015 Christopher Cooper, Sam Craig, Tiger Huang, Vincent Mai, Sam Mercier, and Kristofer Rye # # This file is part of FReCon, an API for scouting at FRC Competitions, which is # licensed under the MIT license. You should have received a copy of the MIT # license with this program. If not, please see # <http://opensource.org/licenses/MIT>. require "yaml" require "frecon/configuration" module FReCon class ConfigurationFile attr_accessor :filename def initialize(filename) @filename = filename end def read begin data = open(@filename, "rb") do |io| io.read end Configuration.new(YAML.load(data)) rescue Errno::ENOENT nil end end def self.default self.new(File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "config", "default.yml"))) end def self.system self.new(File.join("", "etc", "frecon", "config.yml")) end def self.user self.new(File.join(Dir.home, ".config", "frecon.yml")) end end end