Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Introduce LoadError, mixing in Terrestrial::Error | module Terrestrial
Error = Module.new
end
| module Terrestrial
Error = Module.new
class LoadError < RuntimeError
include Error
def initialize(relation_name, factory, record, original_error)
@relation_name = relation_name
@factory = factory
@record = record
@original_error = original_error
end
attr_reader :relation_name, :factory, :record, :original_error
private :relation_name, :factory, :record, :original_error
def message
[
"Error loading record from `#{relation_name}` relation `#{record.inspect}`.",
"Using: `#{factory.inspect}`.",
"Check that the factory is compatible.",
"Got Error: #{original_error.class.name} #{original_error.message}",
].join("\n")
end
end
end
|
Include non-Ruby files in gem package | # Copyright 2013 Google Inc. All Rights Reserved.
# Licensed under the Apache License, Version 2.0, found in the LICENSE file.
Gem::Specification.new do |spec|
spec.name = "rack-allocation_stats"
spec.version = "0.1.0"
spec.authors = ["Sam Rawlins"]
spec.email = ["sam.rawlins@gmail.com"]
spec.license = "Apache v2"
spec.summary = "Rack middleware for tracing object allocations in Ruby 2.1"
spec.description = "Rack middleware for tracing object allocations in Ruby 2.1"
#spec.files = `git ls-files`.split("\n")
spec.files = `find . -path "*.rb"`.split("\n")
spec.require_paths = ["lib"]
spec.add_dependency "allocation_stats"
spec.add_dependency "yajl-ruby"
#spec.add_dependency "pry"
spec.add_development_dependency "rspec"
# ">= 2.1.0" seems logical, but rubygems thought that "2.1.0.dev.0" did not fit that bill.
# "> 2.0.0" was my next guess, but apparently "2.0.0.247" _does_ fit that bill.
spec.required_ruby_version = "> 2.0.99"
end
| # Copyright 2013 Google Inc. All Rights Reserved.
# Licensed under the Apache License, Version 2.0, found in the LICENSE file.
Gem::Specification.new do |spec|
spec.name = "rack-allocation_stats"
spec.version = "0.1.0"
spec.authors = ["Sam Rawlins"]
spec.email = ["sam.rawlins@gmail.com"]
spec.license = "Apache v2"
spec.summary = "Rack middleware for tracing object allocations in Ruby 2.1"
spec.description = "Rack middleware for tracing object allocations in Ruby 2.1"
spec.files = Dir.glob('{lib,spec}/**/*') + %w[LICENSE README.markdown TODO.markdown]
spec.require_paths = ["lib"]
spec.add_dependency "allocation_stats"
spec.add_dependency "yajl-ruby"
#spec.add_dependency "pry"
spec.add_development_dependency "rspec"
# ">= 2.1.0" seems logical, but rubygems thought that "2.1.0.dev.0" did not fit that bill.
# "> 2.0.0" was my next guess, but apparently "2.0.0.247" _does_ fit that bill.
spec.required_ruby_version = "> 2.0.99"
end
|
Change requires from absolute to relative paths | require 'mongo'
require 'dm-core'
require 'dm-aggregates'
dir = Pathname(__FILE__).dirname.expand_path + 'dm-mongo-adapter'
require dir + 'query'
require dir + 'query' + 'java_script'
require dir + 'property' + 'bson_object_id'
require dir + 'property' + 'foreign_object_id'
require dir + 'property' + 'object_id'
require dir + 'property' + 'array'
require dir + 'property' + 'hash'
require dir + 'support' + 'class'
require dir + 'support' + 'date'
require dir + 'support' + 'date_time'
require dir + 'support' + 'object'
require dir + 'migrations'
require dir + 'model'
require dir + 'resource'
require dir + 'migrations'
require dir + 'modifier'
require dir + 'aggregates'
require dir + 'adapter'
| require 'mongo'
require 'dm-core'
require 'dm-aggregates'
require 'dm-mongo-adapter/query'
require 'dm-mongo-adapter/query/java_script'
require 'dm-mongo-adapter/property/bson_object_id'
require 'dm-mongo-adapter/property/foreign_object_id'
require 'dm-mongo-adapter/property/object_id'
require 'dm-mongo-adapter/property/array'
require 'dm-mongo-adapter/property/hash'
require 'dm-mongo-adapter/support/class'
require 'dm-mongo-adapter/support/date'
require 'dm-mongo-adapter/support/date_time'
require 'dm-mongo-adapter/support/object'
require 'dm-mongo-adapter/migrations'
require 'dm-mongo-adapter/model'
require 'dm-mongo-adapter/resource'
require 'dm-mongo-adapter/migrations'
require 'dm-mongo-adapter/modifier'
require 'dm-mongo-adapter/aggregates'
require 'dm-mongo-adapter/adapter'
|
ADD bfs in (POST /api/vi/results) | class Api::V1::ResultsController < ApplicationController
protect_from_forgery except: [:index, :create, :show]
def index
hs = Result.all
render :json => hs
end
def create
param = searchParams
########################
# chains = awesomeMethod params[:from], params[:to]
# => [@node, @node, @node]
chains = [1, 2, 3, 4, 5]
########################
result = Result.new
if result.save
chains.each do |node_id|
result_item = ResultItem.new result_id: result.id, node_id: node_id
result_item.save
end
render json: result
else
render json: result
end
end
def show
ri = ResultItem.where(result_id: params['results_id'])
render :json => ri
end
private
def searchParams
params.require(:result).permit(:from, :to)
end
end
| # -*- coding: undecided -*-
class Api::V1::ResultsController < ApplicationController
protect_from_forgery except: [:index, :create, :show]
def index
hs = Result.all
render :json => hs
end
def bfs(client, open_list=[], check_list=[], from_id, to_id)
records = client.query("select to_id from wikipedia_edges where from_id = '#{from_id}' limit 100").to_a.map{|record| record['to_id']}
check_list.push from_id
open_list.concat records
return true if records.include? to_id
records.each do |next_from_id|
unless check_list.include? next_from_id
bfs(client, open_list, check_list, next_from_id, to_id)
end
end
return 0
end
def create
param = searchParams
ids = client.query("select id, word from wikipedia_nodes where word = '#{params[:from]}' or word = '#{params[:to]}'").to_a.map{|record| record['id']}
from_id = ids[0]
to_id = ids[1]
chains = Array.new
########################
# chains = awesomeMethod params[:from], params[:to]
# => [@node, @node, @node]
# chains = [1, 2, 3, 4, 5]
########################
chains.push(from_id)
chains.push(bfs(client, [], [], from_id, to_id))
chains.push(to_id)
result = Result.new
if result.save
chains.each do |node_id|
result_item = ResultItem.new result_id: result.id, node_id: node_id
result_item.save
end
render json: result
else
render json: result
end
end
def show
ri = ResultItem.where(result_id: params['results_id'])
render :json => ri
end
private
def searchParams
params.require(:result).permit(:from, :to)
end
end
|
Extend aruba timeout in order to have plenty of time to debug. | require 'aruba/cucumber'
require 'methadone/cucumber'
ENV['PATH'] = "#{File.expand_path(File.dirname(__FILE__) + '/../../bin')}#{File::PATH_SEPARATOR}#{ENV['PATH']}"
LIB_DIR = File.join(File.expand_path(File.dirname(__FILE__)),'..','..','lib')
Before do
# Using "announce" causes massive warnings on 1.9.2
@puts = true
@original_rubylib = ENV['RUBYLIB']
ENV['RUBYLIB'] = LIB_DIR + File::PATH_SEPARATOR + ENV['RUBYLIB'].to_s
end
After do
ENV['RUBYLIB'] = @original_rubylib
end
| require 'aruba/cucumber'
require 'methadone/cucumber'
ENV['PATH'] = "#{File.expand_path(File.dirname(__FILE__) + '/../../bin')}#{File::PATH_SEPARATOR}#{ENV['PATH']}"
LIB_DIR = File.join(File.expand_path(File.dirname(__FILE__)),'..','..','lib')
Before do
@aruba_timeout_seconds = 3600
# Using "announce" causes massive warnings on 1.9.2
@puts = true
@original_rubylib = ENV['RUBYLIB']
ENV['RUBYLIB'] = LIB_DIR + File::PATH_SEPARATOR + ENV['RUBYLIB'].to_s
end
After do
ENV['RUBYLIB'] = @original_rubylib
end
|
Add new_file_full_path method on Rugged::Diff::Delta | module Rugged
class Diff
class Delta
def new_blob
blob(new_file)
end
def old_blob
blob(old_file)
end
def repo
diff.tree.repo
end
private
def blob(file)
return if file.nil?
return if file[:oid] == '0000000000000000000000000000000000000000'
repo.lookup(file[:oid])
end
end
end
end
| module Rugged
class Diff
class Delta
def repo
diff.tree.repo
end
def new_file_full_path
repo_path = Pathname.new(repo.path).parent
repo_path.join(new_file[:path])
end
end
end
end
|
Handle non-strings a little better? | module X
module Editable
module Rails
module ViewHelpers
def editable(object, method, options = {})
data_url = polymorphic_path(object)
object = object.last if object.kind_of?(Array)
if xeditable? and can?(:edit, object)
model_param = object.class.name.split('::').last.underscore
klass = options[:nested] ? object.class.const_get(options[:nested].to_s.singularize.capitalize) : object.class
tag = options.fetch(:tag, 'span')
title = options.fetch(:title, klass.human_attribute_name(method))
data = {
type: options.fetch(:type, 'text'),
model: model_param,
name: method,
url: data_url,
nested: options[:nested],
nid: options[:nid]
}.merge options.fetch(:data, {})
content_tag tag, class: 'editable', title: title, data: data do
object.send(method).try(:html_safe)
end
else
options.fetch(:e, object.send(method)).try(:html_safe)
end
end
end
end
end
end
| module X
module Editable
module Rails
module ViewHelpers
def editable(object, method, options = {})
data_url = polymorphic_path(object)
object = object.last if object.kind_of?(Array)
value = object.send(method)
value = value.html_safe if value.respond_to? :html_safe
if xeditable? and can?(:edit, object)
model_param = object.class.name.split('::').last.underscore
klass = options[:nested] ? object.class.const_get(options[:nested].to_s.singularize.capitalize) : object.class
tag = options.fetch(:tag, 'span')
title = options.fetch(:title, klass.human_attribute_name(method))
data = {
type: options.fetch(:type, 'text'),
model: model_param,
name: method,
url: data_url,
nested: options[:nested],
nid: options[:nid]
}.merge options.fetch(:data, {})
content_tag tag, class: 'editable', title: title, data: data do
value
end
else
options.fetch(:e, value)
end
end
end
end
end
end
|
Remove redundant code and add message about (lack of) decryption capability | require_relative 'vdm_msg'
module NMEAPlus
module Message
module AIS
module VDMPayload
class VDMMsg8USCGEncrypted < NMEAPlus::Message::AIS::VDMPayload::VDMMsg
payload_reader :encrypted_data_2b, 56, 952, :_d
payload_reader :encrypted_data_6b, 56, 952, :_6b_string
payload_reader :encrypted_data_8b, 56, 952, :_8b_data_string
end
# Type 8: Binary Broadcast Message Subtype: US Coast Guard (USCG) blue force encrypted position report
class VDMMsg8d366f56 < VDMMsg8USCGEncrypted
payload_reader :encrypted_data_2b, 56, 952, :_d
payload_reader :encrypted_data_6b, 56, 952, :_6b_string
payload_reader :encrypted_data_8b, 56, 952, :_8b_data_string
end
# Type 8: Binary Broadcast Message Subtype: US Coast Guard (USCG) blue force encrypted data
class VDMMsg8d366f57 < VDMMsg8USCGEncrypted
payload_reader :encrypted_data_2b, 56, 952, :_d
payload_reader :encrypted_data_6b, 56, 952, :_6b_string
payload_reader :encrypted_data_8b, 56, 952, :_8b_data_string
end
end
end
end
end
| require_relative 'vdm_msg'
module NMEAPlus
module Message
module AIS
module VDMPayload
# Basic decoding of "blue force" encrypted binary messages.
# Note that this module is incapable of decrypting the messages. It can only deocde and return
# the encrypted payload to be decrypted elsewhere.
class VDMMsg8USCGEncrypted < NMEAPlus::Message::AIS::VDMPayload::VDMMsg
payload_reader :encrypted_data_2b, 56, 952, :_d
payload_reader :encrypted_data_6b, 56, 952, :_6b_string
payload_reader :encrypted_data_8b, 56, 952, :_8b_data_string
end
# Type 8: Binary Broadcast Message Subtype: US Coast Guard (USCG) blue force encrypted position report
class VDMMsg8d366f56 < VDMMsg8USCGEncrypted; end
# Type 8: Binary Broadcast Message Subtype: US Coast Guard (USCG) blue force encrypted data
class VDMMsg8d366f57 < VDMMsg8USCGEncrypted; end
end
end
end
end
|
Add tests for Fintop::Metrics JSON string parsing functions. | require 'test_helper'
require 'fintop/metrics'
class MetricsTest < Test::Unit::TestCase
def test_process_ostrich_json
json_str = %q{{"counters":{"srv\/http\/received_bytes":37,"srv\/http\/requests":4},"gauges":{"jvm_uptime":219,"srv\/http\/connections":1}}}
expected = {'srv'=>{'http/received_bytes'=>37,'http/requests'=>4,'http/connections'=>1},'jvm'=>{'uptime'=>219}}
output = Fintop::Metrics.process_ostrich_json(json_str)
assert_equal(output, expected)
end
end
| require 'test_helper'
require 'fintop/metrics'
class MetricsTest < Test::Unit::TestCase
def test_process_ostrich_json_parses_valid_json_string
json_str = %q{{"counters":{"srv\/http\/received_bytes":37},"gauges":{"jvm_uptime":219,"srv\/http\/connections":1}}}
expected = {
'srv'=>{'http/received_bytes'=>37,'http/connections'=>1},
'jvm'=>{'uptime'=>219}
}
output = Fintop::Metrics.process_ostrich_json(json_str)
assert_equal(output, expected)
end
def test_process_ostrich_json_throws_on_empty_string
assert_raise JSON::ParserError do
Fintop::Metrics.process_ostrich_json("")
end
end
def test_process_ostrich_json_throws_on_invalid_json_string
assert_raise JSON::ParserError do
Fintop::Metrics.process_ostrich_json("{j")
end
end
def test_process_metrics_tm_json_parses_valid_json_string
json_str = %q{{"jvm\/uptime":183.0,"srv\/http\/connections":1.0,"srv\/http\/received_bytes":96}}
expected = {
'srv'=>{'http/received_bytes'=>96,'http/connections'=>1.0},
'jvm'=>{'uptime'=>183.0}
}
output = Fintop::Metrics.process_metrics_tm_json(json_str)
assert_equal(output, expected)
end
def test_process_metrics_tm_json_throws_on_empty_string
assert_raise JSON::ParserError do
Fintop::Metrics.process_metrics_tm_json("")
end
end
def test_process_metrics_tm_json_throws_on_invalid_json_string
assert_raise JSON::ParserError do
Fintop::Metrics.process_metrics_tm_json("{j")
end
end
end
|
Add gem data and HTTParty dependency | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ipaddresslabs/version'
Gem::Specification.new do |spec|
spec.name = "ipaddresslabs"
spec.version = Ipaddresslabs::VERSION
spec.authors = ["TODO: Write your name"]
spec.email = ["nicolas@engage.is"]
spec.summary = %q{TODO: Write a short summary. Required.}
spec.description = %q{TODO: Write a longer description. Optional.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rake"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ipaddresslabs/version'
Gem::Specification.new do |spec|
spec.name = "ipaddresslabs"
spec.version = Ipaddresslabs::VERSION
spec.authors = ["Nícolas Iensen"]
spec.email = ["nicolas@iensen.me"]
spec.summary = %q{Gem wrapper for the ipaddresslabs.com API}
spec.homepage = "https://github.com/nicolasiensen/ipaddresslabs"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rake"
spec.add_runtime_dependency 'httparty'
end
|
Switch to options hash for 1.9 compat | module SwaggerYard
class Type
def self.from_type_list(types)
new(types.first)
end
# Default model location path
MODEL_PATH = '#/definitions/'.freeze
attr_reader :source
def initialize(string)
@source = string
@name = nil
end
def name
return @name if @name
@name = name_for(schema)
@name = name_for(schema['items']) if @name == 'array'
@name
end
def ref?
schema["$ref"]
end
def schema
@schema ||= TypeParser.new.json_schema(source)
end
def schema_with(model_path: MODEL_PATH)
if model_path != MODEL_PATH
TypeParser.new(model_path).json_schema(source)
else
schema
end
end
private
def name_for(schema)
schema["type"] || schema["$ref"][%r'.*/([^/]*)$', 1]
end
end
end
| module SwaggerYard
class Type
def self.from_type_list(types)
new(types.first)
end
# Default model location path
MODEL_PATH = '#/definitions/'.freeze
attr_reader :source
def initialize(string)
@source = string
@name = nil
end
def name
return @name if @name
@name = name_for(schema)
@name = name_for(schema['items']) if @name == 'array'
@name
end
def ref?
schema["$ref"]
end
def schema
@schema ||= TypeParser.new.json_schema(source)
end
def schema_with(options = {})
model_path = options && options[:model_path] || MODEL_PATH
if model_path != MODEL_PATH
TypeParser.new(model_path).json_schema(source)
else
schema
end
end
private
def name_for(schema)
schema["type"] || schema["$ref"][%r'.*/([^/]*)$', 1]
end
end
end
|
Update feature generator to use the Capybara spec DSL | require "minitest_helper"
# To be handled correctly by Capybara this spec must end with "Feature Test"
describe "<%= class_name %> Feature Test" do
it "sanity" do
visit root_path
page.must_have_content "Hello World"
page.wont_have_content "Goobye All!"
end
end
| require "minitest_helper"
# To be handled correctly by Capybara this spec must end with "Feature Test"
feature "<%= class_name %> Feature Test" do
scenario "the test is sound" do
visit root_path
page.must_have_content "Hello World"
page.wont_have_content "Goobye All!"
end
end
|
Add attribute tests for user model. | require 'rails_helper'
RSpec.describe User, type: :model do
pending "add some examples to (or delete) #{__FILE__}"
end
| require 'rails_helper'
RSpec.describe User, type: :model do
let(:user){User.new(username: 'derrick', email: 'derrick@derrick.com', password: 'aaa', verified: true )}
describe "it has attributes" do
it "has a username" do
expect( user.username ).to_not eq nil
expect( user.username ).to eq 'derrick'
end
it "has an email" do
expect( user.email ).to_not eq nil
expect( user.email ).to eq 'derrick@derrick.com'
end
it "has a password_digest" do
expect( user.password_digest ).to_not eq nil
expect( user.password_digest ).to eq 'aaa'
end
end
end
|
Switch to warn validation class. | module Executors
module Configurators
module Yaml
class Validator < Kwalify::Validator
EXECUTOR_RULE_NAME = "executor"
@@schema = Kwalify::Yaml.load_file(File.join(File.dirname(__FILE__), "schema.yml"))
def initialize
super(@@schema)
end
def validate_hook value, rule, path, errors
case rule.name
when EXECUTOR_RULE_NAME
unless Configurator::SIZE_REQUIRING_TYPES.include? value[Configurator::TYPE_KEY].downcase
if value[Configurator::SIZE_KEY]
errors << Kwalify::ValidationError.new("\"size\" is not required.", path)
end
end
end
end
end
end
end
end | require "executors/configurators/yaml/validation_warn"
# YAML validator.
module Executors
module Configurators
module Yaml
class Validator < Kwalify::Validator
EXECUTOR_RULE_NAME = "executor"
@@schema = Kwalify::Yaml.load_file(File.join(File.dirname(__FILE__), "schema.yml"))
def initialize
super(@@schema)
end
def validate_hook value, rule, path, errors
case rule.name
when EXECUTOR_RULE_NAME
unless Configurator::SIZE_REQUIRING_TYPES.include? value[Configurator::TYPE_KEY].downcase
if value[Configurator::SIZE_KEY]
errors << ValidationWarn.new("\"size\" is not required.", path, rule, value)
end
end
end
end
end
end
end
end |
Test that currency symbol position can be changed | # frozen_string_literal: true
require 'spec_helper'
describe "General Settings" do
include AuthenticationHelper
before do
login_as_admin_and_visit spree.admin_dashboard_path
click_link "Configuration"
click_link "General Settings"
end
context "visiting general settings (admin)" do
it "should have the right content" do
expect(page).to have_content("General Settings")
expect(find("#site_name").value).to eq("OFN Demo Site")
expect(find("#site_url").value).to eq("demo.openfoodnetwork.org")
end
end
context "editing general settings (admin)" do
it "should be able to update the site name" do
fill_in "site_name", with: "OFN Demo Site99"
click_button "Update"
within("[class='flash success']") do
expect(page).to have_content(Spree.t(:successfully_updated, resource: Spree.t(:general_settings)))
end
expect(find("#site_name").value).to eq("OFN Demo Site99")
end
end
end
| # frozen_string_literal: true
require 'spec_helper'
describe "General Settings" do
include AuthenticationHelper
before do
login_as_admin_and_visit spree.admin_dashboard_path
click_link "Configuration"
click_link "General Settings"
end
context "visiting general settings (admin)" do
it "should have the right content" do
expect(page).to have_content("General Settings")
expect(find("#site_name").value).to eq("OFN Demo Site")
expect(find("#site_url").value).to eq("demo.openfoodnetwork.org")
end
end
context "editing general settings (admin)" do
it "should be able to update the site name" do
fill_in "site_name", with: "OFN Demo Site99"
click_button "Update"
within("[class='flash success']") do
expect(page).to have_content(Spree.t(:successfully_updated, resource: Spree.t(:general_settings)))
end
expect(find("#site_name").value).to eq("OFN Demo Site99")
end
end
context 'editing currency symbol position' do
it 'updates its position' do
expect(page).to have_content('Currency Settings')
within('.currency') do
find("[for='currency_symbol_position_after']").click
end
click_button 'Update'
expect(page).to have_content(Spree.t(:successfully_updated, resource: Spree.t(:general_settings)))
expect(page).to have_checked_field('10.00 $')
end
end
end
|
Remove handler for unused options and unused file loading in directory | require "fog/core/collection"
require "fog/google/models/storage_json/directory"
module Fog
module Storage
class GoogleJSON
class Directories < Fog::Collection
model Fog::Storage::GoogleJSON::Directory
def all
data = service.get_service.body["items"]
load(data)
end
def get(key, options = {})
remap_attributes(options, :delimiter => "delimiter",
:marker => "marker",
:max_keys => "max-keys",
:prefix => "prefix")
data = service.get_bucket(key, options).body
directory = new(:key => data["name"])
# options = {}
# for k, v in data
# if %w(commonPrefixes delimiter IsTruncated Marker MaxKeys Prefix).include?(k)
# options[k] = v
# end
# end
# directory.files.merge_attributes(options)
# directory.files.load(data["contents"])
directory
rescue Excon::Errors::NotFound
nil
end
end
end
end
end
| require "fog/core/collection"
require "fog/google/models/storage_json/directory"
module Fog
module Storage
class GoogleJSON
class Directories < Fog::Collection
model Fog::Storage::GoogleJSON::Directory
def all
data = service.get_service.body["items"]
load(data)
end
def get(key, options = {})
remap_attributes(options, :delimiter => "delimiter",
:marker => "marker",
:max_keys => "max-keys",
:prefix => "prefix")
data = service.get_bucket(key, options).body
new(:key => data["name"])
rescue Excon::Errors::NotFound
nil
end
end
end
end
end
|
Revert "Enable request queuing tracking in Datadog" | if ENV['DATADOG_RAILS_APM']
Datadog.configure do |c|
c.use :rails, service_name: 'rails'
c.use :delayed_job, service_name: 'delayed_job'
c.use :dalli, service_name: 'memcached'
c.analytics_enabled = true
c.runtime_metrics_enabled = true
c.request_queuing = true
end
end
| if ENV['DATADOG_RAILS_APM']
Datadog.configure do |c|
c.use :rails, service_name: 'rails'
c.use :delayed_job, service_name: 'delayed_job'
c.use :dalli, service_name: 'memcached'
c.analytics_enabled = true
c.runtime_metrics_enabled = true
end
end
|
Add spec for generate_upload_url override. | require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe AdminRequestController do
describe 'POST generate_upload_url' do
it 'creates a user for the authority with a dummy date of birth' do
user = FactoryGirl.create(:user, :dob => '2/2/2000')
info_request = FactoryGirl.create(:info_request, :user => user)
post :generate_upload_url, :id => info_request.id
user = User.where(:email => info_request.public_body.request_email).first
expect(user.dob).to eq(Date.new(1900, 1, 1 ))
end
end
end | |
Revert "Added debugging calls to the events controller" | class EventsController < ApplicationController
before_action :access_required
before_action :limit_count, only: [:more]
before_action :track_request, only: [:more], unless: :is_admin?
before_action :find_user, only: [:index, :more]
respond_to :html, :json, :js
def index
ap @user.subscribed_channels
ap @user.subscribed_channels.to_json
@subscribed_channels = @user.subscribed_channels.to_json
ap @user.activity_stats
ap @user.activity_stats.to_json
@stats = @user.activity_stats.to_json
end
def more
from = params[:since].try(:to_f) || 0
to = Time.now.to_f
Event.user_activity(@user, from, to, @count, true)
respond_with @user.activity_stats
end
private
def track_request
end
def limit_count
@count = params[:count].nil? ? 5 : [params[:count].to_i, 10].min
end
def verify_ownership
redirect_to(root_url) unless (params[:username] == current_user.username)
end
def find_user
@user = current_user
end
def find_featured_protips
if Rails.env.development? && ENV['FEATURED_PROTIPS'].blank?
ENV['FEATURED_PROTIPS'] = Protip.limit(3).collect(&:public_id).join(',')
end
return [] if ENV['FEATURED_PROTIPS'].blank?
Protip.where(public_id: ENV['FEATURED_PROTIPS'].split(','))
end
end
| class EventsController < ApplicationController
before_action :access_required
before_action :limit_count, only: [:more]
before_action :track_request, only: [:more], unless: :is_admin?
before_action :find_user, only: [:index, :more]
respond_to :html, :json, :js
def index
@subscribed_channels = @user.subscribed_channels.to_json
@stats = @user.activity_stats.to_json
end
def more
from = params[:since].try(:to_f) || 0
to = Time.now.to_f
Event.user_activity(@user, from, to, @count, true)
respond_with @user.activity_stats
end
private
def track_request
end
def limit_count
@count = params[:count].nil? ? 5 : [params[:count].to_i, 10].min
end
def verify_ownership
redirect_to(root_url) unless (params[:username] == current_user.username)
end
def find_user
@user = current_user
end
def find_featured_protips
if Rails.env.development? && ENV['FEATURED_PROTIPS'].blank?
ENV['FEATURED_PROTIPS'] = Protip.limit(3).collect(&:public_id).join(',')
end
return [] if ENV['FEATURED_PROTIPS'].blank?
Protip.where(public_id: ENV['FEATURED_PROTIPS'].split(','))
end
end
|
Fix the rakefile for RSpec 2. | begin
require 'spec'
rescue LoadError
begin
require 'rubygems'
require 'spec'
rescue LoadError
puts <<-EOS
To use rspec for testing you must install rspec gem:
gem install rspec
EOS
exit(0)
end
end
require 'spec/rake/spectask'
namespace :watirspec do
desc "Run the specs under #{File.dirname(__FILE__)}"
Spec::Rake::SpecTask.new(:run) do |t|
t.spec_files = FileList["#{File.dirname(__FILE__)}/*_spec.rb"]
end
end
namespace :watirspec do
def spec_watir; File.dirname(__FILE__); end
#
# stolen from rubinius
#
desc 'Switch to the committer url for watirspec'
task :committer do
Dir.chdir spec_watir do
sh "git config remote.origin.url git@github.com:jarib/watirspec.git"
end
puts "\nYou're now accessing watirspec via the committer URL."
end
desc "Switch to the watirspec anonymous URL"
task :anon do
Dir.chdir spec_watir do
sh "git config remote.origin.url git://github.com/jarib/watirspec.git"
end
puts "\nYou're now accessing watirspec via the anonymous URL."
end
end
| begin
require 'rspec'
rescue LoadError
begin
require 'rubygems'
require 'rspec'
rescue LoadError
puts <<-EOS
To use rspec for testing you must install rspec gem:
gem install rspec
EOS
exit(0)
end
end
require 'rspec/core/rake_task'
namespace :watirspec do
desc "Run the specs under #{File.dirname(__FILE__)}"
RSpec::Core::RakeTask.new(:run) do |t|
t.pattern = "#{File.dirname(__FILE__)}/*_spec.rb"
end
end
namespace :watirspec do
def spec_watir; File.dirname(__FILE__); end
#
# stolen from rubinius
#
desc 'Switch to the committer url for watirspec'
task :committer do
Dir.chdir spec_watir do
sh "git config remote.origin.url git@github.com:jarib/watirspec.git"
end
puts "\nYou're now accessing watirspec via the committer URL."
end
desc "Switch to the watirspec anonymous URL"
task :anon do
Dir.chdir spec_watir do
sh "git config remote.origin.url git://github.com/jarib/watirspec.git"
end
puts "\nYou're now accessing watirspec via the anonymous URL."
end
end
|
Update gps file with pseudocode | # Method to create a list
# create an empty hash
# input: string of items separated by spaces (example: "carrots apples cereal pizza")
# steps:
# separate the string into individual items
# add each item to the hash, set default quantity
# print the list to the console using a loop
# output: (hash), could also be a string with hash data inside
# Method to add an item to a list
# input: item name and optional quantity
# steps: add the item name and quantity as a new pair into existing hash
# output: return hash
# Method to remove an item from the list
# input: using a pre-existing hash method, give it the input of the key of the pair I want to delete
# steps: the method deletes it
# output: the updated hash
# Method to update the quantity of an item
# input: hash of specific item now equals new quantity
# steps: the method updates the quantity
# output: returns the updated hash
# Method to print a list and make it look pretty
# input: using a loop to iterate through each pair in the hash
# steps: tell it what to do with each pair (i.e. print it inside of this fancy string)
# output: each string with interpolated data, return nil?
| |
Clean the checked out directory before re-applying stashed changes. | module Heroku::Deploy::Task
class StashGitChanges < Base
include Heroku::Deploy::Shell
def before_deploy
output = git "status --untracked-files --short"
unless output.empty?
@stash_name = "heroku-deploy-#{Time.now.to_i}"
task "Stashing your current changes" do
git "stash save -u #{@stash_name}"
end
end
end
def rollback_before_deploy
after_deploy
end
def after_deploy
return unless @stash_name
task "Applying back your local changes" do
stashes = git 'stash list'
matched_stash = stashes.split("\n").find { |x| x.match @stash_name }
label = matched_stash.match(/^([^:]+)/)
git "stash apply #{label}"
git "stash drop #{label}"
end
end
end
end
| module Heroku::Deploy::Task
class StashGitChanges < Base
include Heroku::Deploy::Shell
def before_deploy
output = git "status --untracked-files --short"
unless output.empty?
@stash_name = "heroku-deploy-#{Time.now.to_i}"
task "Stashing your current changes" do
git "stash save -u #{@stash_name}"
end
end
end
def rollback_before_deploy
after_deploy
end
def after_deploy
return unless @stash_name
task "Applying back your local changes" do
stashes = git 'stash list'
matched_stash = stashes.split("\n").find { |x| x.match @stash_name }
label = matched_stash.match(/^([^:]+)/)
# Make sure there are no weird local changes (think db/schema.db changing
# because we ran migrations locally, and column order changing because postgres
# is crazy like that)
git "clean -fd"
git "stash apply #{label}"
git "stash drop #{label}"
end
end
end
end
|
Add some pseudo-live artifact output | class BuildPartJob < JobBase
attr_reader :build_part_result, :build_part, :build
def initialize(build_part_result_id)
@build_part_result = BuildPartResult.find(build_part_result_id)
@build_part = BuildPart.find(@build_part_result.build_part_id)
@build = @build_part.build
end
def perform
build_part_result.start!
build_part_result.update_attributes(:builder => hostname)
GitRepo.inside_copy('web-cache', build.sha, true) do
# TODO:
# collect stdout, stderr, and any logs
result = tests_green? ? :passed : :failed
build_part_result.finish!(result)
collect_artifacts(BUILD_ARTIFACTS)
end
end
def tests_green?
ENV["TEST_RUNNER"] = build_part.kind
ENV["RUN_LIST"] = build_part.paths.join(",")
system(BUILD_COMMAND.call build_part)
end
def collect_artifacts(artifacts_glob)
Dir[*artifacts_glob].each do |path|
if File.file? path
build_part_result.build_artifacts.create!(:content => File.read(path), :name => path)
end
end
end
private
def hostname
`hostname`
end
end
| require 'webrick'
class BuildPartJob < JobBase
attr_reader :build_part_result, :build_part, :build
def initialize(build_part_result_id)
@build_part_result = BuildPartResult.find(build_part_result_id)
@build_part = BuildPart.find(@build_part_result.build_part_id)
@build = @build_part.build
end
def perform
build_part_result.start!
build_part_result.update_attributes(:builder => hostname)
GitRepo.inside_copy('web-cache', build.sha, true) do
start_live_artifact_server
result = tests_green? ? :passed : :failed
build_part_result.finish!(result)
collect_artifacts(BUILD_ARTIFACTS)
end
ensure
kill_live_artifact_server
end
def tests_green?
ENV["TEST_RUNNER"] = build_part.kind
ENV["RUN_LIST"] = build_part.paths.join(",")
system(BUILD_COMMAND.call build_part)
end
def collect_artifacts(artifacts_glob)
Dir[*artifacts_glob].each do |path|
if File.file? path
build_part_result.build_artifacts.create!(:content => File.read(path), :name => path)
end
end
end
private
def hostname
`hostname`
end
def start_live_artifact_server
pid = fork
if pid.nil?
begin
server = WEBrick::HTTPServer.new(
:Port => 55555,
:DocumentRoot => "log",
:FancyIndexing => true)
server.start
rescue Interrupt
server.stop
end
else
@artifact_server_pid = pid
end
end
def kill_live_artifact_server
Process.kill("KILL", @artifact_server_pid)
end
end
|
Fix the capitalization of Yeppp./configure --with-pgconfig=/usr/local/pgsql/bin/pg_config && make && sudo make install | require 'mkmf'
home_dir = `echo $HOME`.strip
dirs = [
File.join(home_dir, 'yeppp-1.0.0/library/headers'),
File.join(home_dir, 'yeppp-1.0.0/binaries/linux/x86_64')
]
dirs.each{|d| puts d}
extension_name = 'ryeppp'
dir_config(extension_name)
dir_config('yeppp-1.0.0',
# Include paths.
dirs,
# Library paths.
dirs
)
if have_library('yeppp')
create_makefile(extension_name)
else
puts 'No yeppp! support available.'
end
| require 'mkmf'
home_dir = `echo $HOME`.strip
dirs = [
File.join(home_dir, 'yeppp-1.0.0/library/headers'),
File.join(home_dir, 'yeppp-1.0.0/binaries/linux/x86_64')
]
dirs.each{|d| puts d}
extension_name = 'ryeppp'
dir_config(extension_name)
dir_config('yeppp-1.0.0',
# Include paths.
dirs,
# Library paths.
dirs
)
if have_library('yeppp')
create_makefile(extension_name)
else
puts 'No Yeppp! support available.'
end
|
Add version to sqlite3 dependency | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "emcee/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "emcee"
s.version = Emcee::VERSION
s.authors = ["Andrew Huth"]
s.email = ["andrew@huth.me"]
s.homepage = "https://github.com/ahuth/emcee"
s.summary = "Add web components to the Rails asset pipeline."
s.description = "Add web components to the Rails asset pipeline"
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["test/**/*"]
s.add_dependency "nokogiri", "~> 1.0"
s.add_dependency "rails", "~> 4.0"
s.add_development_dependency "coffee-rails", "~> 4.0"
s.add_development_dependency "sass", "~> 3.0"
s.add_development_dependency "sqlite3"
end
| $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "emcee/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "emcee"
s.version = Emcee::VERSION
s.authors = ["Andrew Huth"]
s.email = ["andrew@huth.me"]
s.homepage = "https://github.com/ahuth/emcee"
s.summary = "Add web components to the Rails asset pipeline."
s.description = "Add web components to the Rails asset pipeline"
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["test/**/*"]
s.add_dependency "nokogiri", "~> 1.0"
s.add_dependency "rails", "~> 4.0"
s.add_development_dependency "coffee-rails", "~> 4.0"
s.add_development_dependency "sass", "~> 3.0"
s.add_development_dependency "sqlite3", ">= 1.3.9"
end
|
Add workaround to save failed LogEntries | # workaround for issue https://github.com/spree/spree/issues/1767
# based on http://stackoverflow.com/questions/10427365/need-to-write-to-db-from-validation
Spree::LogEntry.class_eval do
after_rollback :save_anyway
def save_anyway
log = Spree::LogEntry.new
log.source = source
log.details = details
log.save!
end
end
| |
Upgrade development dependency rake to 12.3.3 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'hotch/version'
Gem::Specification.new do |spec|
spec.name = "hotch"
spec.version = Hotch::VERSION
spec.authors = ["Peter Leitzen"]
spec.email = ["peter@leitzen.de"]
spec.summary = %q{Profile helper}
spec.description = %q{Callstack and memory profiler}
spec.homepage = "https://github.com/splattael/hotch"
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_runtime_dependency "stackprof", "~> 0.2.15"
spec.add_runtime_dependency "allocation_tracer", "~> 0.6.3"
spec.add_development_dependency "bundler"
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 'hotch/version'
Gem::Specification.new do |spec|
spec.name = "hotch"
spec.version = Hotch::VERSION
spec.authors = ["Peter Leitzen"]
spec.email = ["peter@leitzen.de"]
spec.summary = %q{Profile helper}
spec.description = %q{Callstack and memory profiler}
spec.homepage = "https://github.com/splattael/hotch"
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_runtime_dependency "stackprof", "~> 0.2.15"
spec.add_runtime_dependency "allocation_tracer", "~> 0.6.3"
spec.add_development_dependency "bundler"
spec.add_development_dependency "rake", ">= 12.3.3"
end
|
Fix notification url not generated properly | json.partial! 'api/v1/shared/page_meta', collection: @notifications
json._links do
json.self url_for(notification_params.merge(only_path: true))
json.next url_for(notification_params.merge(page: @notifications.next_page, only_path: true)) unless @notifications.next_page.nil?
json.mark_read mark_read_api_v1_notification_path(':id')
end
json.notifications @notifications do |notification|
json.extract! notification, :id, :message, :read, :created_at
if notification.to_actual_model.nil?
json.url notifications_path
else
json.url url_for(notification.to_actual_model, only_path: true)
end
end
| json.partial! 'api/v1/shared/page_meta', collection: @notifications
json._links do
json.self url_for(notification_params.merge(only_path: true))
json.next url_for(notification_params.merge(page: @notifications.next_page, only_path: true)) unless @notifications.next_page.nil?
json.mark_read mark_read_api_v1_notification_path(':id')
end
json.notifications @notifications do |notification|
json.extract! notification, :id, :message, :read, :created_at
if notification.to_actual_model.nil?
json.url notifications_path
else
json.url url_for([notification.to_actual_model, only_path: true])
end
end
|
Add test coverage of monkey patches | require 'spec_helper'
describe Array do
pending "write it"
end
describe Float do
pending "write it"
end
| require 'spec_helper'
describe Array do
describe "to hash" do
it "should map to correct keys and values" do
[["foo", "bar"], ["something", "nothing"]].to_hash.should == { :foo => "bar", :something => "nothing" }
end
it "should make keys lower case" do
[["FOO", "bar"]].to_hash.should == { :foo => "bar" }
end
it "should replace spaces in keys with underscores" do
[["FOO FOO", "bar"]].to_hash.should == { :foo_foo => "bar" }
end
end
end
describe Float do
describe "should round to" do
it "a float" do
Math::PI.round_to.should be_instance_of(Float)
end
it "zero decimal places by default" do
Math::PI.round_to.should == 3.0
end
it "a specified number of decimal places" do
Math::PI.round_to(2).should == 3.14
end
end
end
|
Return bare js if no source map is created. | require 'json'
require 'uglifier'
module Sprockets
# Public: Uglifier/Uglify compressor.
#
# To accept the default options
#
# environment.register_bundle_processor 'application/javascript',
# Sprockets::UglifierCompressor
#
# Or to pass options to the Uglifier class.
#
# environment.register_bundle_processor 'application/javascript',
# Sprockets::UglifierCompressor.new(comments: :copyright)
#
class UglifierCompressor
VERSION = '2'
def self.call(*args)
new.call(*args)
end
def initialize(options = {})
# Feature detect Uglifier 2.0 option support
if Uglifier::DEFAULTS[:copyright]
# Uglifier < 2.x
options[:copyright] ||= false
else
# Uglifier >= 2.x
options[:copyright] ||= :none
end
@uglifier = ::Uglifier.new(options)
@cache_key = [
'UglifierCompressor',
::Uglifier::VERSION,
VERSION,
JSON.generate(options)
]
end
def call(input)
data = input[:data]
js, map = input[:cache].fetch(@cache_key + [data]) do
@uglifier.compile_with_map(data)
end
minified = SourceMap::Map.from_json(map)
original = input[:metadata][:map]
combined = original | minified
{ data: js,
map: combined }
end
end
end
| require 'json'
require 'uglifier'
module Sprockets
# Public: Uglifier/Uglify compressor.
#
# To accept the default options
#
# environment.register_bundle_processor 'application/javascript',
# Sprockets::UglifierCompressor
#
# Or to pass options to the Uglifier class.
#
# environment.register_bundle_processor 'application/javascript',
# Sprockets::UglifierCompressor.new(comments: :copyright)
#
class UglifierCompressor
VERSION = '2'
def self.call(*args)
new.call(*args)
end
def initialize(options = {})
# Feature detect Uglifier 2.0 option support
if Uglifier::DEFAULTS[:copyright]
# Uglifier < 2.x
options[:copyright] ||= false
else
# Uglifier >= 2.x
options[:copyright] ||= :none
end
@uglifier = ::Uglifier.new(options)
@cache_key = [
'UglifierCompressor',
::Uglifier::VERSION,
VERSION,
JSON.generate(options)
]
end
def call(input)
data = input[:data]
js, map = input[:cache].fetch(@cache_key + [data]) do
@uglifier.compile_with_map(data)
end
if input[:metadata][:map]
minified = SourceMap::Map.from_json(map)
original = input[:metadata][:map]
combined = original | minified
{ data: js,
map: combined }
else
js
end
end
end
end
|
Allow decorators in the parent app. | module RubyWedding
class Engine < ::Rails::Engine
isolate_namespace RubyWedding
config.generators do |g|
g.test_framework :rspec, fixture: false
g.fixture_replacement :factory_girl, dir: 'spec/factories'
g.assets false
g.helper false
end
end
end
| module RubyWedding
class Engine < ::Rails::Engine
isolate_namespace RubyWedding
config.generators do |g|
g.test_framework :rspec, fixture: false
g.fixture_replacement :factory_girl, dir: 'spec/factories'
g.assets false
g.helper false
end
config.to_prepare do
Dir.glob(Rails.root + "app/decorators/**/**/*_decorator*.rb").each do |c|
require_dependency(c)
end
end
end
end
|
Remove rescuing JSON parsing error in JSON formatter | module Dox
module Formatters
class Json < Dox::Formatters::Base
def format
JSON.pretty_generate(JSON.parse(body || ''))
rescue JSON::ParserError
''
end
end
end
end
| module Dox
module Formatters
class Json < Dox::Formatters::Base
def format
# in cases where the body isn't valid JSON
# and the headers specify the Content-Type is application/json
# an error should be raised
return '' if body.nil? || body.length < 2
JSON.pretty_generate(JSON.parse(body))
end
end
end
end
|
Fix a typo. Add minor config options. |
require 'curtis/version'
require 'ncurses'
require 'curtis/base_view'
require 'curtis/view'
module Curtis
class << self
def config
@config ||= Configuration.new
yield @config if block_given?
@config
end
alias_method :configure, :config
def show(**options)
screen = Ncurses.initscr
Ncurses.cbreak
Ncurses.noecho
Ncurses.curs_set(0) if config.hide_cursor
screen.refresh
yield BaseView.new(screen)
ensure
Ncurses.endwin
end
end
class Configuration
attr_accessor :hide_cursor
def initializes
@hide_cursor = false
end
end
end
| require 'curtis/version'
require 'ncurses'
require 'curtis/base_view'
require 'curtis/view'
module Curtis
class << self
def config
@config ||= Configuration.new
yield @config if block_given?
@config
end
alias_method :configure, :config
def show(**options)
screen = Ncurses.initscr
Ncurses.cbreak if config.cbreak
Ncurses.noecho if config.noecho
Ncurses.curs_set(0) if config.hide_cursor
screen.refresh
yield BaseView.new(screen)
ensure
Ncurses.endwin
end
end
class Configuration
attr_accessor :cbreak
attr_accessor :noecho
attr_accessor :hide_cursor
def initialize
@cbreak = true
@noecho = true
@hide_cursor = false
end
end
end
|
Revert "add more codes to reproduce segfault more." | module Crispy
module CrispyInternal
class ClassSpy < ::Module
include SpyMixin
include WithStubber
@registry = {}
def initialize klass, stubs_map = {}
super()
@received_messages = []
initialize_stubber stubs_map
prepend_stubber klass
sneak_into Target.new(klass)
end
def define_wrapper method_name
#return method_name if method_name == :initialize
return method_name if method_name == :method_missing
p method_name
define_method method_name do|*arguments, &attached_block|
#::Kernel.print "e" # <= with this statement, prepend-ing :method_missing doesn't cause the segfault.
::Crispy::CrispyInternal::ClassSpy.of_class(::Kernel.p self.class).received_messages <<
::Crispy::CrispyReceivedMessageWithReceiver.new(self, method_name, *arguments, &attached_block)
super(*arguments, &attached_block)
end
method_name
end
private :define_wrapper
class Target
def initialize klass
@target_class = klass
end
def as_class
@target_class
end
# define accessor after prepending to avoid to spy unexpectedly.
def pass_spy_through spy
::Crispy::CrispyInternal::ClassSpy.register spy: spy, of_class: @target_class
end
end
def self.register(spy: nil, of_class: nil)
@registry[of_class] = spy
end
def self.of_class(klass)
@registry[klass]
end
end
end
end
| module Crispy
module CrispyInternal
class ClassSpy < ::Module
include SpyMixin
include WithStubber
@registry = {}
def initialize klass, stubs_map = {}
super()
@received_messages = []
initialize_stubber stubs_map
prepend_stubber klass
sneak_into Target.new(klass)
end
def define_wrapper method_name
define_method method_name do|*arguments, &attached_block|
::Crispy::CrispyInternal::ClassSpy.of_class(self.class).received_messages <<
::Crispy::CrispyReceivedMessageWithReceiver.new(self, method_name, *arguments, &attached_block)
super(*arguments, &attached_block)
end
method_name
end
private :define_wrapper
class Target
def initialize klass
@target_class = klass
end
def as_class
@target_class
end
# define accessor after prepending to avoid to spy unexpectedly.
def pass_spy_through spy
::Crispy::CrispyInternal::ClassSpy.register spy: spy, of_class: @target_class
end
end
def self.register(spy: nil, of_class: nil)
@registry[of_class] = spy
end
def self.of_class(klass)
@registry[klass]
end
end
end
end
|
Remove deprecation from Country call | require 'countries/version'
require 'iso3166'
require 'countries/mongoid' if defined?(Mongoid)
class Country < ISO3166::Country
def to_s
warn "[DEPRECATION] `Country` is deprecated. Please use `ISO3166::Country` instead."
name
end
end
| require 'countries/version'
require 'iso3166'
require 'countries/mongoid' if defined?(Mongoid)
class Country < ISO3166::Country
def to_s
name
end
end
|
Update Bitwig Studio cask to 1.3.5 | cask 'bitwig-studio' do
version '1.3.3'
sha256 '6d614095b1b39e387ed4c96a70342c5d982a6d4a5c71e6a4498f25b7898b909b'
url "https://downloads.bitwig.com/Bitwig%20Studio%20#{version}.dmg"
name 'Bitwig Studio'
homepage 'https://www.bitwig.com'
license :commercial
app 'Bitwig Studio.app'
end
| cask 'bitwig-studio' do
version '1.3.5'
sha256 'f15404e9a2a84fbd0165243af49629da1846252ed5915db4853f212a43daecf1'
url "https://downloads.bitwig.com/stable/#{version}/Bitwig%20Studio%20#{version}.dmg"
name 'Bitwig Studio'
homepage 'https://www.bitwig.com'
license :commercial
auto_updates true
app 'Bitwig Studio.app'
end
|
Add 'rutty scp' tests file | require 'helper'
class TestActionSCP < Test::Unit::TestCase
context "The 'rutty scp' action" do
setup { ensure_fresh_config! }
teardown { clean_test_config! }
end
end
| |
Add required packages to build nokogiri. | include_recipe 'cron'
# install gem backup with options --no-ri --no-rdoc before include_recipe 'backup'
gem_package 'backup' do
version node['backup']['version'] if node['backup']['version']
action :upgrade if node['backup']['upgrade?']
options '--no-ri --no-rdoc'
end
include_recipe 'backup'
include_recipe 'percona::backup'
link '/usr/local/bin/backup' do
to '/root/.chefdk/gem/ruby/2.1.0/bin/backup'
only_if { File.exist?('/root/.chefdk/gem/ruby/2.1.0/bin/backup') }
end
# for s3
include_recipe 'yum-epel'
include_recipe 's3cmd-master'
package 'python-dateutil'
| include_recipe 'cron'
package ['zlib-devel', 'xz-devel'] do
action :install
end
# install gem backup with options --no-ri --no-rdoc before include_recipe 'backup'
gem_package 'backup' do
version node['backup']['version'] if node['backup']['version']
action :upgrade if node['backup']['upgrade?']
options '--no-ri --no-rdoc'
end
include_recipe 'backup'
include_recipe 'percona::backup'
link '/usr/local/bin/backup' do
to '/root/.chefdk/gem/ruby/2.1.0/bin/backup'
only_if { File.exist?('/root/.chefdk/gem/ruby/2.1.0/bin/backup') }
end
# for s3
include_recipe 'yum-epel'
include_recipe 's3cmd-master'
package 'python-dateutil'
|
Simplify link :app, to link | class Gitbox < Cask
url 'http://d1oa71y4zxyi0a.cloudfront.net/gitbox-1.6.2-ml.zip'
homepage 'http://gitboxapp.com/'
version '1.6.2'
sha1 '20fdea01bf3b26f6ba23fa2b909a7d56cddb6250'
link :app, 'Gitbox.app'
end
| class Gitbox < Cask
url 'http://d1oa71y4zxyi0a.cloudfront.net/gitbox-1.6.2-ml.zip'
homepage 'http://gitboxapp.com/'
version '1.6.2'
sha1 '20fdea01bf3b26f6ba23fa2b909a7d56cddb6250'
link 'Gitbox.app'
end
|
Add scope for get variant data | Spree::Variant.class_eval do
scope :complete_order, -> { joins(:orders).where.not(spree_orders: { completed_at: nil }) }
def self.sales_sku
select("spree_variants.id, spree_variants.sku, spree_products.name, spree_variants.variant_name, SUM(spree_line_items.quantity) AS quantity, spree_prices.amount").
joins(:product, :default_price).
complete_order.
group("spree_variants.id, spree_variants.sku, spree_products.name, spree_prices.amount, spree_variants.variant_name")
end
end
| |
Add more development packages for SmartOS | #
# Cookbook Name:: build-essential
# Recipe:: smartos
#
# Copyright 2008-2013, Opscode, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
potentially_at_compile_time do
package 'build-essential'
end
| #
# Cookbook Name:: build-essential
# Recipe:: smartos
#
# Copyright 2008-2013, Opscode, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
potentially_at_compile_time do
package 'autoconf'
package 'binutils'
package 'build-essential'
package 'gcc47'
package 'gmake'
package 'pkg-config'
end
|
Update to remedy after upgrade to 0.36.1 of cocoapods | Pod::Spec.new do |s|
s.name = "TilllessBCScanner"
s.version = "0.0.2"
s.summary = "TBarcodeScannerViewController suitable for working with RubyMotion."
s.description = <<-DESC
Concrete implementation of AVCaptureMetadataOutputObjectsDelegate in
TBarcodeScannerViewController to work with RubyMotion.
DESC
s.homepage = 'https://github.com/tillless/bcscanner'
s.license = 'MIT'
s.author = { "Tillless" => "info@tillless.com" }
s.source = { :git => 'https://github.com/tillless/bcscanner.git', :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/tillless'
s.platform = :ios, '8.1'
s.requires_arc = true
s.source_files = 'Pod/Classes/**/*'
s.resource_bundles = {
'TilllessBCScanner' => ['Pod/Assets/*.png']
}
s.frameworks = 'UIKit', 'QuartzCore'
end
| Pod::Spec.new do |s|
s.name = "TilllessBCScanner"
s.version = "0.0.2"
s.summary = "TBarcodeScannerViewController suitable for working with RubyMotion."
s.description = <<-DESC
Concrete implementation of AVCaptureMetadataOutputObjectsDelegate in
TBarcodeScannerViewController to work with RubyMotion.
DESC
s.homepage = 'https://github.com/tillless/bcscanner'
s.license = 'MIT'
s.author = { "Tillless" => "info@tillless.com" }
s.source = { :git => 'https://github.com/tillless/bcscanner.git', :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/tillless'
s.platform = :ios, '8.1'
s.requires_arc = true
s.source_files = 'Pod/Classes/**/*'
s.public_header_files = 'Pod/Classes/**/*.h'
s.resource_bundles = {
'TilllessBCScanner' => ['Pod/Assets/*.png']
}
s.frameworks = 'UIKit', 'QuartzCore'
end
|
Change json parser to check for 'application/json' not 'json' | require 'faraday'
require 'json'
require 'smartsheet/api/faraday_adapter/faraday_response'
module Smartsheet
module API
module Middleware
# Wraps responses into {FaradayResponse FaradayResponses}, parsing JSON bodies when applicable
class ResponseParser < Faraday::Middleware
def initialize(app)
super(app)
end
def call(env)
@app.call(env).on_complete do |response_env|
if response_env[:response_headers]['content-type'] =~ /\bjson\b/
response_env[:body] = JSON.parse(response_env[:body], symbolize_names: true)
end
response_env[:body] = FaradayResponse.from_response_env response_env
end
end
end
end
end
end | require 'faraday'
require 'json'
require 'smartsheet/api/faraday_adapter/faraday_response'
module Smartsheet
module API
module Middleware
# Wraps responses into {FaradayResponse FaradayResponses}, parsing JSON bodies when applicable
class ResponseParser < Faraday::Middleware
def initialize(app)
super(app)
end
def call(env)
@app.call(env).on_complete do |response_env|
if response_env[:response_headers]['content-type'] =~ /\bapplication\/json\b/
response_env[:body] = JSON.parse(response_env[:body], symbolize_names: true)
end
response_env[:body] = FaradayResponse.from_response_env response_env
end
end
end
end
end
end |
Write summary and description of gemspec | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'peeek/version'
Gem::Specification.new do |spec|
spec.name = 'peeek'
spec.version = Peeek::VERSION
spec.authors = ['Takahiro Kondo']
spec.email = ['heartery@gmail.com']
spec.description = %q{TODO: Write a gem description}
spec.summary = %q{TODO: Write a gem summary}
spec.homepage = ''
spec.license = 'MIT'
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler', '~> 1.3'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec'
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'peeek/version'
Gem::Specification.new do |spec|
spec.name = 'peeek'
spec.version = Peeek::VERSION
spec.authors = ['Takahiro Kondo']
spec.email = ['heartery@gmail.com']
spec.description = %q{Peek at calls of a method}
spec.summary = spec.description
spec.homepage = 'https://github.com/takkkun/peeek'
spec.license = 'MIT'
spec.required_ruby_version = '>= 1.8.7'
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler', '~> 1.3'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec'
end
|
Print a message to standard output indicating that Exlibris::Aleph has completed initialization | begin
# Load all the sub libraries when the application starts
Exlibris::Aleph::TablesManager.instance.sub_libraries.all
# Load all the item circulation policies when the application starts
Exlibris::Aleph::TablesManager.instance.item_circulation_policies.all
rescue Errno::ENOENT => e
message = "Skipping Exlibris::Aleph initialization since \"#{e.message}\""
p message
Rails.logger.warn(message)
end
| begin
# Load all the sub libraries when the application starts
Exlibris::Aleph::TablesManager.instance.sub_libraries.all
# Load all the item circulation policies when the application starts
Exlibris::Aleph::TablesManager.instance.item_circulation_policies.all
p 'Exlibris::Aleph initialized'
rescue Errno::ENOENT => e
message = "Skipping Exlibris::Aleph initialization since \"#{e.message}\""
p message
Rails.logger.warn(message)
end
|
Add method for getting overdue days | module CandyCheck
module AppStore
# Store multiple {Receipt}s in order to perform collective operation on them
class ReceiptCollection
# @return [Array<Receipt>]
attr_reader :receipts
# Initializes a new instance which bases on a JSON result
# from Apple's verification server
# @param attributes [Hash]
def initialize(attributes)
@receipts = attributes.map { |r| Receipt.new(r) }
end
# Check if the latest expiration date is passed
# @return [bool]
def expired?
last_expires_date.to_date <= Date.today
end
# Check if in trial
# @return [bool]
def trial?
@receipts.last.is_trial_period
end
# Get latest expiration date
# @return [DateTime]
def last_expires_date
@receipts.last.expires_date
end
end
end
end
| module CandyCheck
module AppStore
# Store multiple {Receipt}s in order to perform collective operation on them
class ReceiptCollection
# @return [Array<Receipt>]
attr_reader :receipts
# Initializes a new instance which bases on a JSON result
# from Apple's verification server
# @param attributes [Hash]
def initialize(attributes)
@receipts = attributes.map { |r| Receipt.new(r) }
end
# Check if the latest expiration date is passed
# @return [bool]
def expired?
overdue_days > 0
end
# Check if in trial
# @return [bool]
def trial?
@receipts.last.is_trial_period
end
# Get latest expiration date
# @return [DateTime]
def last_expires_date
@receipts.last.expires_date
end
# Get number of overdue days. If this is negative, it is not overdue.
# @return [Integer]
def overdue_days
(Date.today - last_expires_date.to_date).to_i
end
end
end
end
|
Add test of source_file for rails integration | require File.expand_path("../rails_helper", __FILE__)
describe EasySettings do
subject { described_class }
its(:namespace) { is_expected.to eq Rails.env }
its(:app_name) { is_expected.to eq "Test App for EasySettings" }
its(:endpoint) { is_expected.to eq "https://endpoint-for-test" }
its(:apikey) { is_expected.to eq "EASYSETTINGS" }
end
| require File.expand_path("../rails_helper", __FILE__)
describe EasySettings do
subject { described_class }
its(:namespace) { is_expected.to eq Rails.env }
its(:source_file) { is_expected.to eq Rails.root.join("config/settings.yml").to_s }
its(:app_name) { is_expected.to eq "Test App for EasySettings" }
its(:endpoint) { is_expected.to eq "https://endpoint-for-test" }
its(:apikey) { is_expected.to eq "EASYSETTINGS" }
end
|
Update Node.js documentation (6.0.0, 4.4.3) | module Docs
class Node < UrlScraper
self.name = 'Node.js'
self.slug = 'node'
self.type = 'node'
self.links = {
home: 'https://nodejs.org/',
code: 'https://github.com/nodejs/node'
}
html_filters.push 'node/clean_html', 'node/entries', 'title'
options[:title] = false
options[:root_title] = 'Node.js'
options[:container] = '#apicontent'
options[:skip] = %w(index.html all.html documentation.html synopsis.html)
options[:attribution] = <<-HTML
© Joyent, Inc. and other Node contributors<br>
Licensed under the MIT License.<br>
Node.js is a trademark of Joyent, Inc. and is used with its permission.<br>
We are not endorsed by or affiliated with Joyent.
HTML
version do
self.release = '5.11.0'
self.base_url = 'https://nodejs.org/api/'
end
version '4 LTS' do
self.release = '4.4.3'
self.base_url = "https://nodejs.org/dist/v#{release}/docs/api/"
end
end
end
| module Docs
class Node < UrlScraper
self.name = 'Node.js'
self.slug = 'node'
self.type = 'node'
self.links = {
home: 'https://nodejs.org/',
code: 'https://github.com/nodejs/node'
}
html_filters.push 'node/clean_html', 'node/entries', 'title'
options[:title] = false
options[:root_title] = 'Node.js'
options[:container] = '#apicontent'
options[:skip] = %w(index.html all.html documentation.html synopsis.html)
options[:attribution] = <<-HTML
© Joyent, Inc. and other Node contributors<br>
Licensed under the MIT License.<br>
Node.js is a trademark of Joyent, Inc. and is used with its permission.<br>
We are not endorsed by or affiliated with Joyent.
HTML
version do
self.release = '6.0.0'
self.base_url = 'https://nodejs.org/api/'
end
version '4 LTS' do
self.release = '4.4.3'
self.base_url = "https://nodejs.org/dist/v#{release}/docs/api/"
end
end
end
|
Refactor current scope to play nice with joins | # frozen_string_literal: true
class Forecast < ApplicationRecord
extend ApiMethods
self.abstract_class = true
belongs_to :api_request
belongs_to :spot
class << self
def current
where('timestamp > ?', Time.now.utc)
end
def ordered
order(:spot_id, :timestamp)
end
def default_scope
current.ordered
end
def api_url(spot)
raise_not_implemented_error
end
def parse_response(spot, request, responses)
raise_not_implemented_error
end
def api_pull(spot)
return false unless (result = api_get(api_url(spot)))
parse_response(spot, result.request, JSON.parse(result.response, object_class: OpenStruct))
true
end
def forecasted_max(stamps)
[
Spitcast.where(timestamp: stamps).maximum(:height),
Msw.where(timestamp: stamps).maximum(:max_height),
SurflineNearshore.where(timestamp: stamps).maximum(:max_height),
SurflineLola.where(timestamp: stamps).maximum(:max_height)
].map { |v| v || 0 }.max
end
private
def raise_not_implemented_error
raise NotImplementedError, "Subclass should override method '#{caller[0][/`.*'/][1..-2]}'"
end
end
end
| # frozen_string_literal: true
class Forecast < ApplicationRecord
extend ApiMethods
self.abstract_class = true
belongs_to :api_request
belongs_to :spot
class << self
def current
where(timestamp: Time.now.utc..(Time.now.utc + 1.month))
end
def ordered
order(:spot_id, :timestamp)
end
def default_scope
current.ordered
end
def api_url(spot)
raise_not_implemented_error
end
def parse_response(spot, request, responses)
raise_not_implemented_error
end
def api_pull(spot)
return false unless (result = api_get(api_url(spot)))
parse_response(spot, result.request, JSON.parse(result.response, object_class: OpenStruct))
true
end
def forecasted_max(stamps)
[
Spitcast.where(timestamp: stamps).maximum(:height),
Msw.where(timestamp: stamps).maximum(:max_height),
SurflineNearshore.where(timestamp: stamps).maximum(:max_height),
SurflineLola.where(timestamp: stamps).maximum(:max_height)
].map { |v| v || 0 }.max
end
private
def raise_not_implemented_error
raise NotImplementedError, "Subclass should override method '#{caller[0][/`.*'/][1..-2]}'"
end
end
end
|
Throw a named exception when the socket fails to connect. | require 'thread'
module Noam
class Player
def initialize(con_host,con_port)
@socket = TCPSocket.new(con_host, con_port)
@queue = Queue.new
@thread = Thread.new do |t|
begin
loop do
@socket.print(@queue.pop.nome_encode)
@socket.flush
end
rescue NoamThreadCancelled
# going down
ensure
@socket.close
end
end
end
def put(o)
@queue.push(o)
end
def stop
@thread.raise(NoamThreadCancelled)
@thread.join
end
end
end
| require 'thread'
module Noam
class NoamPlayerException < Exception; end
class Player
def initialize(con_host,con_port)
begin
@socket = TCPSocket.new(con_host, con_port)
rescue Errno::ECONNREFUSED
raise NoamPlayerException.new("Unable to connect to the Noam server at #{con_host}:#{con_port}. Is it running?")
end
@queue = Queue.new
@thread = Thread.new do |t|
begin
loop do
@socket.print(@queue.pop.nome_encode)
@socket.flush
end
rescue NoamThreadCancelled
# going down
ensure
@socket.close
end
end
end
def put(o)
@queue.push(o)
end
def stop
@thread.raise(NoamThreadCancelled)
@thread.join
end
end
end
|
Print Request-Id when HEROKU_DEBUG is on. | class HTTPInstrumentor
class << self
def filter_parameter(parameter)
@filter_parameters ||= []
@filter_parameters << parameter
end
def instrument(name, params={}, &block)
headers = params[:headers]
case name
when "excon.error"
$stderr.puts params[:error].message
when "excon.request"
$stderr.print "HTTP #{params[:method].upcase} #{params[:scheme]}://#{params[:host]}#{params[:path]} "
$stderr.print "[auth] " if headers['Authorization'] && headers['Authorization'] != 'Basic Og=='
$stderr.print "[2fa] " if headers['Heroku-Two-Factor-Code']
$stderr.puts filter(params[:query])
when "excon.response"
$stderr.puts "#{params[:status]} #{params[:reason_phrase]}"
if headers['Content-Encoding'] == 'gzip'
$stderr.puts filter(ungzip(params[:body]))
else
$stderr.puts filter(params[:body])
end
else
$stderr.puts name
end
yield if block_given?
end
private
def ungzip(string)
Zlib::GzipReader.new(StringIO.new(string)).read()
end
def filter(obj)
string = obj.to_s
(@filter_parameters || []).each do |parameter|
string.gsub! parameter, '[FILTERED]'
end
string
end
end
end
| class HTTPInstrumentor
class << self
def filter_parameter(parameter)
@filter_parameters ||= []
@filter_parameters << parameter
end
def instrument(name, params={}, &block)
headers = params[:headers]
case name
when "excon.error"
$stderr.puts params[:error].message
when "excon.request"
$stderr.print "HTTP #{params[:method].upcase} #{params[:scheme]}://#{params[:host]}#{params[:path]} "
$stderr.print "[auth] " if headers['Authorization'] && headers['Authorization'] != 'Basic Og=='
$stderr.print "[2fa] " if headers['Heroku-Two-Factor-Code']
$stderr.puts filter(params[:query])
when "excon.response"
$stderr.puts "#{params[:status]} #{params[:reason_phrase]}"
$stderr.puts "request-id: #{headers['Request-id']}" if headers['Request-Id']
if headers['Content-Encoding'] == 'gzip'
$stderr.puts filter(ungzip(params[:body]))
else
$stderr.puts filter(params[:body])
end
else
$stderr.puts name
end
yield if block_given?
end
private
def ungzip(string)
Zlib::GzipReader.new(StringIO.new(string)).read()
end
def filter(obj)
string = obj.to_s
(@filter_parameters || []).each do |parameter|
string.gsub! parameter, '[FILTERED]'
end
string
end
end
end
|
Add a rake task to wrap flattening utility | namespace :marriage_abroad do
desc "Flatten a set of outcomes for a given country"
task :flatten_outcomes, [:country] => [:environment] do |_, args|
MarriageAbroadOutcomeFlattener.new(args[:country]).flatten
end
end
| |
Allow country to be null. | class CreateAddresses < ActiveRecord::Migration
def change
create_table :addresses do |t|
t.integer :preference_order, :null => false, :default => 1
t.integer :address_preference_order, :null => false, :default => 1
t.string :full_street_address
t.string :unit_number
t.string :city
t.string :state_or_province
t.string :postal_code
t.string :country, :null => false, :default => "US"
t.timestamps
end
add_index :addresses, :city
add_index :addresses, :state_or_province
add_index :addresses, :country
end
end | class CreateAddresses < ActiveRecord::Migration
def change
create_table :addresses do |t|
t.integer :preference_order, :null => false, :default => 1
t.integer :address_preference_order, :null => false, :default => 1
t.string :full_street_address
t.string :unit_number
t.string :city
t.string :state_or_province
t.string :postal_code
t.string :country, :default => "US"
t.timestamps
end
add_index :addresses, :city
add_index :addresses, :state_or_province
add_index :addresses, :country
end
end |
Fix ssh hostname for in-house runs |
step "Create artifacts directory" do
unless File.directory?('artifacts')
Dir.mkdir("artifacts")
end
end
step "Collect puppetdb log file" do
# Would like to do this through the harness, but
# there is currently only an "scp_to" method on
# that goes *out* to the hosts, no method that
# scp's *from* the hosts.
scp_cmd = "scp root@#{database['ip']}:/var/log/puppetdb/puppetdb.log ./artifacts 2>&1"
PuppetAcceptance::Log.notify("Executing scp command:\n\n#{scp_cmd}\n\n")
result = `#{scp_cmd}`
status = $?
PuppetAcceptance::Log.notify(result)
assert(status.success?, "Collecting puppetdb log file failed with exit code #{status.exitstatus}.")
end
|
step "Create artifacts directory" do
unless File.directory?('artifacts')
Dir.mkdir("artifacts")
end
end
step "Collect puppetdb log file" do
# Would like to do this through the harness, but
# there is currently only an "scp_to" method on
# that goes *out* to the hosts, no method that
# scp's *from* the hosts.
ssh_host = database['ip'] || database.name
scp_cmd = "scp root@#{ssh_host}:/var/log/puppetdb/puppetdb.log ./artifacts 2>&1"
PuppetAcceptance::Log.notify("Executing scp command:\n\n#{scp_cmd}\n\n")
result = `#{scp_cmd}`
status = $?
PuppetAcceptance::Log.notify(result)
assert(status.success?, "Collecting puppetdb log file failed with exit code #{status.exitstatus}.")
end
|
Add missing DOWNTIME constant to the AddTimestampsToMembersAgain migration | # rubocop:disable all
# 20141121133009_add_timestamps_to_members.rb was meant to ensure that all
# rows in the members table had created_at and updated_at set, following an
# error in a previous migration. This failed to set all rows in at least one
# case: https://gitlab.com/gitlab-org/gitlab-ce/issues/20568
#
# Why this happened is lost in the mists of time, so repeat the SQL query
# without speculation, just in case more than one person was affected.
class AddTimestampsToMembersAgain < ActiveRecord::Migration
def up
execute "UPDATE members SET created_at = NOW() WHERE created_at IS NULL"
execute "UPDATE members SET updated_at = NOW() WHERE updated_at IS NULL"
end
def down
# no change
end
end
| # rubocop:disable all
# 20141121133009_add_timestamps_to_members.rb was meant to ensure that all
# rows in the members table had created_at and updated_at set, following an
# error in a previous migration. This failed to set all rows in at least one
# case: https://gitlab.com/gitlab-org/gitlab-ce/issues/20568
#
# Why this happened is lost in the mists of time, so repeat the SQL query
# without speculation, just in case more than one person was affected.
class AddTimestampsToMembersAgain < ActiveRecord::Migration
DOWNTIME = false
def up
execute "UPDATE members SET created_at = NOW() WHERE created_at IS NULL"
execute "UPDATE members SET updated_at = NOW() WHERE updated_at IS NULL"
end
def down
# no change
end
end
|
Add booking template id to line items. | class AddBookingTemplateIdToLineItems < ActiveRecord::Migration
def change
add_column :line_items, :booking_template_id, :integer
add_index :line_items, :booking_template_id
end
end
| |
Support a new bracket type | module Amakanize
module Filters
class BracketsNormalizationFilter < BaseFilter
PAIRS = %w|
‹ ›
‾ ‾
- -
〜 〜
« »
( )
[ ]
{ }
{ }
〈 〉
《 》
【 】
〔 〕
〘 〙
〚 〛
\[ \]
< >
< >
~ ~
|.each_slice(2)
# @note Override
# @param string [String] e.g. `"IS〈インフィニット・ストラトス〉 1 (オーバーラップ文庫)"`
# @return [String] e.g. `"IS(インフィニット・ストラトス) 1 (オーバーラップ文庫)"`
def call(string)
PAIRS.each_with_object(string) do |(open, close), result|
result.gsub!(/#{open}(.+?)#{close}/, '(\1)')
end
end
end
end
end
| module Amakanize
module Filters
class BracketsNormalizationFilter < BaseFilter
PAIRS = %w|
‹ ›
‾ ‾
- -
― ―
〜 〜
« »
( )
[ ]
{ }
{ }
〈 〉
《 》
【 】
〔 〕
〘 〙
〚 〛
\[ \]
< >
< >
~ ~
|.each_slice(2)
# @note Override
# @param string [String] e.g. `"IS〈インフィニット・ストラトス〉 1 (オーバーラップ文庫)"`
# @return [String] e.g. `"IS(インフィニット・ストラトス) 1 (オーバーラップ文庫)"`
def call(string)
PAIRS.each_with_object(string) do |(open, close), result|
result.gsub!(/#{open}(.+?)#{close}/, '(\1)')
end
end
end
end
end
|
Update configurer specs for new structure | require 'rspec'
require 'yaml'
require 'selenium-webdriver'
require 'jasmine_selenium_runner/configure_jasmine'
describe "Configuring jasmine" do
class FakeConfig
attr_accessor :port, :runner
end
def configure
Dir.stub(:pwd).and_return(working_dir)
Jasmine.stub(:configure).and_yield(fake_config)
JasmineSeleniumRunner::ConfigureJasmine.install_selenium_runner
end
def stub_config_file(config_obj)
config_path = File.join(working_dir, 'spec', 'javascripts', 'support', 'jasmine_selenium_runner.yml')
File.stub(:exist?).with(config_path).and_return(true)
File.stub(:read).with(config_path).and_return(YAML.dump(config_obj))
end
let(:working_dir) { 'hi' }
let(:fake_config) { FakeConfig.new }
context "when a custom selenium server is specified" do
before do
stub_config_file 'selenium_server' => 'http://example.com/selenium/stuff'
configure
end
it "make a webdriver pointing to the custom server" do
Selenium::WebDriver.should_receive(:for).with(:remote, hash_including(url: 'http://example.com/selenium/stuff'))
fake_config.runner.call(nil, nil)
end
end
context "when the user wants firebug installed" do
before do
stub_config_file 'browser' => 'firefox-firebug'
configure
end
it "should create a firebug profile and pass that to WebDriver" do
profile = double(:profile, enable_firebug: nil)
Selenium::WebDriver::Firefox::Profile.stub(:new).and_return(profile)
Selenium::WebDriver.should_receive(:for).with('firefox-firebug'.to_sym, {profile: profile})
fake_config.runner.call(nil, nil)
end
end
end
| require 'rspec'
require 'yaml'
require 'selenium-webdriver'
require 'jasmine_selenium_runner/configure_jasmine'
describe "Configuring jasmine" do
let(:configurer) { JasmineSeleniumRunner::ConfigureJasmine.new(nil, nil, config) }
context "when a custom selenium server is specified" do
let(:config) { { 'selenium_server' => 'http://example.com/selenium/stuff' }}
it "make a webdriver pointing to the custom server" do
Selenium::WebDriver.should_receive(:for).with(:remote, hash_including(url: 'http://example.com/selenium/stuff'))
configurer.make_runner
end
end
context "when the user wants firebug installed" do
let(:config) { { 'browser' => 'firefox-firebug' } }
it "should create a firebug profile and pass that to WebDriver" do
profile = double(:profile, enable_firebug: nil)
Selenium::WebDriver::Firefox::Profile.stub(:new).and_return(profile)
Selenium::WebDriver.should_receive(:for).with('firefox-firebug'.to_sym, {profile: profile})
configurer.make_runner
end
end
end
|
Test for displaying Trap Number | describe "miq_policy/_alert_details.html.haml" do
before do
@alert = FactoryGirl.create(:miq_alert)
exp = {:eval_method => 'nothing', :mode => 'internal', :options => {}}
allow(@alert).to receive(:expression).and_return(exp)
set_controller_for_view("miq_policy")
end
it "Trap Number is displayed correctly" do
opts = {:notifications => {:snmp => {:host => ['test.test.org'], :snmp_version => 'v1', :trap_id => '42'}}}
allow(@alert).to receive(:options).and_return(opts)
render :partial => "miq_policy/alert_details"
expect(rendered).to include('Trap Number')
end
end
| |
Remove CodeClimate (does not work) | require 'codeclimate-test-reporter'
## Start CodeClimate TestReporter
CodeClimate::TestReporter.start
require 'simplecov'
## Start Simplecov
SimpleCov.start 'rails' do
add_group 'Redmine Jenkins', 'plugins/redmine_jenkins'
end
## Load Redmine App
ENV["RAILS_ENV"] = 'test'
require File.expand_path(File.dirname(__FILE__) + '/../config/environment')
require 'rspec/rails'
## Load FactoryGirls factories
Dir[Rails.root.join("plugins/*/spec/factories/**/*.rb")].each {|f| require f}
## Configure RSpec
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
config.infer_spec_type_from_file_location!
config.color = true
config.fail_fast = false
config.expect_with :rspec do |c|
c.syntax = :expect
end
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
| require 'simplecov'
## Start Simplecov
SimpleCov.start 'rails' do
add_group 'Redmine Jenkins', 'plugins/redmine_jenkins'
end
## Load Redmine App
ENV["RAILS_ENV"] = 'test'
require File.expand_path(File.dirname(__FILE__) + '/../config/environment')
require 'rspec/rails'
## Load FactoryGirls factories
Dir[Rails.root.join("plugins/*/spec/factories/**/*.rb")].each {|f| require f}
## Configure RSpec
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
config.infer_spec_type_from_file_location!
config.color = true
config.fail_fast = false
config.expect_with :rspec do |c|
c.syntax = :expect
end
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
|
Remove unused MCAS subjects from validation whitelist | class Assessment < ActiveRecord::Base
has_many :student_assessments, dependent: :destroy
has_many :students, through: :student_assessments
validate :has_valid_subject
VALID_MCAS_SUBJECTS = [ 'ELA', 'Mathematics', 'Science', 'Arts', 'Technology' ].freeze
VALID_STAR_SUBJECTS = [ 'Mathematics', 'Reading' ].freeze
def has_valid_subject
case family
when 'MCAS'
errors.add(:subject, "must be a valid MCAS subject") unless subject.in?(VALID_MCAS_SUBJECTS)
when 'STAR'
errors.add(:subject, "must be a valid STAR subject") unless subject.in?(VALID_STAR_SUBJECTS)
when 'DIBELS'
errors.add(:subject, "DIBELS has no subject") unless subject.nil?
end
end
def self.seed_somerville_assessments
Assessment.create!([
{ family: "MCAS", subject: "Mathematics" },
{ family: "MCAS", subject: "ELA" },
{ family: "STAR", subject: "Mathematics" },
{ family: "STAR", subject: "Reading" },
{ family: "ACCESS" },
{ family: "DIBELS" }
])
end
end
| class Assessment < ActiveRecord::Base
has_many :student_assessments, dependent: :destroy
has_many :students, through: :student_assessments
validate :has_valid_subject
VALID_MCAS_SUBJECTS = [ 'ELA', 'Mathematics' ].freeze
VALID_STAR_SUBJECTS = [ 'Mathematics', 'Reading' ].freeze
def has_valid_subject
case family
when 'MCAS'
errors.add(:subject, "must be a valid MCAS subject") unless subject.in?(VALID_MCAS_SUBJECTS)
when 'STAR'
errors.add(:subject, "must be a valid STAR subject") unless subject.in?(VALID_STAR_SUBJECTS)
when 'DIBELS'
errors.add(:subject, "DIBELS has no subject") unless subject.nil?
end
end
def self.seed_somerville_assessments
Assessment.create!([
{ family: "MCAS", subject: "Mathematics" },
{ family: "MCAS", subject: "ELA" },
{ family: "STAR", subject: "Mathematics" },
{ family: "STAR", subject: "Reading" },
{ family: "ACCESS" },
{ family: "DIBELS" }
])
end
end
|
Implement generate_diff method for HunkLine | require_relative 'hunk_base'
module GitCrecord
module Hunks
class HunkLine < HunkBase
attr_accessor :selected
def initialize(line)
@line = line
@selected = true
super(add? || del?)
end
def strings(width)
@line.scan(/.{1,#{width}}/)
end
def add?
@line.start_with?('+')
end
def del?
@line.start_with?('-')
end
def highlightable?
add? || del?
end
def expanded
false
end
end
end
end
| require_relative 'hunk_base'
module GitCrecord
module Hunks
class HunkLine < HunkBase
attr_accessor :selected
def initialize(line)
@line = line
@selected = true
super(add? || del?)
end
def strings(width)
@line.scan(/.{1,#{width}}/)
end
def add?
@line.start_with?('+')
end
def del?
@line.start_with?('-')
end
def highlightable?
add? || del?
end
def expanded
false
end
def generate_diff
return " #{@line[1..-1]}" if !selected && del?
return @line if selected
nil
end
end
end
end
|
Set default Reek config to config/*.reek, per Reek docs | module MetricFu
class MetricReek < Metric
def name
:reek
end
def default_run_options
{ :dirs_to_reek => MetricFu::Io::FileSystem.directory('code_dirs'),
:config_file_pattern => nil}
end
def has_graph?
true
end
def enable
super
end
def activate
super
end
end
end
| module MetricFu
class MetricReek < Metric
def name
:reek
end
def default_run_options
{ :dirs_to_reek => MetricFu::Io::FileSystem.directory('code_dirs'),
:config_file_pattern => 'config/*.reek'}
end
def has_graph?
true
end
def enable
super
end
def activate
super
end
end
end
|
Use env variable for webhook. | require 'rubygems'
require 'sinatra'
require 'json'
require 'uri'
require 'net/http'
require 'dicebag'
post '/' do
puts request.POST.inspect
username = request.POST["user_name"]
text = request.POST["text"]
puts "requester: #{username}"
puts "text: #{text}"
die_request = text[5..-1].strip
%r{^(?<number_of_dice>\d+)d(?<die_size>\d+)?\+?(?<plus>\d+)?$} =~ die_request
if number_of_dice.nil? or die_size.nil?
return 200
end
result = DiceBag::Roll.new(die_request).result()
total = result.total
tally = result.sections[0].tally
webhook_url = "https://hooks.slack.com/services/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"
uri = URI(webhook_url)
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
request = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})
request.body = { "text" => "#{username} rolled #{number_of_dice}d#{die_size} and got #{total} #{tally}" }.to_json
response = https.request(request)
puts response.inspect
return 200
end
| require 'rubygems'
require 'sinatra'
require 'json'
require 'uri'
require 'net/http'
require 'dicebag'
post '/' do
puts request.POST.inspect
username = request.POST["user_name"]
text = request.POST["text"]
puts "requester: #{username}"
puts "text: #{text}"
die_request = text[5..-1].strip
%r{^(?<number_of_dice>\d+)d(?<die_size>\d+)?\+?(?<plus>\d+)?$} =~ die_request
if number_of_dice.nil? or die_size.nil?
return 200
end
result = DiceBag::Roll.new(die_request).result()
total = result.total
tally = result.sections[0].tally
webhook_url = ENV["SLACK_WEBHOOK_URL"]
uri = URI(webhook_url)
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
request = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})
request.body = { "text" => "#{username} rolled #{number_of_dice}d#{die_size} and got #{total} #{tally}" }.to_json
response = https.request(request)
puts response.inspect
return 200
end
|
Add missing route for supervisions list page | Peergroupsupervision::Application.routes.draw do
resources :rules
resources :chat_rooms do
member do
post :select_leader
post :select_problem_owner
end
resources :chat_updates
resources :chat_users
resources :chat_rules
end
resources :users do
get :following
get :followers
end
resources :sessions, :only => [:new, :create, :destroy]
resource :relationships, :only => [:create, :destroy]
resources :supervisions, :only => [:new, :create, :show] do
resources :topics, :only => [:new, :index, :create]
resources :topic_votes
resources :topic_questions
resources :topic_answers
resources :ideas
resources :ideas_feedbacks
resources :solutions
resources :solutions_feedbacks
resources :supervision_feedbacks
resources :votes
end
resources :groups do
resources :memberships
resources :rules
end
match '/signin' => 'sessions#new', :as => 'signin'
match '/signout' =>'sessions#destroy', :as => 'signout'
match '/contact' => 'pages#contact', :as => 'contact'
match '/about' => 'pages#about', :as => 'about'
match '/help' => 'pages#help', :as => 'help'
match '/signup' =>'users#new', :as => 'signup'
root :to => 'pages#home'
end
| Peergroupsupervision::Application.routes.draw do
resources :rules
resources :chat_rooms do
member do
post :select_leader
post :select_problem_owner
end
resources :chat_updates
resources :chat_users
resources :chat_rules
end
resources :users do
get :following
get :followers
end
resources :sessions, :only => [:new, :create, :destroy]
resource :relationships, :only => [:create, :destroy]
resources :supervisions, :only => [:new, :create, :show, :index] do
resources :topics, :only => [:new, :index, :create]
resources :topic_votes
resources :topic_questions
resources :topic_answers
resources :ideas
resources :ideas_feedbacks
resources :solutions
resources :solutions_feedbacks
resources :supervision_feedbacks
resources :votes
end
resources :groups do
resources :memberships
resources :rules
end
match '/signin' => 'sessions#new', :as => 'signin'
match '/signout' =>'sessions#destroy', :as => 'signout'
match '/contact' => 'pages#contact', :as => 'contact'
match '/about' => 'pages#about', :as => 'about'
match '/help' => 'pages#help', :as => 'help'
match '/signup' =>'users#new', :as => 'signup'
root :to => 'pages#home'
end
|
Update project_id primary and foreign keys to bigint | class ChangeProjectIdToBigint < ActiveRecord::Migration[6.0]
def up
change_column :projects, :id, :bigint
change_column :subjects, :project_id, :bigint
end
def down
change_column :projects, :id, :integer
change_column :subjects, :project_id, :integer
end
end
| |
Fix typo on task name | require 'active_support/all'
class DocumentProcessBootstrapTask
@queue = :document_process_bootstrap
def self.perform(document_id)
document = Document.find(document_id)
task_finder = TaskFinder.new(document)
if task_finder.last_task? and task_finder.current_task_ended?
document.update_attribute :status_msg, 'Completado'
document.update_attribute :percentage, 100
document.update_attribute :flagger_id, nil
else
klass = task_finder.next_task.split('_').map(&:capitalize).join.constantize
Resque.enqueue(klass, document_id)
end
end
end
| require 'active_support/all'
class DocumentProcessBootstrapTask
@queue = :document_process_bootstrap_task
def self.perform(document_id)
document = Document.find(document_id)
task_finder = TaskFinder.new(document)
if task_finder.last_task? and task_finder.current_task_ended?
document.update_attribute :status_msg, 'Completado'
document.update_attribute :percentage, 100
document.update_attribute :flagger_id, nil
else
klass = task_finder.next_task.split('_').map(&:capitalize).join.constantize
Resque.enqueue(klass, document_id)
end
end
end
|
Deal with the case where something like TT-32 returns a 404. | require 'jiralicious'
module Noteworthy
class Jira
attr_accessor :configured
def configure(config=nil)
@configured = false
return false if config.nil?
Jiralicious.configure do |c|
c.username = ENV["JIRA_USER"]
c.password = ENV["JIRA_PASS"]
c.uri = config['jira']
c.api_version = "latest"
c.auth_type = :basic
end
@configured = true
end
def get_issue(key=nil)
return false if key.nil?
return false unless self.configured?
return Jiralicious::Issue.find(key)
end
def configured?
return false unless @configured
@configured
end
end
end
| require 'jiralicious'
module Noteworthy
class Jira
attr_accessor :configured
def configure(config=nil)
@configured = false
return false if config.nil?
Jiralicious.configure do |c|
c.username = ENV["JIRA_USER"]
c.password = ENV["JIRA_PASS"]
c.uri = config['jira']
c.api_version = "latest"
c.auth_type = :basic
end
@configured = true
end
def get_issue(key=nil)
return false if key.nil?
return false unless self.configured?
begin
return Jiralicious::Issue.find(key)
rescue
return false
end
return false
end
def configured?
return false unless @configured
@configured
end
end
end
|
Add Jekyll v3.3 as dependency | # coding: utf-8
Gem::Specification.new do |spec|
spec.name = "minimal-mistakes-jekyll"
spec.version = "4.0.2"
spec.authors = ["Michael Rose"]
spec.summary = %q{A flexible two-column Jekyll theme.}
spec.homepage = "https://github.com/mmistakes/minimal-mistakes"
spec.license = "MIT"
spec.metadata["plugin_type"] = "theme"
spec.files = `git ls-files -z`.split("\x0").select do |f|
f.match(%r{^(assets|_(includes|layouts|sass)/|(LICENSE|README|CHANGELOG)((\.(txt|md|markdown)|$)))}i)
end
spec.add_development_dependency "jekyll", "~> 3.3"
spec.add_development_dependency "bundler", "~> 1.12"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_runtime_dependency "jekyll-paginate", "~> 1.1"
spec.add_runtime_dependency "jekyll-sitemap", "~> 0.10"
spec.add_runtime_dependency "jekyll-gist", "~> 1.4"
spec.add_runtime_dependency "jekyll-feed", "~> 0.5.1"
spec.add_runtime_dependency "jemoji", "~> 0.7"
end
| # coding: utf-8
Gem::Specification.new do |spec|
spec.name = "minimal-mistakes-jekyll"
spec.version = "4.0.2"
spec.authors = ["Michael Rose"]
spec.summary = %q{A flexible two-column Jekyll theme.}
spec.homepage = "https://github.com/mmistakes/minimal-mistakes"
spec.license = "MIT"
spec.metadata["plugin_type"] = "theme"
spec.files = `git ls-files -z`.split("\x0").select do |f|
f.match(%r{^(assets|_(includes|layouts|sass)/|(LICENSE|README|CHANGELOG)((\.(txt|md|markdown)|$)))}i)
end
spec.add_dependency "jekyll", "~> 3.3"
spec.add_development_dependency "bundler", "~> 1.12"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_runtime_dependency "jekyll-paginate", "~> 1.1"
spec.add_runtime_dependency "jekyll-sitemap", "~> 0.10"
spec.add_runtime_dependency "jekyll-gist", "~> 1.4"
spec.add_runtime_dependency "jekyll-feed", "~> 0.5.1"
spec.add_runtime_dependency "jemoji", "~> 0.7"
end
|
Add missing frozen_string_literal: true comment | module Transproc
# @api private
class Compiler
InvalidFunctionNameError = Class.new(StandardError)
attr_reader :registry, :transformer
def initialize(registry, transformer = nil)
@registry = registry
@transformer = transformer
end
def call(ast)
ast.map(&method(:visit)).reduce(:>>)
end
def visit(node)
id, *rest = node
public_send(:"visit_#{id}", *rest)
end
def visit_fn(node)
name, rest = node
args = rest.map { |arg| visit(arg) }
if registry.contain?(name)
registry[name, *args]
elsif transformer.respond_to?(name)
Function.new(transformer.method(name), name: name, args: args)
else
raise InvalidFunctionNameError, "function name +#{name}+ is not valid"
end
end
def visit_arg(arg)
arg
end
def visit_t(node)
call(node)
end
end
end
| # frozen_string_literal: true
module Transproc
# @api private
class Compiler
InvalidFunctionNameError = Class.new(StandardError)
attr_reader :registry, :transformer
def initialize(registry, transformer = nil)
@registry = registry
@transformer = transformer
end
def call(ast)
ast.map(&method(:visit)).reduce(:>>)
end
def visit(node)
id, *rest = node
public_send(:"visit_#{id}", *rest)
end
def visit_fn(node)
name, rest = node
args = rest.map { |arg| visit(arg) }
if registry.contain?(name)
registry[name, *args]
elsif transformer.respond_to?(name)
Function.new(transformer.method(name), name: name, args: args)
else
raise InvalidFunctionNameError, "function name +#{name}+ is not valid"
end
end
def visit_arg(arg)
arg
end
def visit_t(node)
call(node)
end
end
end
|
Use a warning for the deprecation notice | require "git_tracker/prepare_commit_message"
require "git_tracker/hook"
require "git_tracker/version"
module GitTracker
module Runner
def self.execute(cmd_arg = "help", *args)
command = cmd_arg.tr("-", "_")
abort("[git_tracker] command: '#{cmd_arg}' does not exist.") unless respond_to?(command)
send(command, *args)
end
def self.prepare_commit_msg(*args)
PrepareCommitMessage.run(*args)
end
def self.init
Hook.init
end
def self.install
puts "`git-tracker install` is deprecated. Please use `git-tracker init`"
init
end
def self.help
puts <<~HELP
git-tracker #{VERSION} is installed.
Remember, git-tracker is a hook which Git interacts with during its normal
lifecycle of committing, rebasing, merging, etc. You need to initialize this
hook by running `git-tracker init` from each repository in which you wish to
use it. Cheers!
HELP
end
end
end
| require "git_tracker/prepare_commit_message"
require "git_tracker/hook"
require "git_tracker/version"
module GitTracker
module Runner
def self.execute(cmd_arg = "help", *args)
command = cmd_arg.tr("-", "_")
abort("[git_tracker] command: '#{cmd_arg}' does not exist.") unless respond_to?(command)
send(command, *args)
end
def self.prepare_commit_msg(*args)
PrepareCommitMessage.run(*args)
end
def self.init
Hook.init
end
def self.install
warn("`git-tracker install` is deprecated. Please use `git-tracker init`", uplevel: 1)
init
end
def self.help
puts <<~HELP
git-tracker #{VERSION} is installed.
Remember, git-tracker is a hook which Git interacts with during its normal
lifecycle of committing, rebasing, merging, etc. You need to initialize this
hook by running `git-tracker init` from each repository in which you wish to
use it. Cheers!
HELP
end
end
end
|
Test still runs but commented out? win! | require 'test_helper'
class NotableDetailedTemplateTest < ActiveSupport::TestCase
def setup
@file_name = "/tmp/notable_detailed.pdf"
@template_manager = Risu::Base::TemplateManager.new "risu/templates"
@report = Report
@report.title = "Function Test"
@report.author = "hammackj"
@report.company = "None"
@report.classification = "None"
@templater = Risu::Base::Templater.new("notable_detailed", Report, @file_name, @template_manager)
@templater.generate
end
def teardown
File.delete(@file_name) if File.exist?(@file_name)
end
test "should create #{@filename} on template creation" do
assert File.exist?(@file_name) == true
end
#test "should have an MD5 of ca170f534913a0f9db79c931d9d56cf2 after creation" do
# require 'digest/md5'
# assert Digest::MD5.hexdigest(File.read(@file_name)) == "ca170f534913a0f9db79c931d9d56cf2", "GOT #{Digest::MD5.hexdigest(File.read(@file_name))}"
#end
end
#23c852872357f2808479275461cac1f3 | require 'test_helper'
class NotableDetailedTemplateTest < ActiveSupport::TestCase
def setup
@file_name = "/tmp/notable_detailed.pdf"
@template_manager = Risu::Base::TemplateManager.new "risu/templates"
@report = Report
@report.title = "Function Test"
@report.author = "hammackj"
@report.company = "None"
@report.classification = "None"
@templater = Risu::Base::Templater.new("notable_detailed", Report, @file_name, @template_manager)
@templater.generate
end
def teardown
File.delete(@file_name) if File.exist?(@file_name)
end
test "should create #{@filename} on template creation" do
assert File.exist?(@file_name) == true
end
#test "should have an MD5 of ca170f534913a0f9db79c931d9d56cf2 after creation" do
# require 'digest/md5'
# assert Digest::MD5.hexdigest(File.read(@file_name)) == "ca170f534913a0f9db79c931d9d56cf2", "GOT #{Digest::MD5.hexdigest(File.read(@file_name))}"
#end
end
|
Fix issue with es6 extension with JSHint | # encoding: utf-8
module Phare
class Check
class JSHint < Check
attr_reader :config, :path
def initialize(directory, options = {})
@config = File.expand_path("#{directory}.jshintrc", __FILE__)
@path = File.expand_path("#{directory}app/assets/javascripts", __FILE__)
@glob = File.join(@path, '**/*')
@extensions = %w(.js .js.es6)
@options = options
super
end
def command
if @tree.changed?
"jshint --config #{@config} --extra-ext #{@extensions.join(',')} #{@tree.changes.join(' ')}"
else
"jshint --config #{@config} --extra-ext #{@extensions.join(',')} #{@glob}"
end
end
protected
def binary_exists?
!Phare.system_output('which jshint').empty?
end
def configuration_exists?
File.exists?(@config)
end
def arguments_exists?
@tree.changed? || Dir.exists?(@path)
end
def print_banner
Phare.puts '---------------------------------------------'
Phare.puts 'Running JSHint to check for JavaScript style…'
Phare.puts '---------------------------------------------'
end
end
end
end
| # encoding: utf-8
module Phare
class Check
class JSHint < Check
attr_reader :config, :path
def initialize(directory, options = {})
@config = File.expand_path("#{directory}.jshintrc", __FILE__)
@path = File.expand_path("#{directory}app/assets/javascripts", __FILE__)
@glob = File.join(@path, '**/*')
@extensions = %w(.js .es6)
@options = options
super
end
def command
if @tree.changed?
"jshint --config #{@config} --extra-ext #{@extensions.join(',')} #{@tree.changes.join(' ')}"
else
"jshint --config #{@config} --extra-ext #{@extensions.join(',')} #{@glob}"
end
end
protected
def binary_exists?
!Phare.system_output('which jshint').empty?
end
def configuration_exists?
File.exists?(@config)
end
def arguments_exists?
@tree.changed? || Dir.exists?(@path)
end
def print_banner
Phare.puts '---------------------------------------------'
Phare.puts 'Running JSHint to check for JavaScript style…'
Phare.puts '---------------------------------------------'
end
end
end
end
|
Upgrade 'on' gem to 1.0.0 | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/neo/dci/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Peter Suschlik", "Jakob Holderbaum", "Jonas Thiel"]
gem.email = ["ps@neopoly.de", "jh@neopoly.de", "jt@neopoly.de"]
gem.description = %q{Simple DCI}
gem.summary = %q{Includes Data, Roles and Context.}
gem.homepage = "https://github.com/neopoly/neo-dci"
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 = "neo-dci"
gem.require_paths = ["lib"]
gem.version = Neo::DCI::VERSION
gem.add_runtime_dependency 'on', '~> 0.3.3'
gem.add_development_dependency 'rake'
gem.add_development_dependency 'rdoc'
gem.add_development_dependency 'minitest'
gem.add_development_dependency 'testem'
gem.add_development_dependency 'simplecov'
gem.add_development_dependency 'codeclimate-test-reporter', '~> 1.0.0'
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/neo/dci/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Peter Suschlik", "Jakob Holderbaum", "Jonas Thiel"]
gem.email = ["ps@neopoly.de", "jh@neopoly.de", "jt@neopoly.de"]
gem.description = %q{Simple DCI}
gem.summary = %q{Includes Data, Roles and Context.}
gem.homepage = "https://github.com/neopoly/neo-dci"
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 = "neo-dci"
gem.require_paths = ["lib"]
gem.version = Neo::DCI::VERSION
gem.add_runtime_dependency 'on', '~> 1.0.0'
gem.add_development_dependency 'rake'
gem.add_development_dependency 'rdoc'
gem.add_development_dependency 'minitest'
gem.add_development_dependency 'testem'
gem.add_development_dependency 'simplecov'
gem.add_development_dependency 'codeclimate-test-reporter', '~> 1.0.0'
end
|
Allow rendering an Arbre fragment in view component tests | module ViewComponentExampleGroup
extend ActiveSupport::Concern
include RSpec::Rails::RailsExampleGroup
include ActionView::TestCase::Behavior
include Capybara::RSpecMatchers
included do
attr_reader :rendered
end
def arbre
Arbre::Context.new({}, _view)
end
def helper
_view
end
def render(*args)
@rendered = arbre.send(described_class.builder_method_name, *args)
end
end
RSpec.configure do |config|
config.include(ViewComponentExampleGroup,
:example_group => lambda { |example_group, metadata|
%r(spec/views/components) =~ example_group[:file_path]
})
end
| module ViewComponentExampleGroup
extend ActiveSupport::Concern
include RSpec::Rails::RailsExampleGroup
include ActionView::TestCase::Behavior
include Capybara::RSpecMatchers
included do
attr_reader :rendered
end
def arbre(&block)
Arbre::Context.new({}, _view, &block)
end
def helper
_view
end
def render(*args, &block)
@rendered =
if block_given?
arbre(&block).to_s
else
arbre.send(described_class.builder_method_name, *args, &block)
end
end
end
RSpec.configure do |config|
config.include(ViewComponentExampleGroup,
:example_group => lambda { |example_group, metadata|
%r(spec/views/components) =~ example_group[:file_path]
})
end
|
Use yield instead of block.call | require 'twitter'
require 'retryable'
require 'set'
module T
module Collectable
MAX_NUM_RESULTS = 200
MAX_PAGE = 51
def collect_with_max_id(collection = [], max_id = nil, &block)
tweets = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do
yield(max_id)
end
return collection if tweets.nil?
collection += tweets
tweets.empty? ? collection.flatten : collect_with_max_id(collection, tweets.last.id - 1, &block)
end
def collect_with_count(count)
opts = {}
opts[:count] = MAX_NUM_RESULTS
collect_with_max_id do |max_id|
opts[:max_id] = max_id unless max_id.nil?
opts[:count] = count unless count >= MAX_NUM_RESULTS
if count > 0
tweets = yield opts
count -= tweets.length
tweets
end
end.flatten.compact
end
def collect_with_page(collection = ::Set.new, page = 1, previous = nil, &block)
tweets = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do
block.call(page)
end
return collection if tweets.nil? || tweets == previous || page >= MAX_PAGE
collection += tweets
tweets.empty? ? collection.flatten : collect_with_page(collection, page + 1, tweets, &block)
end
end
end
| require 'twitter'
require 'retryable'
require 'set'
module T
module Collectable
MAX_NUM_RESULTS = 200
MAX_PAGE = 51
def collect_with_max_id(collection = [], max_id = nil, &block)
tweets = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do
yield(max_id)
end
return collection if tweets.nil?
collection += tweets
tweets.empty? ? collection.flatten : collect_with_max_id(collection, tweets.last.id - 1, &block)
end
def collect_with_count(count)
opts = {}
opts[:count] = MAX_NUM_RESULTS
collect_with_max_id do |max_id|
opts[:max_id] = max_id unless max_id.nil?
opts[:count] = count unless count >= MAX_NUM_RESULTS
if count > 0
tweets = yield opts
count -= tweets.length
tweets
end
end.flatten.compact
end
def collect_with_page(collection = ::Set.new, page = 1, previous = nil, &block)
tweets = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do
yield page
end
return collection if tweets.nil? || tweets == previous || page >= MAX_PAGE
collection += tweets
tweets.empty? ? collection.flatten : collect_with_page(collection, page + 1, tweets, &block)
end
end
end
|
Use `scenario` instead of `it` in feature specs | require "rails_helper"
feature "Polls" do
context "Public index" do
it "Budget polls should not be listed" do
poll = create(:poll)
budget_poll = create(:poll, budget: create(:budget))
visit polls_path
expect(page).to have_content(poll.name)
expect(page).not_to have_content(budget_poll.name)
end
end
context "Admin index" do
it "Budget polls should not appear in the list" do
login_as(create(:administrator).user)
poll = create(:poll)
budget_poll = create(:poll, budget: create(:budget))
visit admin_polls_path
expect(page).to have_content(poll.name)
expect(page).not_to have_content(budget_poll.name)
end
end
end
| require "rails_helper"
feature "Polls" do
context "Public index" do
scenario "Budget polls should not be listed" do
poll = create(:poll)
budget_poll = create(:poll, budget: create(:budget))
visit polls_path
expect(page).to have_content(poll.name)
expect(page).not_to have_content(budget_poll.name)
end
end
context "Admin index" do
scenario "Budget polls should not appear in the list" do
login_as(create(:administrator).user)
poll = create(:poll)
budget_poll = create(:poll, budget: create(:budget))
visit admin_polls_path
expect(page).to have_content(poll.name)
expect(page).not_to have_content(budget_poll.name)
end
end
end
|
Refactor the object path class. | class Udongo::ObjectPath
def self.find(object)
unless object.is_a?(Array)
return "#{object.class.name.underscore}_path".gsub('_decorator', '')
end
object.map do |item|
item.is_a?(Symbol) ? "#{item}" : "#{item.class.name.underscore}".gsub('_decorator', '')
end.join('_') << '_path'
end
def self.remove_symbols(object)
return object unless object.is_a?(Array)
object.select { |o| !o.is_a?(Symbol) }
end
end
| class Udongo::ObjectPath
def self.find(object)
unless object.is_a?(Array)
return cleanup("#{object.class.name.underscore}_path")
end
object.map do |item|
item.is_a?(Symbol) ? "#{item}" : cleanup(item.class.name.underscore)
end.join('_') << '_path'
end
def self.remove_symbols(object)
return object unless object.is_a?(Array)
object.select { |o| !o.is_a?(Symbol) }
end
private
def self.cleanup(value)
value.to_s.gsub('_decorator', '')
end
end
|
Use ETSource fixture in the GQL controller spec | require 'spec_helper'
describe Data::GqueriesController do
render_views
let!(:admin) { FactoryGirl.create :admin }
let!(:gquery) { Gquery.all.first }
before do
login_as(admin)
FactoryGirl.create :scenario
end
describe "GET index" do
it "should be successful" do
get :index, :api_scenario_id =>'latest'
response.should render_template(:index)
end
end
describe "GET show" do
it "should be successful" do
get :show, :id => gquery.lookup_id, :api_scenario_id =>'latest'
response.should render_template(:show)
end
end
end
| require 'spec_helper'
describe Data::GqueriesController, :etsource_fixture do
render_views
let!(:admin) { FactoryGirl.create :admin }
let!(:gquery) { Gquery.get('bar_demand') }
before do
login_as(admin)
FactoryGirl.create :scenario
end
describe "GET index" do
it "should be successful" do
get :index, :api_scenario_id =>'latest'
response.should render_template(:index)
end
end
describe "GET show" do
it "should be successful" do
get :show, :id => gquery.lookup_id, :api_scenario_id =>'latest'
response.should render_template(:show)
end
end
end
|
Update webmock version in gemspec | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'wordpress_client/version'
Gem::Specification.new do |spec|
spec.name = "wordpress_client"
spec.version = WordpressClient::VERSION
spec.authors = ["Magnus Bergmark", "Rebecca Meritz"]
spec.email = ["magnus.bergmark@gmail.com", "rebecca@meritz.com"]
spec.summary = "A simple client to the Wordpress API."
spec.description = "A simple client to the Wordpress API."
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_dependency "faraday", "~> 0.9"
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.3"
spec.add_development_dependency "webmock", "~> 1.22"
spec.add_development_dependency "yard", "~> 0.8.7"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'wordpress_client/version'
Gem::Specification.new do |spec|
spec.name = "wordpress_client"
spec.version = WordpressClient::VERSION
spec.authors = ["Magnus Bergmark", "Rebecca Meritz"]
spec.email = ["magnus.bergmark@gmail.com", "rebecca@meritz.com"]
spec.summary = "A simple client to the Wordpress API."
spec.description = "A simple client to the Wordpress API."
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_dependency "faraday", "~> 0.9"
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.3"
spec.add_development_dependency "webmock", "~> 2.0"
spec.add_development_dependency "yard", "~> 0.8.7"
end
|
Add test that client -> server requests are handled in order | require 'acceptance/test_helper'
require 'timeout'
describe "Client requests information from the Server" do
before do
@server, @client1, @client2 = self.class.setup_environment
end
it "asks the server for information and waits for a response" do
@server.on(:client_info) do |message|
"Server responds"
end
message = Pantry::Communication::Message.new("client_info")
response_future = @client1.send_request(message)
Timeout::timeout(1) do
assert_equal ["Server responds"], response_future.value.body
end
end
end
| require 'acceptance/test_helper'
require 'timeout'
describe "Client requests information from the Server" do
before do
@server, @client1, @client2 = self.class.setup_environment
end
it "asks the server for information and waits for a response" do
@server.on(:client_info) do |message|
"Server responds"
end
message = Pantry::Communication::Message.new("client_info")
response_future = @client1.send_request(message)
Timeout::timeout(1) do
assert_equal ["Server responds"], response_future.value.body
end
end
it "handles multiple requests in the proper order" do
response_count = 0
@server.on(:client_info) do |message|
"Server responds #{response_count += 1}"
end
message = Pantry::Communication::Message.new("client_info")
futures = []
10.times do
futures << @client1.send_request(message)
end
Timeout::timeout(5) do
futures.each_with_index do |future, idx|
assert_equal ["Server responds #{idx + 1}"], future.value.body
end
end
end
end
|
Use present? to handle empty array | module Mobility
module ActiveRecord
class UniquenessValidator < ::ActiveRecord::Validations::UniquenessValidator
def validate_each(record, attribute, value)
klass = record.class
if klass.translated_attribute_names.include?(attribute.to_s) ||
(Array(options[:scope]).map(&:to_s) & klass.translated_attribute_names)
return unless value.present?
relation = klass.send(Mobility.query_method).where(attribute => value)
relation = relation.where.not(klass.primary_key => record.id) if record.persisted?
Array(options[:scope]).each do |scope_item|
relation = relation.where(scope_item => record.send(scope_item))
end
relation = relation.merge(options[:conditions]) if options[:conditions]
if relation.exists?
error_options = options.except(:case_sensitive, :scope, :conditions)
error_options[:value] = value
record.errors.add(attribute, :taken, error_options)
end
else
super
end
end
end
end
end
| module Mobility
module ActiveRecord
class UniquenessValidator < ::ActiveRecord::Validations::UniquenessValidator
def validate_each(record, attribute, value)
klass = record.class
if klass.translated_attribute_names.include?(attribute.to_s) ||
(Array(options[:scope]).map(&:to_s) & klass.translated_attribute_names).present?
return unless value.present?
relation = klass.send(Mobility.query_method).where(attribute => value)
relation = relation.where.not(klass.primary_key => record.id) if record.persisted?
Array(options[:scope]).each do |scope_item|
relation = relation.where(scope_item => record.send(scope_item))
end
relation = relation.merge(options[:conditions]) if options[:conditions]
if relation.exists?
error_options = options.except(:case_sensitive, :scope, :conditions)
error_options[:value] = value
record.errors.add(attribute, :taken, error_options)
end
else
super
end
end
end
end
end
|
Include all files in lib | # -*- encoding: utf-8 -*-
$:.unshift File.expand_path('../lib', __FILE__)
require 'claide'
Gem::Specification.new do |s|
s.name = "claide"
s.version = CLAide::VERSION
s.license = "MIT"
s.email = ["eloy.de.enige@gmail.com", "fabiopelosin@gmail.com"]
s.homepage = "https://github.com/CocoaPods/CLAide"
s.authors = ["Eloy Duran", "Fabio Pelosin"]
s.summary = "A small command-line interface framework."
s.files = %w{ lib/claide.rb README.markdown LICENSE }
s.require_paths = %w{ lib }
## Make sure you can build the gem on older versions of RubyGems too:
s.rubygems_version = "1.6.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.specification_version = 3 if s.respond_to? :specification_version
end
| # -*- encoding: utf-8 -*-
$:.unshift File.expand_path('../lib', __FILE__)
require 'claide'
Gem::Specification.new do |s|
s.name = "claide"
s.version = CLAide::VERSION
s.license = "MIT"
s.email = ["eloy.de.enige@gmail.com", "fabiopelosin@gmail.com"]
s.homepage = "https://github.com/CocoaPods/CLAide"
s.authors = ["Eloy Duran", "Fabio Pelosin"]
s.summary = "A small command-line interface framework."
s.files = Dir["lib/**/*.rb"] + %w{ README.markdown LICENSE }
s.require_paths = %w{ lib }
## Make sure you can build the gem on older versions of RubyGems too:
s.rubygems_version = "1.6.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.specification_version = 3 if s.respond_to? :specification_version
end
|
Fix warning regarding putting a space before parentheses. | module CachingHelpers
def cached_directory
"spec/dummy/public/refinery/cache/pages"
end
def cached_file_path(page)
"#{cached_directory}#{refinery.page_path(page)}.html"
end
def cache_page(page)
Refinery::PagesController.any_instance.stub(:refinery_user?).and_return(false)
visit refinery.page_path(page)
Refinery::PagesController.any_instance.unstub(:refinery_user?)
end
RSpec::Matchers.define :be_cached do
match do |page|
File.exists? (cached_file_path(page))
end
end
end | module CachingHelpers
def cached_directory
"spec/dummy/public/refinery/cache/pages"
end
def cached_file_path(page)
"#{cached_directory}#{refinery.page_path(page)}.html"
end
def cache_page(page)
Refinery::PagesController.any_instance.stub(:refinery_user?).and_return(false)
visit refinery.page_path(page)
Refinery::PagesController.any_instance.unstub(:refinery_user?)
end
RSpec::Matchers.define :be_cached do
match do |page|
File.exists?(cached_file_path(page))
end
end
end
|
Fix to pulling in sales tax items | class QbwcWorkers::Requests::SalesTaxItemImport < QbwcWorkers::Requests::BaseImport
self.query ={
:sales_tax_item_query_rq =>{
}
}
end
| class QbwcWorkers::Requests::SalesTaxItemImport < QbwcWorkers::Requests::BaseImport
self.query ={
:item_sales_tax_query_rq =>{
}
}
end
|
Fix `url` stanza comment for Lingo. | cask 'lingo' do
version :latest
sha256 :no_check
# nounproject.s3.amazonaws.com/lingo was verified as official when first introduced to the cask.
url 'https://nounproject.s3.amazonaws.com/lingo/Lingo.dmg'
name 'Lingo'
homepage 'https://lingoapp.com'
license :gratis
app 'Lingo.app'
zap delete: [
'~/Library/Preferences/com.lingoapp.Lingo.plist',
'~/Library/Application Support/com.lingoapp.Lingo',
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.lingoapp.lingo.sfl',
]
end
| cask 'lingo' do
version :latest
sha256 :no_check
# nounproject.s3.amazonaws.com/lingo was verified as official when first introduced to the cask
url 'https://nounproject.s3.amazonaws.com/lingo/Lingo.dmg'
name 'Lingo'
homepage 'https://lingoapp.com'
license :gratis
app 'Lingo.app'
zap delete: [
'~/Library/Preferences/com.lingoapp.Lingo.plist',
'~/Library/Application Support/com.lingoapp.Lingo',
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.lingoapp.lingo.sfl',
]
end
|
Include iso_code3 in emissions request | module Api
module V1
module HistoricalEmissions
class RecordSerializer < ActiveModel::Serializer
belongs_to :location
belongs_to :gas
belongs_to :data_source, key: :source
belongs_to :sector
attribute :emissions
attribute :gwp
def location
object.location.wri_standard_name
end
def gas
object.gas.name
end
def data_source
object.data_source.name
end
def sector
object.sector.name
end
def gwp
object.gwp.name
end
def emissions
date_before = @instance_options[:params]['date_before']&.to_i
date_after = @instance_options[:params]['date_after']&.to_i
object.emissions.select do |em|
(date_before ? em['year'] <= date_before : true) &&
(date_after ? em['year'] >= date_after : true)
end
end
end
end
end
end
| module Api
module V1
module HistoricalEmissions
class RecordSerializer < ActiveModel::Serializer
belongs_to :location
belongs_to :iso_code3
belongs_to :gas
belongs_to :data_source, key: :source
belongs_to :sector
attribute :emissions
attribute :gwp
def location
object.location.wri_standard_name
end
def iso_code3
object.location.iso_code3
end
def gas
object.gas.name
end
def data_source
object.data_source.name
end
def sector
object.sector.name
end
def gwp
object.gwp.name
end
def emissions
date_before = @instance_options[:params]['date_before']&.to_i
date_after = @instance_options[:params]['date_after']&.to_i
object.emissions.select do |em|
(date_before ? em['year'] <= date_before : true) &&
(date_after ? em['year'] >= date_after : true)
end
end
end
end
end
end
|
Update the minimum deployment target in the podspec | Pod::Spec.new do |s|
s.name = "pgoapi"
s.version = "0.0.2"
s.summary = "A Pokèmon Go API written in swift."
s.description = <<-DESC
This is still a work in progress. The only working function at the moment is login via PTC, and downloading the following data:
player data, hatched eggs, inventory, badges, settings, & map objects.
DESC
s.homepage = "https://github.com/AgentFeeble/pgoapi"
s.license = "Apache"
s.author = "Rayman Rosevear"
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.10'
s.source = { :git => "https://github.com/AgentFeeble/pgoapi.git", :tag => "#{s.version}" }
s.source_files = "pgoapi/Classes/**/*.{swift,h,c,mm}", "pgoapi/3rd Party/**/*.{h,c,cc}"
s.public_header_files = "pgoapi/Classes/**/*.h"
s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
s.dependency "Alamofire", "~> 4.0.1"
s.dependency "Bolts-Swift", "~> 1.3.0"
s.dependency "ProtocolBuffers-Swift"
end
| Pod::Spec.new do |s|
s.name = "pgoapi"
s.version = "0.0.2"
s.summary = "A Pokèmon Go API written in swift."
s.description = <<-DESC
This is still a work in progress. The only working function at the moment is login via PTC, and downloading the following data:
player data, hatched eggs, inventory, badges, settings, & map objects.
DESC
s.homepage = "https://github.com/AgentFeeble/pgoapi"
s.license = "Apache"
s.author = "Rayman Rosevear"
s.ios.deployment_target = '9.0'
s.osx.deployment_target = '10.10'
s.source = { :git => "https://github.com/AgentFeeble/pgoapi.git", :tag => "#{s.version}" }
s.source_files = "pgoapi/Classes/**/*.{swift,h,c,mm}", "pgoapi/3rd Party/**/*.{h,c,cc}"
s.public_header_files = "pgoapi/Classes/**/*.h"
s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
s.dependency "Alamofire", "~> 4.0.1"
s.dependency "Bolts-Swift", "~> 1.3.0"
s.dependency "ProtocolBuffers-Swift"
end
|
Fix NameError when installing plugin | module OpenProject::Revisions::Subversion
VERSION = "0.0.1"
end
| module OpenProject
module Revisions
module Subversion
VERSION = "0.0.1"
end
end
end
|
Remove secret key reference for prod | require 'sinatra'
require 'sinatra/static_assets'
require 'json'
require 'rest_client'
require 'fast-aes'
require 'profiler'
require 'sanitize'
configure do
set :views, ['views/layouts', 'views/pages', 'views/partials']
enable :sessions
set :production, true
if settings.production?
set :domain, "https://be.nowcado.com"
else
set :domain, "https://127.0.0.1:3000"
end
set :secret_key, File.read('secret-key').strip
end
Dir["./app/models/*.rb"].each { |file| require file }
Dir["./app/helpers/*.rb"].each { |file| require file }
Dir["./app/controllers/*.rb"].each { |file| require file }
before "/*" do
#if mobile_request?
# set :mobile, "mobile/"
# set :erb, :layout => :mobile
#else
set :mobile, ""
set :erb, :layout => :layout
#end
end
| require 'sinatra'
require 'sinatra/static_assets'
require 'json'
require 'rest_client'
require 'fast-aes'
require 'profiler'
require 'sanitize'
configure do
set :views, ['views/layouts', 'views/pages', 'views/partials']
enable :sessions
set :production, true
if settings.production?
set :domain, "https://be.nowcado.com"
else
set :domain, "https://127.0.0.1:3000"
end
#set :secret_key, File.read('secret-key').strip
end
Dir["./app/models/*.rb"].each { |file| require file }
Dir["./app/helpers/*.rb"].each { |file| require file }
Dir["./app/controllers/*.rb"].each { |file| require file }
before "/*" do
#if mobile_request?
# set :mobile, "mobile/"
# set :erb, :layout => :mobile
#else
set :mobile, ""
set :erb, :layout => :layout
#end
end
|
Add license and description to gemspec. | Gem::Specification.new do |s|
s.name = 'lancat'
s.version = '0.0.1'
s.summary = 'Zero-configuration LAN file transfer'
s.author = 'Graham Edgecombe'
s.email = 'graham@grahamedgecombe.com'
s.homepage = 'http://grahamedgecombe.com/projects/lancat'
s.files = Dir['{bin/lancat,lib/lancat.rb,lib/lancat/*.rb}']
s.executables = 'lancat'
end
| Gem::Specification.new do |s|
s.name = 'lancat'
s.version = '0.0.1'
s.summary = 'Zero-configuration LAN file transfer'
s.description = 'lancat is a program which allows files and other data to ' \
'be quickly transferred over the local network by piping ' \
'data into lancat in the shell at one end, and out of ' \
'lancat at the other end. It uses multicast so no ' \
'configuration (e.g. of IP addresses) needs to take place.'
s.license = 'ISC'
s.author = 'Graham Edgecombe'
s.email = 'graham@grahamedgecombe.com'
s.homepage = 'http://grahamedgecombe.com/projects/lancat'
s.files = Dir['{bin/lancat,lib/lancat.rb,lib/lancat/*.rb}']
s.executables = 'lancat'
end
|
Fix validation. rehab year must be entered | #
# Schedule Rehabilitation update event. This is event type is required for
# all implementations
#
class ScheduleRehabilitationUpdateEvent < AssetEvent
# Callbacks
after_initialize :set_defaults
validates :rebuild_year, :numericality => {:only_integer => :true, :greater_than_or_equal_to => Date.today.year - 10}, :allow_nil => true
#------------------------------------------------------------------------------
# Scopes
#------------------------------------------------------------------------------
# set the default scope
default_scope { where(:asset_event_type_id => AssetEventType.find_by_class_name(self.name).id).order(:event_date, :created_at) }
# List of hash parameters allowed by the controller
FORM_PARAMS = [
:rebuild_year
]
#------------------------------------------------------------------------------
#
# Class Methods
#
#------------------------------------------------------------------------------
def self.allowable_params
FORM_PARAMS
end
#returns the asset event type for this type of event
def self.asset_event_type
AssetEventType.find_by_class_name(self.name)
end
#------------------------------------------------------------------------------
#
# Instance Methods
#
#------------------------------------------------------------------------------
# This must be overriden otherwise a stack error will occur
def get_update
"Scheduled for rehabilitation in #{fiscal_year(rebuild_year)}."
end
protected
# Set resonable defaults for a new condition update event
def set_defaults
super
self.rebuild_year ||= current_fiscal_year_year
self.asset_event_type ||= AssetEventType.find_by_class_name(self.name)
end
end
| #
# Schedule Rehabilitation update event. This is event type is required for
# all implementations
#
class ScheduleRehabilitationUpdateEvent < AssetEvent
# Callbacks
after_initialize :set_defaults
validates :rebuild_year, :numericality => {:only_integer => :true, :greater_than_or_equal_to => Date.today.year - 10}
#------------------------------------------------------------------------------
# Scopes
#------------------------------------------------------------------------------
# set the default scope
default_scope { where(:asset_event_type_id => AssetEventType.find_by_class_name(self.name).id).order(:event_date, :created_at) }
# List of hash parameters allowed by the controller
FORM_PARAMS = [
:rebuild_year
]
#------------------------------------------------------------------------------
#
# Class Methods
#
#------------------------------------------------------------------------------
def self.allowable_params
FORM_PARAMS
end
#returns the asset event type for this type of event
def self.asset_event_type
AssetEventType.find_by_class_name(self.name)
end
#------------------------------------------------------------------------------
#
# Instance Methods
#
#------------------------------------------------------------------------------
# This must be overriden otherwise a stack error will occur
def get_update
"Scheduled for rehabilitation in #{fiscal_year(rebuild_year)}."
end
protected
# Set resonable defaults for a new condition update event
def set_defaults
super
self.rebuild_year ||= current_fiscal_year_year
self.asset_event_type ||= AssetEventType.find_by_class_name(self.name)
end
end
|
Update model extension to support some extra irisi specific cruft | module Domgen
module Iris
class IrisElement < BaseConfigElement
attr_reader :parent
def initialize(parent, options = {}, &block)
@parent = parent
super(options, &block)
end
end
class IrisAttribute < IrisElement
attr_accessor :inverse_sorter
end
class IrisClass < IrisElement
end
end
class Attribute
def iris
@iris = Domgen::Iris::IrisAttribute.new(self) unless @iris
@iris
end
end
class ObjectType
def iris
@iris = Domgen::Iris::IrisClass.new(self) unless @iris
@iris
end
end
end
| module Domgen
module Iris
class IrisElement < BaseConfigElement
attr_reader :parent
def initialize(parent, options = {}, &block)
@parent = parent
super(options, &block)
end
end
class IrisAttribute < IrisElement
attr_accessor :inverse_sorter
attr_writer :traversable
def traversable?
@traversable = false if @traversable.nil?
@traversable
end
end
class IrisClass < IrisElement
attr_accessor :metadata_that_can_change
attr_accessor :display_name
end
end
class Attribute
def iris
@iris = Domgen::Iris::IrisAttribute.new(self) unless @iris
@iris
end
end
class ObjectType
def iris
@iris = Domgen::Iris::IrisClass.new(self) unless @iris
@iris
end
end
end
|
Add seed for dummy app | # create users
User.create(email: 'partner@example.com')
partner = User.first
4.times do |n|
User.create(email: "m#{n}@example.com")
User.last.tap do |u|
partner.reload.partnership.referrals << u
Referrals::IncomeHistory.create(
referral: u,
partner: partner.partnership,
info: 'Payment for subscription',
amount: 2077,
share: partner.partnership.share,
share_amount: partner.partnership.share * 2077
)
end
end
| |
Kill unneeded assignment to local var | module ZombieScout
class MethodCallFinder
def initialize(ruby_project)
@ruby_project = ruby_project
end
def count_calls(method_name)
method_name = method_name.to_s
method_name.sub!(/=$/, ' *=')
find_occurrances(method_name).size
end
private
def find_occurrances(method_name)
# TODO somehow expose some of this config for end-users
command = "grep -rnw --include=\"*.rb\" --include=\"*.erb\" --binary-files=without-match #{method_name} #{files_to_search} "
# grep -r --include="*.rb" --include="*.erb" -nw PATTERN app lib
grep_lines = `#{command}`
grep_lines.split("\n")
end
def files_to_search
glob = @ruby_project.folders.join(' ')
end
end
end
| module ZombieScout
class MethodCallFinder
def initialize(ruby_project)
@ruby_project = ruby_project
end
def count_calls(method_name)
method_name = method_name.to_s
method_name.sub!(/=$/, ' *=')
find_occurrances(method_name).size
end
private
def find_occurrances(method_name)
# TODO somehow expose some of this config for end-users
command = "grep -rnw --include=\"*.rb\" --include=\"*.erb\" --binary-files=without-match #{method_name} #{files_to_search} "
# grep -r --include="*.rb" --include="*.erb" -nw PATTERN app lib
grep_lines = `#{command}`
grep_lines.split("\n")
end
def files_to_search
@ruby_project.folders.join(' ')
end
end
end
|
Make sure UserDefinedTypeInfo is available | require 'ffi'
require 'gir_ffi-base'
require 'ffi-gobject_introspection'
require 'gir_ffi/ffi_ext'
require 'gir_ffi/class_base'
require 'gir_ffi/type_map'
require 'gir_ffi/info_ext'
require 'gir_ffi/in_pointer'
require 'gir_ffi/in_out_pointer'
require 'gir_ffi/sized_array'
require 'gir_ffi/zero_terminated'
require 'gir_ffi/arg_helper'
require 'gir_ffi/builder'
module GirFFI
def self.setup module_name, version=nil
module_name = module_name.to_s
GirFFI::Builder.build_module module_name, version
end
def self.define_type klass, &block
info = UserDefinedTypeInfo.new(klass, &block)
Builders::UserDefinedBuilder.new(info).build_class
klass.get_gtype
end
end
require 'ffi-glib'
require 'ffi-gobject'
| require 'ffi'
require 'gir_ffi-base'
require 'ffi-gobject_introspection'
require 'gir_ffi/ffi_ext'
require 'gir_ffi/class_base'
require 'gir_ffi/type_map'
require 'gir_ffi/info_ext'
require 'gir_ffi/in_pointer'
require 'gir_ffi/in_out_pointer'
require 'gir_ffi/sized_array'
require 'gir_ffi/zero_terminated'
require 'gir_ffi/arg_helper'
require 'gir_ffi/user_defined_type_info'
require 'gir_ffi/builder'
module GirFFI
def self.setup module_name, version=nil
module_name = module_name.to_s
GirFFI::Builder.build_module module_name, version
end
def self.define_type klass, &block
info = UserDefinedTypeInfo.new(klass, &block)
Builders::UserDefinedBuilder.new(info).build_class
klass.get_gtype
end
end
require 'ffi-glib'
require 'ffi-gobject'
|
Remove ref to top-level constant | require 'spec_helper'
describe TaskMapper::Basecamp do
let(:tm) { create_instance }
describe "#new" do
it "creates a new TaskMapper instance" do
expect(tm).to be_a TaskMapper
end
it "can be explicitly called as a provider" do
tm = TaskMapper::Provider::Basecamp.new(
:token => token,
:domain => domain
)
expect(tm).to be_a TaskMapper
end
end
describe "#valid?" do
context "with a correctly authenticated Basecamp user" do
it "returns true" do
expect(tm.valid?).to be_true
end
end
end
end
| require 'spec_helper'
describe TaskMapper::Provider::Basecamp do
let(:tm) { create_instance }
describe "#new" do
it "creates a new TaskMapper instance" do
expect(tm).to be_a TaskMapper
end
it "can be explicitly called as a provider" do
tm = TaskMapper::Provider::Basecamp.new(
:token => token,
:domain => domain
)
expect(tm).to be_a TaskMapper
end
end
describe "#valid?" do
context "with a correctly authenticated Basecamp user" do
it "returns true" do
expect(tm.valid?).to be_true
end
end
end
end
|
Create new comment to avoid nil form object | class CommentsController < ApplicationController
def new
@trail = Trail.find(params[:trail_id])
@comments = @trail.comments
render :new
end
def create
@comment = Comment.new(comment_params)
@comment.user_id = current_user
if @comment.save
redirect_to trail_path
else
render :new
end
end
private
def comment_params
params.require(:comment).permit(:content,:user_id,:trail_id)
end
end | class CommentsController < ApplicationController
def new
@trail = Trail.find(params[:trail_id])
@comment = Comment.new
render :new
end
def create
@comment = Comment.new(comment_params)
@comment.user_id = current_user
if @comment.save
redirect_to trail_path
else
render :new
end
end
private
def comment_params
params.require(:comment).permit(:content,:user_id,:trail_id)
end
end |
Remove autoload in favor of require | path = File.expand_path(File.dirname(__FILE__))
$:.unshift(path) unless $:.include?(path)
require path + '/rfm/utilities/case_insensitive_hash'
require path + '/rfm/utilities/factory'
module Rfm
class CommunicationError < StandardError; end
class ParameterError < StandardError; end
class AuthenticationError < StandardError; end
autoload :Error, 'rfm/error'
autoload :Server, 'rfm/server'
autoload :Database, 'rfm/database'
autoload :Layout, 'rfm/layout'
autoload :Resultset, 'rfm/resultset'
end | # encoding: utf-8
require 'rfm/utilities/case_insensitive_hash'
require 'rfm/utilities/factory'
require 'rfm/error'
require 'rfm/server'
require 'rfm/database'
require 'rfm/layout'
require 'rfm/resultset'
module Rfm
class CommunicationError < StandardError; end
class ParameterError < StandardError; end
class AuthenticationError < StandardError; end
end
|
Correct assignment to array's last element | module WorthSaving
module Form
module Record
def self.included(base)
base.send :include, InstanceMethods
end
module InstanceMethods
private
def record
@record
end
def draft
@draft ||= object.worth_saving_draft
end
def options
@options
end
def object
@object ||= record.is_a?(Array) ? record.last : record
end
def recovery?
# TODO: If a draft is present but reconstituting the draft will provide no additional information
# about the record, delete the draft and make recovery false
@recovery ||= draft.present?
end
def rescued_object
@rescued_object ||= draft && draft.reconstituted_record
end
def rescued_record
if record.is_a? Array
rescued_record = record.dup
rescued_record.last = rescued_object
else
rescued_record = rescued_object
end
end
end
end
end
end | module WorthSaving
module Form
module Record
def self.included(base)
base.send :include, InstanceMethods
end
module InstanceMethods
private
def record
@record
end
def draft
@draft ||= object.worth_saving_draft
end
def options
@options
end
def object
@object ||= record.is_a?(Array) ? record.last : record
end
def recovery?
# TODO: If a draft is present but reconstituting the draft will provide no additional information
# about the record, delete the draft and make recovery false
@recovery ||= draft.present?
end
def rescued_object
@rescued_object ||= draft && draft.reconstituted_record
end
def rescued_record
if record.is_a? Array
rescued_record = record.dup
rescued_record[-1] = rescued_object
else
rescued_record = rescued_object
end
end
end
end
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.