Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add unit test to install a specific version. | require 'spec_helper'
describe 'default recipe on Ubuntu 14.04' do
let(:chef_run) do
ChefSpec::ServerRunner.new do |node|
node.automatic[:lsb][:codename] = 'trusty'
end.converge('chef-grafana::default')
end
it 'converges successfully' do
expect { :chef_run }.to_not raise_error
end
end
| require 'spec_helper'
describe 'default recipe on Ubuntu 14.04' do
let(:chef_run) do
ChefSpec::ServerRunner.new do |node|
node.automatic[:lsb][:codename] = 'trusty'
end.converge('chef-grafana::default')
end
let(:chef_run_versioned) do
ChefSpec::ServerRunner.new do |node|
node.automatic['chef-grafana']['install']['version'] = '4.5.0'
end.converge('chef-grafana::default')
end
context 'latest version' do
it 'converges successfully' do
expect { :chef_run }.to_not raise_error
end
it 'upgrades successfully' do
expect(chef_run).to upgrade_package('grafana')
end
end
context 'specific version' do
it 'converges successfully' do
expect { :chef_run_versioned }.to_not raise_error
end
it 'installs successfully' do
expect(chef_run_versioned).to install_package('grafana').with(version: '4.5.0')
end
end
end
|
Add Compiler with output specified context. | require "test_helper"
class CompilerTest < Test::Unit::TestCase
context "default" do
setup do
flexmock(IronRubyInline::Path).
should_receive(:tmpfile => "temp_file_name").
once
@compiler = IronRubyInline::Compiler.new
end
should "have temp file name for parameters output" do
result = @compiler.parameters.output
assert_equal "temp_file_name", result
end
end
end
| require "test_helper"
class CompilerTest < Test::Unit::TestCase
context "default" do
setup do
flexmock(IronRubyInline::Path).
should_receive(:tmpfile => "temp_file_name").
once
@compiler = IronRubyInline::Compiler.new
end
should "have temp file name for output parameter" do
result = @compiler.parameters.output
assert_equal "temp_file_name", result
end
end
context "with output specified" do
setup do
flexmock(IronRubyInline::Path).
should_receive(:tmpfile).
never
@compiler = IronRubyInline::Compiler.new("output")
end
should "have expected output parameter" do
result = @compiler.parameters.output
assert_equal "output", result
end
end
end
|
Modify to use CONSUL_SECRET_KEY on serverspec. | require 'net/http'
require 'json'
require 'base64'
require 'active_support'
require 'net/http'
require 'uri'
module ConsulParameters
def read
parameters = {}
begin
response = Net::HTTP.get URI.parse('http://localhost:8500/v1/kv/cloudconductor/parameters')
response_hash = JSON.parse(response, symbolize_names: true).first
parameters_json = Base64.decode64(response_hash[:Value])
parameters = JSON.parse(parameters_json, symbolize_names: true)
rescue => exception
p exception.message
end
parameters
end
def read_servers
begin
servers = {}
response = Net::HTTP.get URI.parse('http://localhost:8500/v1/kv/cloudconductor/servers?recurse')
JSON.parse(response, symbolize_names: true).each do |response_hash|
key = response_hash[:Key]
next if key == 'cloudconductor/servers'
hostname = key.slice(%r{cloudconductor/servers/(?<hostname>[^/]*)}, 'hostname')
server_info_json = Base64.decode64(response_hash[:Value])
servers[hostname] = JSON.parse(server_info_json, symbolize_names: true)
end
rescue
servers = {}
end
servers
end
end
| require 'net/http'
require 'json'
require 'base64'
require 'active_support'
require 'net/http'
require 'uri'
require 'cgi'
module ConsulParameters
def read
parameters = {}
begin
consul_secret_key = ENV['CONSUL_SECRET_KEY'].nil? ? '' : CGI::escape(ENV['CONSUL_SECRET_KEY'])
response = Net::HTTP.get URI.parse("http://localhost:8500/v1/kv/cloudconductor/parameters?token=#{consul_secret_key}")
response_hash = JSON.parse(response, symbolize_names: true).first
parameters_json = Base64.decode64(response_hash[:Value])
parameters = JSON.parse(parameters_json, symbolize_names: true)
rescue => exception
p exception.message
end
parameters
end
def read_servers
begin
servers = {}
consul_secret_key = ENV['CONSUL_SECRET_KEY'].nil? ? '' : CGI::escape(ENV['CONSUL_SECRET_KEY'])
response = Net::HTTP.get URI.parse("http://localhost:8500/v1/kv/cloudconductor/servers?recurse&token=#{consul_secret_key}")
JSON.parse(response, symbolize_names: true).each do |response_hash|
key = response_hash[:Key]
next if key == 'cloudconductor/servers'
hostname = key.slice(%r{cloudconductor/servers/(?<hostname>[^/]*)}, 'hostname')
server_info_json = Base64.decode64(response_hash[:Value])
servers[hostname] = JSON.parse(server_info_json, symbolize_names: true)
end
rescue
servers = {}
end
servers
end
end
|
Update author name and email address :) | # encoding: utf-8
require File.expand_path('../lib/oembed/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Alex Soulim"]
gem.email = ["soulim@gmail.com"]
gem.description = %q{A slim library to work with oEmbed format.}
gem.summary = %q{A slim library to work with oEmbed format.}
gem.homepage = "http://soulim.github.com/oembed"
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 = "oembed"
gem.require_paths = ["lib"]
gem.version = Oembed::VERSION
gem.add_development_dependency 'rspec'
gem.add_development_dependency 'simplecov'
gem.add_development_dependency 'fakeweb'
end
| # encoding: utf-8
require File.expand_path('../lib/oembed/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Alex Sulim"]
gem.email = ["hello@sul.im"]
gem.description = %q{A slim library to work with oEmbed format.}
gem.summary = %q{A slim library to work with oEmbed format.}
gem.homepage = "http://soulim.github.com/oembed"
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 = "oembed"
gem.require_paths = ["lib"]
gem.version = Oembed::VERSION
gem.add_development_dependency 'rspec'
gem.add_development_dependency 'simplecov'
gem.add_development_dependency 'fakeweb'
end
|
Include a display test for a user's events | require 'test_helper'
class UsersProfileTest < ActionDispatch::IntegrationTest
include ApplicationHelper
def setup
@user = users(:nick)
end
test "profile display" do
get user_path(@user)
assert_template 'users/show'
assert_select 'title', full_title(@user.name)
assert_select 'h1', text: @user.name
assert_select 'h1>img.gravatar'
@user.last_n_events(5).each do |event|
assert_match event.name, response.body
assert_match event.group.name, response.body
assert_match formatted_day(event.date), response.body
end
end
end
| require 'test_helper'
class UsersProfileTest < ActionDispatch::IntegrationTest
include ApplicationHelper
def setup
@user = users(:nick)
end
test "profile display" do
get user_path(@user)
assert_template 'users/show'
assert_select 'title', full_title(@user.name)
assert_select 'h1', text: @user.name
assert_select 'h1>img.gravatar'
@user.last_n_events(5).each do |event|
assert_match event.name, response.body
assert_match event.group.name, response.body
assert_match formatted_day(event.date), response.body
end
end
test "user's events display" do
log_in_as(@user)
get events_user_path(@user)
assert_template 'users/events'
@user.events.each do |event|
assert_select 'a[href=?]', event_path(event), text: event.name
assert_match event.group.name, response.body
assert_match formatted_day(event.date), response.body
assert_match event.description, response.body
end
end
end
|
Store just the name of a saved file (junk the path) | module Bkwrapper
module Backup
module Compressor
def compress_command
"zip /var/tmp/#{compressed_filename} /var/tmp/#{backup_filename}"
end
def compressed_filename
"#{backup_filename}.zip"
end
end
end
end
| module Bkwrapper
module Backup
module Compressor
def compress_command
"zip -j /var/tmp/#{compressed_filename} /var/tmp/#{backup_filename}"
end
def compressed_filename
"#{backup_filename}.zip"
end
end
end
end
|
Remove dependency on Rails' human_attribute_name (check if class responds to it) | module DiningTable
module Columns
class Column
attr_accessor :name, :table, :options, :block
def initialize( table, name, options = {}, &block)
self.table = table
self.name = name
self.options = options
self.block = block
end
def value(object)
if block
block.call(object, self)
else
object.send(name).try(:to_s) if object.respond_to?(name)
end
end
def header
@header ||= begin
label = determine_label(:header)
return label if label
object_class = table.collection.first.try(:class)
object_class.human_attribute_name( name) if object_class
end
end
def footer
@footer ||= determine_label(:footer)
end
def options_for(identifier)
options[ identifier ] || { }
end
private
def determine_label( name )
if options[ name ]
label_ = options[ name ]
label_ = label_.call if label_.respond_to?(:call)
return label_.try(:to_s)
end
end
end
end
end | module DiningTable
module Columns
class Column
attr_accessor :name, :table, :options, :block
def initialize( table, name, options = {}, &block)
self.table = table
self.name = name
self.options = options
self.block = block
end
def value(object)
if block
block.call(object, self)
else
object.send(name).try(:to_s) if object.respond_to?(name)
end
end
def header
@header ||= begin
label = determine_label(:header)
return label if label
object_class = table.collection.first.try(:class)
object_class.human_attribute_name( name ) if object_class && object_class.respond_to?( :human_attribute_name )
end
end
def footer
@footer ||= determine_label(:footer)
end
def options_for(identifier)
options[ identifier ] || { }
end
private
def determine_label( name )
if options[ name ]
label_ = options[ name ]
label_ = label_.call if label_.respond_to?(:call)
return label_.try(:to_s)
end
end
end
end
end |
Fix fingerprinting migration as it is refactored | class RegenerateErrFingerprints < Mongoid::Migration
def self.up
Err.all.each do |err|
if err.notices.any? && err.problem
err.update_attribute(
:fingerprint,
Fingerprint.generate(err.notices.first, err.app.api_key)
)
end
end
end
def self.down
end
end
| class RegenerateErrFingerprints < Mongoid::Migration
def self.up
Err.all.each do |err|
if err.notices.any? && err.problem
err.update_attribute(
:fingerprint,
Fingerprint::Sha1.generate(err.notices.first, err.app.api_key)
)
end
end
end
def self.down
end
end
|
Add date-1 spec, which is pending as RDF.rb does more xsd:date comparisons. | # coding: utf-8
#
require 'spec_helper'
# Auto-generated by build_w3c_tests.rb
#
# date-1
# Added type : xsd:date '='
# /Users/ben/repos/datagraph/tests/tests/data-r2/open-world/date-1.rq
#
# This is a W3C test from the DAWG test suite:
# http://www.w3.org/2001/sw/DataAccess/tests/r2#date-1
#
# This test is approved:
# http://lists.w3.org/Archives/Public/public-rdf-dawg/2007AprJun/att-0082/2007-06-12-dawg-minutes.html
#
describe "W3C test" do
context "open-world" do
before :all do
@data = %q{
@prefix : <http://example/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
:dt1 :r "2006-08-23T09:00:00+01:00"^^xsd:dateTime .
:d1 :r "2006-08-23"^^xsd:date .
:d2 :r "2006-08-23Z"^^xsd:date .
:d3 :r "2006-08-23+00:00"^^xsd:date .
:d4 :r "2001-01-01"^^xsd:date .
:d5 :r "2001-01-01Z"^^xsd:date .
:d6 :s "2006-08-23"^^xsd:date .
:d7 :s "2006-08-24Z"^^xsd:date .
:d8 :s "2000-01-01"^^xsd:date .
}
@query = %q{
(prefix ((xsd: <http://www.w3.org/2001/XMLSchema#>)
(: <http://example/>))
(filter (= ?v "2006-08-23"^^xsd:date)
(bgp (triple ?x :r ?v))))
}
end
example "date-1" do
graphs = {}
graphs[:default] = { :data => @data, :format => :ttl}
repository = 'open-world-date-2'
expected = [
{
:v => RDF::Literal.new('2006-08-23' , :datatype => RDF::URI('http://www.w3.org/2001/XMLSchema#date')),
:x => RDF::URI('http://example/d1'),
},
]
pending("Not Approved, and RDF.rb does object matching, not lexical matching") do
sparql_query(:graphs => graphs, :query => @query, # unordered comparison in rspec is =~
:repository => repository, :form => :select).should =~ expected
end
end
end
end
| |
Add workaround for poor query key counting in Rack 1.1.6 | # Workaround for incorrect counting of the keyspace in nested params in rack
# https://github.com/rack/rack/pull/321
# https://github.com/rack/rack/issues/318
if Rack::Utils.respond_to?("key_space_limit=")
Rack::Utils.key_space_limit = 2622144
end
| |
Add formula for the Stanford Parser | require 'formula'
class StanfordParser <Formula
url 'http://nlp.stanford.edu/software/stanford-parser-2010-02-26.tgz'
homepage 'http://nlp.stanford.edu/software/lex-parser.shtml'
md5 '25e26c79d221685956d2442592321027'
version '1.6.2'
def shim_script target_script
<<-EOS
#!/bin/bash
exec "#{libexec}/#{target_script}" $@
EOS
end
def install
libexec.install Dir['*']
Dir["#{libexec}/*.csh"].each do |f|
f = File.basename(f)
(bin+f).write shim_script(f)
end
end
def test
system "lexparser.csh", "#{libexec}/testsent.txt"
end
end
| |
Add missing logic to google_oauth2 callback | # frozen_string_literal: true
class CallbacksController < Devise::OmniauthCallbacksController
def facebook
if oauth_user.valid?
sign_in_and_redirect
else
session['devise.omniauth_data'] = oauth
redirect_to new_user_registration_path, alert: flash_message
end
end
def google_oauth2
sign_in_and_redirect
end
private
def flash_message
if oauth_user.errors.keys.include?(:email)
I18n.t('oauth.errors.email_not_provided')
else
I18n.t('oauth.errors.duplicated_username', provider: oauth['provider'])
end
end
def sign_in_and_redirect
oauth_user.save!
sign_in oauth_user
redirect_to root_url
end
def oauth_user
@oauth_user ||= OauthenticatorService.new(oauth).authenticate
end
def oauth
request.env['omniauth.auth']
end
end
| # frozen_string_literal: true
class CallbacksController < Devise::OmniauthCallbacksController
def facebook
handle_oauth_callback
end
def google_oauth2
handle_oauth_callback
end
private
def handle_oauth_callback
if oauth_user.valid?
sign_in_and_redirect
else
session['devise.omniauth_data'] = oauth
redirect_to new_user_registration_path, alert: flash_message
end
end
def flash_message
if oauth_user.errors.keys.include?(:email)
I18n.t('oauth.errors.email_not_provided')
else
I18n.t('oauth.errors.duplicated_username', provider: oauth['provider'])
end
end
def sign_in_and_redirect
oauth_user.save!
sign_in oauth_user
redirect_to root_url
end
def oauth_user
@oauth_user ||= OauthenticatorService.new(oauth).authenticate
end
def oauth
request.env['omniauth.auth']
end
end
|
Add lib directory to auto_load path | require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module AntiPlag
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
end
end
| require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module AntiPlag
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.autoload_paths << "#{Rails.root}/lib"
end
end
|
Add the rabbitmq management plugin | name "dev"
description "Development Environment for Adam"
run_list "recipe[apt]",
"recipe[motd-tail]",
"recipe[git]",
"recipe[ruby_build]",
"recipe[rbenv::user]",
"recipe[mongodb::10gen_repo]",
"recipe[adam::apt-update]",
"recipe[mongodb::default]",
"recipe[rabbitmq]",
"recipe[ejabberd]",
"recipe[adam]"
| name "dev"
description "Development Environment for Adam"
run_list "recipe[apt]",
"recipe[motd-tail]",
"recipe[git]",
"recipe[ruby_build]",
"recipe[rbenv::user]",
"recipe[mongodb::10gen_repo]",
"recipe[adam::apt-update]",
"recipe[mongodb::default]",
"recipe[rabbitmq]",
"recipe[rabbitmq::mgmt_console]",
"recipe[ejabberd]",
"recipe[adam]"
|
Add file cache for checking the content change | require 'digest'
require 'singleton'
class FileCache
include Singleton
attr_accessor :cache
def initialize
@cache = {}
end
def fetch(path)
cache[path]
end
def set(path)
cache[path] = Digest::SHA256.hexdigest(File.read(path))
end
def changed?(path)
return true unless cache.has_key?(path)
data = File.read(path)
!(cache[path] == Digest::SHA256.hexdigest(data))
end
end | |
Fix Failing Number Mask Value | module MaskableAttribute
class MaskableAttribute
attr_accessor :object, :attribute, :masks
def initialize(object, attribute, masks)
@object = object
@attribute = attribute
@masks = Masks.new masks
end
def masks
@masks.names
end
def masked
value = unmasked
if !value.blank? and value.match(/\{.*\}/)
value.scan(/(?<={)[^}]+(?=})/).each do |mask| #mask: two_digit model_series
value = value.sub "{#{mask}}", @masks[mask].unmask(@object) unless @masks[mask].unmask(@object).nil?
end
end
value
end
alias :to_s :masked
def masked_object
@object
end
def unmasked
@object.read_attribute attribute
end
def set(value)
unless value.blank?
@masks.each do |mask|
mask.accessed_by.each do |mask_accessor|
value.sub! /#{mask.unmask(@object, :formatted => mask_accessor)}(?![^{]*})/, "{#{mask_accessor}}" unless mask.unmask(@object).blank?
end
end
end
value
end
class InvalidMask < RuntimeError
attr :mask, :obj
def initialize(mask, obj)
@mask = mask
@obj = obj
end
def to_s
"Invalid mask '#{@mask}' for #{@obj.class.name}"
end
end
end
end
| module MaskableAttribute
class MaskableAttribute
attr_accessor :object, :attribute, :masks
def initialize(object, attribute, masks)
@object = object
@attribute = attribute
@masks = Masks.new masks
end
def masks
@masks.names
end
def masked
value = unmasked
if !value.blank? and value.match(/\{.*\}/)
value.scan(/(?<={)[^}]+(?=})/).each do |mask| #mask: two_digit model_series
value = value.sub "{#{mask}}", @masks[mask].unmask(@object).to_s unless @masks[mask].unmask(@object).nil?
end
end
value
end
alias :to_s :masked
def masked_object
@object
end
def unmasked
@object.read_attribute attribute
end
def set(value)
unless value.blank?
@masks.each do |mask|
mask.accessed_by.each do |mask_accessor|
value.sub! /#{mask.unmask(@object, :formatted => mask_accessor)}(?![^{]*})/, "{#{mask_accessor}}" unless mask.unmask(@object).blank?
end
end
end
value
end
class InvalidMask < RuntimeError
attr :mask, :obj
def initialize(mask, obj)
@mask = mask
@obj = obj
end
def to_s
"Invalid mask '#{@mask}' for #{@obj.class.name}"
end
end
end
end
|
Define and test deprecation behavior for a getter method | require "attr_deprecated/version"
require 'active_support'
module AttrDeprecated
module Model
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def attr_deprecated(*attr_names)
# TODO
end
end
end
end
ActiveSupport.on_load(:active_record) do
include AttrDeprecated::Model
end
| require "attr_deprecated/version"
require 'active_support'
require 'active_record'
require 'active_model'
module AttrDeprecated
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
##
# == attr_deprecated
# class macro definition to non-destructively mark an attribute as deprecated.
#
# The original method (i.e. the one marked as deprecated) is wrapped in an alias that dispatches the notification.
# (See the `around_alias` pattern. [Paolo Perotta. Metaprogramming Ruby, p. 121])
#
#
def attr_deprecated(*attr_names)
attr_names.each do |attr_name|
original_getter = "_#{attr_name}_deprecated".to_sym
#original_setter = "_#{attr_name}_deprecated=".to_sym
attr_name.to_sym
# TODO: Use alias_attribute from ActiveSupport to handle both getter and setter
alias_method(original_getter, attr_name.to_sym)
# The getter
define_method attr_name.to_sym, -> do
puts "WARNING: deprecated attribute #{original_getter} was called:"
puts Thread.current.backtrace.join("\n")
method(original_getter).call()
end
# TODO: The setter
end
end
end
end
ActiveSupport.on_load(:active_record) do
include AttrDeprecated
end
|
Raise an exception without a variable | module TestAfterCommit::DatabaseStatements
def transaction(*args)
@test_open_transactions ||= 0
super(*args) do
begin
@test_open_transactions += 1
if ActiveRecord::VERSION::MAJOR == 3
@_current_transaction_records.push([]) if @_current_transaction_records.empty?
end
result = yield
rescue Exception => e
rolled_back = true
raise e
ensure
begin
@test_open_transactions -= 1
if TestAfterCommit.enabled && @test_open_transactions == 0 && !rolled_back
test_commit_records
end
ensure
result
end
end
end
end
def test_commit_records
if ActiveRecord::VERSION::MAJOR == 3
commit_transaction_records
else
# To avoid an infinite loop, we need to copy the transaction locally, and clear out
# `records` on the copy that stays in the AR stack. Otherwise new
# transactions inside a commit callback will cause an infinite loop.
#
# This is because we're re-using the transaction on the stack, before
# it's been popped off and re-created by the AR code.
original = @transaction || @transaction_manager.current_transaction
transaction = original.dup
transaction.instance_variable_set(:@records, transaction.records.dup) # deep clone of records array
original.records.clear # so that this clear doesn't clear out both copies
transaction.commit_records
end
end
end
| module TestAfterCommit::DatabaseStatements
def transaction(*args)
@test_open_transactions ||= 0
super(*args) do
begin
@test_open_transactions += 1
if ActiveRecord::VERSION::MAJOR == 3
@_current_transaction_records.push([]) if @_current_transaction_records.empty?
end
result = yield
rescue Exception
rolled_back = true
raise
ensure
begin
@test_open_transactions -= 1
if TestAfterCommit.enabled && @test_open_transactions == 0 && !rolled_back
test_commit_records
end
ensure
result
end
end
end
end
def test_commit_records
if ActiveRecord::VERSION::MAJOR == 3
commit_transaction_records
else
# To avoid an infinite loop, we need to copy the transaction locally, and clear out
# `records` on the copy that stays in the AR stack. Otherwise new
# transactions inside a commit callback will cause an infinite loop.
#
# This is because we're re-using the transaction on the stack, before
# it's been popped off and re-created by the AR code.
original = @transaction || @transaction_manager.current_transaction
transaction = original.dup
transaction.instance_variable_set(:@records, transaction.records.dup) # deep clone of records array
original.records.clear # so that this clear doesn't clear out both copies
transaction.commit_records
end
end
end
|
Create MethodHelper for specific method formatting helper methods | module YARD
module Generators::Helpers
module MethodHelper
protected
def format_def(object)
h(object.signature.gsub(/^def\s*(?:.+?(?:\.|::)\s*)?/, ''))
end
def format_return_types(object)
typenames = "Object"
if object.has_tag?(:return)
types = object.tags(:return).map do |t|
t.types.map do |type|
type.gsub(/(^|[<>])\s*([^<>#]+)\s*(?=[<>]|$)/) {|m| $1 + linkify($2) }
end
end.flatten
typenames = types.size == 1 ? types.first : h("[#{types.join(", ")}]")
end
typenames
end
def format_block(object)
if object.has_tag?(:yieldparam)
h "{|" + object.tags(:yieldparam).map {|t| t.name }.join(", ") + "| ... }"
else
""
end
end
def format_meth_name(object)
(object.scope == :instance ? '#' : '') + h(object.name.to_s)
end
end
end
end | |
Use ActiveSupport.on_load hook instead of eagerly loading external dependencies | require 'redshift_cursor/version'
require 'redshift_cursor/active_record/connection_adapters/redshift_type_map'
require 'postgresql_cursor'
require 'active_record'
require 'active_record/connection_adapters/redshift_adapter'
ActiveRecord::ConnectionAdapters::RedshiftAdapter.send(:include, RedshiftCursor::ActiveRecord::ConnectionAdapters::RedshiftTypeMap)
| require 'redshift_cursor/version'
require 'active_support'
ActiveSupport.on_load :active_record do
require 'redshift_cursor/active_record/connection_adapters/redshift_type_map'
require 'postgresql_cursor'
require 'active_record/connection_adapters/redshift_adapter'
ActiveRecord::ConnectionAdapters::RedshiftAdapter.send(:include, RedshiftCursor::ActiveRecord::ConnectionAdapters::RedshiftTypeMap)
end
|
Delete old Api class from root file as its been replaced by the new Client class. Researching other popular gems this file seems to be empty as a standard perhaps? Best practice? | require 'net/https'
require 'xmlsimple'
require 'csv'
require 'active_support'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/keys'
require 'salesforce_bulk/version'
require 'salesforce_bulk/core_extensions/string'
require 'salesforce_bulk/salesforce_error'
require 'salesforce_bulk/client'
require 'salesforce_bulk/job'
require 'salesforce_bulk/batch'
require 'salesforce_bulk/batch_result'
require 'salesforce_bulk/batch_result_collection'
require 'salesforce_bulk/query_result_collection'
require 'salesforce_bulk/connection'
module SalesforceBulk
# Your code goes here...
class Api
@@SALESFORCE_API_VERSION = '23.0'
def initialize(username, password)
@connection = SalesforceBulk::Connection.new(username, password, @@SALESFORCE_API_VERSION)
end
def upsert(sobject, records, external_field)
self.do_operation('upsert', sobject, records, external_field)
end
def update(sobject, records)
self.do_operation('update', sobject, records, nil)
end
def create(sobject, records)
self.do_operation('insert', sobject, records, nil)
end
def delete(sobject, records)
self.do_operation('delete', sobject, records, nil)
end
def query(sobject, query)
self.do_operation('query', sobject, query, nil)
end
#private
def do_operation(operation, sobject, records, external_field)
job = SalesforceBulk::Job.new(operation, sobject, records, external_field, @connection)
# TODO: put this in one function
job_id = job.create_job()
if(operation == "query")
batch_id = job.add_query()
else
batch_id = job.add_batch()
end
job.close_job()
while true
state = job.check_batch_status()
#puts "\nstate is #{state}\n"
if state != "Queued" && state != "InProgress"
break
end
sleep(2) # wait x seconds and check again
end
if state == 'Completed'
job.get_batch_result()
else
return "error"
end
end
end # End class
end
| require 'net/https'
require 'xmlsimple'
require 'csv'
require 'active_support'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/keys'
require 'salesforce_bulk/version'
require 'salesforce_bulk/core_extensions/string'
require 'salesforce_bulk/salesforce_error'
require 'salesforce_bulk/client'
require 'salesforce_bulk/job'
require 'salesforce_bulk/batch'
require 'salesforce_bulk/batch_result'
require 'salesforce_bulk/batch_result_collection'
require 'salesforce_bulk/query_result_collection' |
Remove initializer that loads refinery tests into rspec runlist | require 'refinerycms-core'
require 'rspec-rails'
require 'refinery/generators/testing_generator'
module Refinery
module Testing
autoload :ControllerMacros, 'refinery/testing/controller_macros'
autoload :RequestMacros, 'refinery/testing/request_macros'
class << self
attr_accessor :root
def root
@root ||= Pathname.new(File.expand_path('../../', __FILE__))
end
end
class Engine < ::Rails::Engine
isolate_namespace ::Refinery
config.before_configuration do
::Refinery::Application.module_eval do
def load_tasks
super
# To get specs from all Refinery engines, not just those in Rails.root/spec/
::RSpec::Core::RakeTask.module_eval do
def pattern
[@pattern] | ::Refinery::Plugins.registered.pathnames.map{|p|
p.join('spec', '**', '*_spec.rb').to_s
}
end
end if defined?(::RSpec::Core::RakeTask)
end
end
end
config.after_initialize do
::Refinery::Plugin.register do |plugin|
plugin.pathname = root
plugin.name = 'refinerycms_testing_plugin'
plugin.version = ::Refinery.version
plugin.hide_from_menu = true
end
end
end
end
end
::Refinery.engines << 'testing'
| require 'refinerycms-core'
require 'refinery/generators/testing_generator'
module Refinery
module Testing
autoload :ControllerMacros, 'refinery/testing/controller_macros'
autoload :RequestMacros, 'refinery/testing/request_macros'
class << self
attr_accessor :root
def root
@root ||= Pathname.new(File.expand_path('../../', __FILE__))
end
end
class Engine < ::Rails::Engine
isolate_namespace ::Refinery
config.after_initialize do
::Refinery::Plugin.register do |plugin|
plugin.pathname = root
plugin.name = 'refinerycms_testing_plugin'
plugin.version = ::Refinery.version
plugin.hide_from_menu = true
end
end
end
end
end
::Refinery.engines << 'testing'
|
Use 'required: true' on url attribute | require 'itamae'
require 'open-uri'
module Itamae
module Resource
class HttpRequest < File
UrlNotFoundError = Class.new(StandardError)
define_attribute :headers, type: Hash, default: {}
define_attribute :url, type: String
def pre_action
unless attributes.url
raise UrlNotFoundError, "url is not found"
end
attributes.content = open(attributes.url, attributes.headers).read
super
end
private
def content_file
nil
end
end
end
end
| require 'itamae'
require 'open-uri'
module Itamae
module Resource
class HttpRequest < File
UrlNotFoundError = Class.new(StandardError)
define_attribute :headers, type: Hash, default: {}
define_attribute :url, type: String, required: true
def pre_action
attributes.content = open(attributes.url, attributes.headers).read
super
end
private
def content_file
nil
end
end
end
end
|
Add spec test for workers <=> systemd units | RSpec.describe MiqWorker::SystemdCommon do
describe ".service_base_name" do
before { MiqWorkerType.seed }
it "every worker has a matching systemd target and service file" do
all_systemd_units = (Vmdb::Plugins.systemd_units + Rails.root.join("systemd").glob("*.*")).map(&:basename).map(&:to_s)
all_systemd_units.delete("manageiq.target")
MiqWorkerType.worker_class_names.each do |klass_name|
klass = klass_name.constantize
service_base_name = klass.service_base_name
service_file = "#{service_base_name}@.service"
target_file = "#{service_base_name}.target"
expect(all_systemd_units).to include(service_file)
expect(all_systemd_units).to include(target_file)
all_systemd_units -= [service_file, target_file]
end
expect(all_systemd_units).to be_empty
end
end
end
| |
Make sure a few required assets are explicitly listed on the asset pipeline. This removes the runtime error that asks the developer to manually add them when running the application for the very first time. | require "sufia/version"
require 'blacklight'
require 'blacklight_advanced_search'
require 'blacklight/gallery'
require 'hydra/head'
require 'hydra-batch-edit'
require 'hydra-editor'
require 'browse-everything'
require 'sufia/models'
require 'rails_autolink'
require 'font-awesome-rails'
require 'tinymce-rails'
require 'tinymce-rails-imageupload'
module Sufia
extend ActiveSupport::Autoload
class Engine < ::Rails::Engine
engine_name 'sufia'
# Breadcrumbs on rails must be required outside of an initializer or it doesn't get loaded.
require 'breadcrumbs_on_rails'
config.autoload_paths += %W(
#{config.root}/app/controllers/concerns
#{config.root}/app/models/concerns
#{config.root}/app/models/datastreams
#{Hydra::Engine.root}/app/models/concerns
)
config.assets.paths << config.root.join('vendor', 'assets', 'fonts')
config.assets.precompile << %r(vjs\.(?:eot|ttf|woff)$)
end
end
| require "sufia/version"
require 'blacklight'
require 'blacklight_advanced_search'
require 'blacklight/gallery'
require 'hydra/head'
require 'hydra-batch-edit'
require 'hydra-editor'
require 'browse-everything'
require 'sufia/models'
require 'rails_autolink'
require 'font-awesome-rails'
require 'tinymce-rails'
require 'tinymce-rails-imageupload'
module Sufia
extend ActiveSupport::Autoload
class Engine < ::Rails::Engine
engine_name 'sufia'
# Breadcrumbs on rails must be required outside of an initializer or it doesn't get loaded.
require 'breadcrumbs_on_rails'
config.autoload_paths += %W(
#{config.root}/app/controllers/concerns
#{config.root}/app/models/concerns
#{config.root}/app/models/datastreams
#{Hydra::Engine.root}/app/models/concerns
)
config.assets.paths << config.root.join('vendor', 'assets', 'fonts')
config.assets.precompile << %r(vjs\.(?:eot|ttf|woff)$)
config.assets.precompile += %w( fontawesome-webfont.woff )
config.assets.precompile += %w( fontawesome-webfont.ttf )
config.assets.precompile += %w( fontawesome-webfont.svg )
config.assets.precompile += %w( ZeroClipboard.swf )
end
end
|
Support for different AWS regions. | require 'aws-sdk'
require 'net/dns'
Capistrano::Configuration.instance(:must_exist).load do
def elastic_load_balancer(name, *args)
packet = Net::DNS::Resolver.start(name)
all_cnames= packet.answer.reject { |p| !p.instance_of? Net::DNS::RR::CNAME }
cname = all_cnames.find { |c| c.name == "#{name}."}.cname[0..-2]
elb = AWS::ELB.new(:access_key_id => fetch(:aws_access_key_id),
:secret_access_key => fetch(:aws_secret_access_key))
load_balancer = elb.load_balancers.find { |elb| elb.dns_name == cname }
raise "EC2 Load Balancer not found for #{name}" if load_balancer.nil?
load_balancer.instances.each do |instance|
hostname = instance.dns_name
server(hostname, *args)
end
end
end
| require 'aws-sdk'
require 'net/dns'
Capistrano::Configuration.instance(:must_exist).load do
def elastic_load_balancer(name, *args)
packet = Net::DNS::Resolver.start(name)
all_cnames= packet.answer.reject { |p| !p.instance_of? Net::DNS::RR::CNAME }
cname = all_cnames.find { |c| c.name == "#{name}."}.cname[0..-2]
aws_region= fetch(:aws_region, 'us-east-1')
AWS.config(:access_key_id => fetch(:aws_access_key_id),
:secret_access_key => fetch(:aws_secret_access_key),
:ec2_endpoint => "ec2.#{aws_region}.amazonaws.com",
:elb_endpoint => "elasticloadbalancing.#{aws_region}.amazonaws.com")
load_balancer = AWS::ELB.new.load_balancers.find { |elb| elb.dns_name.downcase == cname.downcase }
raise "EC2 Load Balancer not found for #{name} in region #{aws_region}" if load_balancer.nil?
load_balancer.instances.each do |instance|
hostname = instance.dns_name
server(hostname, *args)
end
end
end
|
Configure Oj to use strict mode | begin
require 'oj'
rescue LoadError
require 'symbolizer'
require 'json'
end
class Freddy
class Payload
def self.parse(payload)
return {} if payload == 'null'
json_handler.parse(payload)
end
def self.dump(payload)
json_handler.dump(payload)
end
def self.json_handler
@_json_handler ||= defined?(Oj) ? OjAdapter : JsonAdapter
end
class OjAdapter
def self.parse(payload)
Oj.load(payload, symbol_keys: true)
end
def self.dump(payload)
Oj.dump(payload, mode: :compat)
end
end
class JsonAdapter
def self.parse(payload)
# MRI has :symbolize_keys, but JRuby does not. Not adding it at the
# moment.
Symbolizer.symbolize(JSON.parse(payload))
end
def self.dump(payload)
JSON.dump(payload)
end
end
end
end
| begin
require 'oj'
rescue LoadError
require 'symbolizer'
require 'json'
end
class Freddy
class Payload
def self.parse(payload)
return {} if payload == 'null'
json_handler.parse(payload)
end
def self.dump(payload)
json_handler.dump(payload)
end
def self.json_handler
@_json_handler ||= defined?(Oj) ? OjAdapter : JsonAdapter
end
class OjAdapter
def self.parse(payload)
Oj.strict_load(payload, symbol_keys: true)
end
def self.dump(payload)
Oj.dump(payload, mode: :compat)
end
end
class JsonAdapter
def self.parse(payload)
# MRI has :symbolize_keys, but JRuby does not. Not adding it at the
# moment.
Symbolizer.symbolize(JSON.parse(payload))
end
def self.dump(payload)
JSON.dump(payload)
end
end
end
end
|
Change up the description for the gemspec | $:.push File.expand_path("../lib", __FILE__)
require "utensils/version"
Gem::Specification.new do |s|
s.name = "utensils"
s.version = Utensils::VERSION
s.authors = ["Matt Kitt"]
s.email = ["info@modeset.com"]
s.homepage = "https://github.com/modeset/utensils"
s.summary = "A UI component library"
s.description = "A UI component library"
s.files = Dir["{app,config,lib,vendor}/**/*"] + ["MIT-LICENSE", "README.md"]
s.test_files = Dir["spec/**/*"]
s.add_dependency "railties", ">= 3.2.5"
s.add_dependency "sass-rails"
s.add_dependency "coffee-rails"
s.add_development_dependency 'teabag', '>= 0.4.6'
# Used by the dummy application
s.add_development_dependency 'docomo'
s.add_development_dependency 'rails', '>= 3.2.5'
end
| $:.push File.expand_path("../lib", __FILE__)
require "utensils/version"
Gem::Specification.new do |s|
s.name = "utensils"
s.version = Utensils::VERSION
s.authors = ["Mode Set"]
s.email = ["info@modeset.com"]
s.homepage = "https://github.com/modeset/utensils"
s.summary = "Client side component library, tuned to work with the asset pipeline."
s.description = "Client side component library, tuned to work with the asset pipeline."
s.files = Dir["{app,config,lib,vendor}/**/*"] + ["MIT-LICENSE", "README.md"]
s.test_files = Dir["spec/**/*"]
s.add_dependency "railties", ">= 3.2.5"
s.add_dependency "sass-rails"
s.add_dependency "coffee-rails"
s.add_development_dependency 'teabag', '>= 0.4.6'
# Used by the dummy application
s.add_development_dependency 'docomo'
s.add_development_dependency 'rails', '>= 3.2.5'
end
|
Set the correct layout for the email and set the correct globals | class ActivityMailer < ActionMailer::Base
include Resque::Mailer
default from: "Factlink <support@factlink.com>"
def new_activity(user, activity)
mail to: user.email, subject: 'New notification!'
end
end
| class ActivityMailer < ActionMailer::Base
include Resque::Mailer
layout "email"
default from: "Factlink <support@factlink.com>"
def new_activity(user, activity)
@user = user
@activity = activity
mail to: user.email, subject: 'New notification!'
end
end
|
Correct path for edit form | class ItemsController < ApplicationController
def index
@items = Item.all
render 'homepage_admin/index'
end
def show
@item = Item.find(params[:id])
render 'items/item'
end
def new
@item = Item.new
render 'items/_new'
end
def create
# p params["item"]
# p "*" * 100
@item = Item.new(item_params)
if @item.save
flash[:notice] = "Item created."
render '/homepage_admin/index'
else
render 'items/_new'
end
end
def edit
@item = Item.find(params[:id])
render 'items/_edit'
end
def update
@item = Item.find(params[:id])
if @item.update(item_params)
flash[:notice] = "Item updated."
redirect_to '/homepage_admin/index'
else
render '/items/_form'
end
end
def destroy
@item = Item.find(params[:id])
@item.destroy
redirect_to items_path
end
private
def item_params
params.require(:item).permit(:name, :description, :price)
end
end
| class ItemsController < ApplicationController
def index
@items = Item.all
render 'homepage_admin/index'
end
def show
@item = Item.find(params[:id])
render 'items/item'
end
def new
@item = Item.new
render 'items/_new'
end
def create
# p params["item"]
# p "*" * 100
@item = Item.new(item_params)
if @item.save
flash[:notice] = "Item created."
render '/homepage_admin/index'
else
render 'items/_new'
end
end
def edit
@item = Item.find(params[:id])
render 'items/_edit'
end
def update
@item = Item.find(params[:id])
if @item.update(item_params)
flash[:notice] = "Item updated."
redirect_to '/homepage_admin/index'
else
render '/items/_edit'
end
end
def destroy
@item = Item.find(params[:id])
@item.destroy
redirect_to items_path
end
private
def item_params
params.require(:item).permit(:name, :description, :price)
end
end
|
Fix bug from merging in upstream | # A controller to handle incoming webhook events
require "openssl"
class EventsController < ApplicationController
include WebhookValidations
before_filter :verify_incoming_webhook_address!
skip_before_filter :verify_authenticity_token, :only => [:create]
def create
event = request.headers["HTTP_X_GITHUB_EVENT"]
delivery = request.headers["HTTP_X_GITHUB_DELIVERY"]
if valid_events.include?(event)
request.body.rewind
if verify_signature(data)
Resque.enqueue(Receiver, event, delivery, event_params)
render :json => {}, :status => :created
else
render :json => {}, :status => :unauthorized
end
else
render :json => {}, :status => :unprocessable_entity
end
end
def valid_events
%w{deployment deployment_status status ping}
end
private
def verify_signature(data)
signature = 'sha1=' + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha1'), ENV['SECRET_TOKEN'], data)
Rack::Utils.secure_compare(signature, request.headers['HTTP_X_HUB_SIGNATURE'])
end
def event_params
params.permit!
end
end
| # A controller to handle incoming webhook events
require "openssl"
class EventsController < ApplicationController
include WebhookValidations
before_filter :verify_incoming_webhook_address!
skip_before_filter :verify_authenticity_token, :only => [:create]
def create
event = request.headers["HTTP_X_GITHUB_EVENT"]
delivery = request.headers["HTTP_X_GITHUB_DELIVERY"]
if valid_events.include?(event)
request.body.rewind
data = request.body.read
if verify_signature(data)
Resque.enqueue(Receiver, event, delivery, event_params)
render :json => {}, :status => :created
else
render :json => {}, :status => :unauthorized
end
else
render :json => {}, :status => :unprocessable_entity
end
end
def valid_events
%w{deployment deployment_status status ping}
end
private
def verify_signature(data)
signature = 'sha1=' + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha1'), ENV['SECRET_TOKEN'], data)
Rack::Utils.secure_compare(signature, request.headers['HTTP_X_HUB_SIGNATURE'])
end
def event_params
params.permit!
end
end
|
Use the registry resource instead of execute | execute 'Enable RDP' do
command 'reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f'
end
execute 'Enable RDP firewall rule' do
command 'netsh advfirewall firewall set rule group="Remote Desktop" new enable=Yes'
end
| registry_key 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server' do
values [{
name: 'fDenyTSConnections',
type: :dword,
data: 0, }]
end
execute 'Enable RDP firewall rule' do
command 'netsh advfirewall firewall set rule group="Remote Desktop" new enable=Yes'
end
|
Simplify filtering items with zero price | # frozen_string_literal: true
class PaypalItemsBuilder
def initialize(order)
@order = order
end
def call
items = order.line_items.map(&method(:line_item_data))
relevant_adjustments.each do |adjustment|
items << adjustment_data(adjustment)
end
# Because PayPal doesn't accept $0 items at all.
# See https://github.com/spree-contrib/better_spree_paypal_express/issues/10
# "It can be a positive or negative value but not zero."
items.reject! do |item|
item[:Amount][:value].zero?
end
items
end
private
attr_reader :order
def relevant_adjustments
# Tax total and shipping costs are added separately, so they're not included here.
order.all_adjustments.eligible - order.all_adjustments.tax - order.all_adjustments.shipping
end
def line_item_data(item)
{
Name: item.product.name,
Number: item.variant.sku,
Quantity: item.quantity,
Amount: {
currencyID: item.order.currency,
value: item.price
},
ItemCategory: "Physical"
}
end
def adjustment_data(adjustment)
{
Name: adjustment.label,
Quantity: 1,
Amount: {
currencyID: order.currency,
value: adjustment.amount
}
}
end
end
| # frozen_string_literal: true
class PaypalItemsBuilder
def initialize(order)
@order = order
end
def call
items = order.line_items.map(&method(:line_item_data))
relevant_adjustments.each do |adjustment|
items << adjustment_data(adjustment)
end
# Because PayPal doesn't accept $0 items at all.
# See https://github.com/spree-contrib/better_spree_paypal_express/issues/10
# "It can be a positive or negative value but not zero."
items.reject do |item|
item[:Amount][:value].zero?
end
end
private
attr_reader :order
def relevant_adjustments
# Tax total and shipping costs are added separately, so they're not included here.
order.all_adjustments.eligible - order.all_adjustments.tax - order.all_adjustments.shipping
end
def line_item_data(item)
{
Name: item.product.name,
Number: item.variant.sku,
Quantity: item.quantity,
Amount: {
currencyID: item.order.currency,
value: item.price
},
ItemCategory: "Physical"
}
end
def adjustment_data(adjustment)
{
Name: adjustment.label,
Quantity: 1,
Amount: {
currencyID: order.currency,
value: adjustment.amount
}
}
end
end
|
Update Razer Synapse to 1.46 | cask 'razer-synapse' do
version '1.45'
sha256 '4b4368bf5f90cb94667a60a120d49b9073329ba6d9efcd4f5108cf709bfe8115'
# amazonaws.com is the official download host per the vendor homepage
url "https://razerdrivers.s3.amazonaws.com/drivers/Synapse2/mac/Razer_Synapse_Mac_Driver_v#{version}.dmg"
name 'Razer Synapse'
homepage 'https://www.razerzone.com/synapse/'
license :gratis
depends_on :macos => '>= :lion'
pkg 'Razer Synapse.pkg'
uninstall :script => '/Applications/Utilities/Uninstall Razer Synapse.app/Contents/MacOS/Uninstall Razer Synapse',
:pkgutil => 'com.razerzone.*',
:quit => [
'com.razerzone.RzUpdater',
'com.razerzone.rzdeviceengine',
],
:launchctl => [
'com.razer.rzupdater',
'com.razerzone.rzdeviceengine',
]
zap :delete => [
'~/Library/Preferenecs/com.razer.*',
'~/Library/Preferenecs/com.razerzone.*',
]
caveats do
reboot
end
end
| cask 'razer-synapse' do
version '1.46'
sha256 'eeb264dc25678eb83532267003f1e00c38397332309c8a0b0569d91deda03253'
# amazonaws.com is the official download host per the vendor homepage
url "https://razerdrivers.s3.amazonaws.com/drivers/Synapse2/mac/Razer_Synapse_Mac_Driver_v#{version}.dmg"
name 'Razer Synapse'
homepage 'https://www.razerzone.com/synapse/'
license :gratis
depends_on :macos => '>= :lion'
pkg 'Razer Synapse.pkg'
uninstall :script => '/Applications/Utilities/Uninstall Razer Synapse.app/Contents/MacOS/Uninstall Razer Synapse',
:pkgutil => 'com.razerzone.*',
:quit => [
'com.razerzone.RzUpdater',
'com.razerzone.rzdeviceengine',
],
:launchctl => [
'com.razer.rzupdater',
'com.razerzone.rzdeviceengine',
]
zap :delete => [
'~/Library/Preferenecs/com.razer.*',
'~/Library/Preferenecs/com.razerzone.*',
]
caveats do
reboot
end
end
|
Add miq_provision_quota mixin to Service Template Provision Request Service model. | module MiqAeMethodService
class MiqAeServiceServiceTemplateProvisionRequest < MiqAeServiceMiqRequest
def ci_type
'service'
end
end
end
| module MiqAeMethodService
class MiqAeServiceServiceTemplateProvisionRequest < MiqAeServiceMiqRequest
require_relative "mixins/miq_ae_service_miq_provision_mixin"
include MiqAeServiceMiqProvisionMixin
def ci_type
'service'
end
end
end
|
Send email after export job | class ExportJob < ApplicationJob
def perform(export_id)
export = Export.find(export_id)
exporter = case export.export_type
when "results"
Exporters::ResultsExporter.new
end
return unless exporter
headers = exporter.headers
data = exporter.rows
s = SpreadsheetCreator.new.create(headers, data)
report = StringIO.new
s.write report
temp_file = Tempfile.new("results", Rails.root.join('tmp'), encoding: "binary").tap do |f|
f.write(report.read)
f.close
end
export.file = temp_file
export.save!
ExportCompleteMailer.send_export(export.id, "Results")
end
end
| class ExportJob < ApplicationJob
def perform(export_id)
export = Export.find(export_id)
exporter = case export.export_type
when "results"
Exporters::ResultsExporter.new
end
return unless exporter
headers = exporter.headers
data = exporter.rows
s = SpreadsheetCreator.new.create(headers, data)
report = StringIO.new
s.write report
temp_file = Tempfile.new("results", Rails.root.join('tmp'), encoding: "binary").tap do |f|
f.write(report.read)
f.close
end
export.file = temp_file
export.save!
ExportCompleteMailer.send_export(export.id, "Results").deliver_later
end
end
|
Remove the some BlockchainInfo adapter related code from HelloblockIo adapter | module StraightEngine
module BlockchainAdapter
class HelloblockIo < Base
# When we call calculate_confirmations, it doesn't always make a new
# request to the blockchain API. Instead, it checks if cached_id matches the one in
# the hash. It's useful when we want to calculate confirmations for all transactions for
# a certain address without making any new requests to the Blockchain API.
@@latest_block = { cache_timestamp: nil, block: nil }
API_BASE_URL = "https://mainnet.helloblock.io/v1"
class << self
# Returns transaction info for the tid
def fetch_transaction(tid)
straighten_transaction JSON.parse(http_request("#{API_BASE_URL}/transactions/#{tid}"))['data']['transaction']
end
# Returns all transactions for the address
def fetch_transactions_for(address)
address = JSON.parse(http_request("#{API_BASE_URL}/addresses/#{address}/transactions"))['data']
transactions = address['transactions']
transactions.map { |t| straighten_transaction(t) }
end
# Returns the current balance of the address
def fetch_balance_for(address)
JSON.parse(http_request("#{API_BASE_URL}/addresses/#{address}"))['data']['address']['balance']
end
private
# Converts transaction info received from the source into the
# unified format expected by users of BlockchainAdapter instances.
def straighten_transaction(transaction)
outs = transaction['outputs'].map do |out|
{ amount: out['value'], receiving_address: out['address'] }
end
{
total_amount: transaction['totalOutputsValue'],
confirmations: transaction['confirmations'],
outs: outs
}
end
end
end
end
end
| module StraightEngine
module BlockchainAdapter
class HelloblockIo < Base
API_BASE_URL = "https://mainnet.helloblock.io/v1"
class << self
# Returns transaction info for the tid
def fetch_transaction(tid)
straighten_transaction JSON.parse(http_request("#{API_BASE_URL}/transactions/#{tid}"))['data']['transaction']
end
# Returns all transactions for the address
def fetch_transactions_for(address)
address = JSON.parse(http_request("#{API_BASE_URL}/addresses/#{address}/transactions"))['data']
transactions = address['transactions']
transactions.map { |t| straighten_transaction(t) }
end
# Returns the current balance of the address
def fetch_balance_for(address)
JSON.parse(http_request("#{API_BASE_URL}/addresses/#{address}"))['data']['address']['balance']
end
private
# Converts transaction info received from the source into the
# unified format expected by users of BlockchainAdapter instances.
def straighten_transaction(transaction)
outs = transaction['outputs'].map do |out|
{ amount: out['value'], receiving_address: out['address'] }
end
{
total_amount: transaction['totalOutputsValue'],
confirmations: transaction['confirmations'],
outs: outs
}
end
end
end
end
end
|
Add search class method for Question. | class Question < ActiveRecord::Base
belongs_to :user
has_many :answers
validates_presence_of :body
validates_presence_of :title
end | class Question < ActiveRecord::Base
belongs_to :user
has_many :answers
validates_presence_of :body
validates_presence_of :title
def self.search(words)
matches = []
words.split(' ').each do |word|
matches << Question.all.map { |q| q.title.include?(word) || q.body.include?(word) }
end
matches
end
end |
Move the benchmark line down. | # ----------------------------------------------------------------------------
# Frozen-string-literal: true
# Copyright: 2015-2016 Jordon Bedwell - MIT License
# Encoding: utf-8
# ----------------------------------------------------------------------------
require "bundler/setup"
require "safe_yaml/load"
require "benchmark/ips"
require "pathutil"
data = "hello: world\nworld: hello"
Benchmark.ips :quiet => true do |x|
x.json! "benchmark.json"
x.report("B:Pathutil.parse_yaml") { Pathutil.parse_yaml(data) }
x.report("A:SafeYAML.load") { SafeYAML.load(data) }
x.compare!
end
| # ----------------------------------------------------------------------------
# Frozen-string-literal: true
# Copyright: 2015-2016 Jordon Bedwell - MIT License
# Encoding: utf-8
# ----------------------------------------------------------------------------
require "bundler/setup"
require "safe_yaml/load"
require "benchmark/ips"
require "pathutil"
data = "hello: world\nworld: hello"
Benchmark.ips :quiet => true do |x|
x.json! "benchmark.json"
x.report("A:SafeYAML.load") { SafeYAML.load(data) }
x.report("B:Pathutil::Helpers.parse_yaml") { Pathutil.parse_yaml(data) }
x.compare!
end
|
Add test for attachment_url method | require 'test_helper'
#
# == AssetsHelper Test
#
class AssetsHelperTest < ActionView::TestCase
include AssetsHelper
# TODO: fix this broken test with paperclip-dropbox
# test 'should return full path for attachment' do
# @subscriber = users(:lana)
# result = attachment_url(@subscriber.avatar, :small, ActionController::TestRequest.new)
# expected = "http://test.host/avatar/#{@lana.id}/small-bart.jpg"
# assert_equal result, expected
# end
test 'should return default image if attachment is not defined' do
@administrator = users(:bob)
result = attachment_url(@administrator.avatar, :small, ActionController::TestRequest.new)
expected = 'http://test.host/default/small-missing.png'
assert_equal result, expected
end
test 'should return nil if attachment is nil' do
assert_nil attachment_url(nil, :small, ActionController::TestRequest.new)
end
end
| require 'test_helper'
#
# == AssetsHelper Test
#
class AssetsHelperTest < ActionView::TestCase
include AssetsHelper
test 'should return full path for attachment' do
@subscriber = users(:lana)
result = attachment_url(@subscriber.avatar, :small, ActionController::TestRequest.new)
expected = "http://test.host/system/test/users/#{@subscriber.id}/small-bart.jpg"
assert_equal expected, result
end
test 'should return default image if attachment is not defined' do
@administrator = users(:bob)
result = attachment_url(@administrator.avatar, :small, ActionController::TestRequest.new)
expected = 'http://test.host/default/small-missing.png'
assert_equal expected, result
end
test 'should return nil if attachment is nil' do
assert_nil attachment_url(nil, :small, ActionController::TestRequest.new)
end
end
|
Package version is increased from 0.0.1.0 to 0.0.1.1 | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'data_aggregation-accumulator'
s.version = '0.0.1.0'
s.summary = 'Data aggregation accumulator library'
s.description = ' '
s.authors = ['Obsidian Software, Inc']
s.email = 'developers@obsidianexchange.com'
s.homepage = 'https://github.com/obsidian-btc/data-aggregation-accumulator'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.bindir = 'bin'
s.add_runtime_dependency 'entity_cache', '~> 0.6.0'
s.add_runtime_dependency 'event_store-entity_projection'
s.add_runtime_dependency 'event_store-consumer'
s.add_development_dependency 'fixtures-expect_message'
end
| # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'data_aggregation-accumulator'
s.version = '0.0.1.1'
s.summary = 'Data aggregation accumulator library'
s.description = ' '
s.authors = ['Obsidian Software, Inc']
s.email = 'developers@obsidianexchange.com'
s.homepage = 'https://github.com/obsidian-btc/data-aggregation-accumulator'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.bindir = 'bin'
s.add_runtime_dependency 'entity_cache', '~> 0.6.0'
s.add_runtime_dependency 'event_store-entity_projection'
s.add_runtime_dependency 'event_store-consumer'
s.add_development_dependency 'fixtures-expect_message'
end
|
Change constant name and call score in self.score | class Scrabble
attr_reader :word
def initialize(word)
@word = word&.downcase
end
def score
return 0 if word_invalid
points = 0
word.each_char do |char|
points += CHAR_POINTS[char]
end
points
end
def self.score(word)
points = 0
word.each_char do |char|
points += CHAR_POINTS[char]
end
points
end
def word_invalid
word.nil? || word == '' || word == " \t\n"
end
CHAR_POINTS = {
'a' => 1,
'b' => 3,
'c' => 3,
'd' => 2,
'e' => 1,
'f' => 4,
'g' => 2,
'h' => 4,
'i' => 1,
'j' => 8,
'k' => 5,
'l' => 1,
'm' => 3,
'n' => 1,
'o' => 1,
'p' => 3,
'q' => 10,
'r' => 1,
's' => 1,
't' => 1,
'u' => 1,
'v' => 4,
'w' => 4,
'x' => 8,
'y' => 4,
'z' => 10
}
end
| class Scrabble
attr_reader :word
def initialize(word)
@word = word&.downcase
end
def score
return 0 if word_invalid
points = 0
word.each_char do |char|
points += TILE_POINTS[char]
end
points
end
def self.score(word)
new(word).score
end
def word_invalid
word.nil? || word == '' || word == " \t\n"
end
TILE_POINTS = {
'a' => 1,
'b' => 3,
'c' => 3,
'd' => 2,
'e' => 1,
'f' => 4,
'g' => 2,
'h' => 4,
'i' => 1,
'j' => 8,
'k' => 5,
'l' => 1,
'm' => 3,
'n' => 1,
'o' => 1,
'p' => 3,
'q' => 10,
'r' => 1,
's' => 1,
't' => 1,
'u' => 1,
'v' => 4,
'w' => 4,
'x' => 8,
'y' => 4,
'z' => 10
}
end
|
Add browser test for course deletion | # frozen_string_literal: true
require 'rails_helper'
describe 'course deletion', type: :feature, js: true do
let(:course) { create(:course) }
let(:admin) { create(:admin) }
it 'destroys the course and redirects to the home page' do
login_as admin
stub_oauth_edit
visit "/courses/#{course.slug}"
expect(Course.count).to eq(1)
accept_prompt(with: course.title) do
click_button 'Delete course'
end
expect(page).to have_content 'Create Course'
expect(Course.count).to eq(0)
end
end
| |
Add development dependency on debugger | # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'has_publishing/version'
Gem::Specification.new do |gem|
gem.name = "has_publishing"
gem.version = HasPublishing::VERSION
gem.authors = ["Josh McArthur @ 3months"]
gem.email = ["joshua.mcarthur@gmail.com"]
gem.description = %q{Add ability to publish/embargo models}
gem.summary = %q{Add publishing to your ActiveRecord models}
gem.homepage = ""
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_dependency "activerecord"
gem.add_dependency "activesupport"
gem.add_development_dependency "rspec-rails"
gem.add_development_dependency "sqlite3"
end
| # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'has_publishing/version'
Gem::Specification.new do |gem|
gem.name = "has_publishing"
gem.version = HasPublishing::VERSION
gem.authors = ["Josh McArthur @ 3months"]
gem.email = ["joshua.mcarthur@gmail.com"]
gem.description = %q{Add ability to publish/embargo models}
gem.summary = %q{Add publishing to your ActiveRecord models}
gem.homepage = ""
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_dependency "activerecord"
gem.add_dependency "activesupport"
gem.add_development_dependency "debugger"
gem.add_development_dependency "rspec-rails"
gem.add_development_dependency "sqlite3"
end
|
Create Ui class inorder to remove dependency on stdin and stdout | require_relative 'console'
class Ui
attr_reader :io
def initialize(io)
@io = io
end
def display_intro_msg(game_being_played)
io.display_intro_msg(game_being_played)
end
def show_board(board)
io.show_board(board)
end
def get_user_input
io.get_user_input
end
end
| |
Fix migration path for PostgreSQL compatbility | class AddUniquenessIndexToPeople < ActiveRecord::Migration
def self.up
remove_index :people, [:user_id, :project_id]
Person.connection.execute <<-EOF
DELETE #{Person.table_name}
FROM #{Person.table_name}
LEFT OUTER JOIN (
SELECT MIN(id) as id, user_id, project_id
FROM #{Person.table_name}
GROUP BY user_id, project_id) as KeepRows ON
#{Person.table_name}.id = KeepRows.id
WHERE
KeepRows.id IS NULL
EOF
add_index :people, [:user_id, :project_id], :unique => true
end
def self.down
remove_index :people, [:user_id, :project_id]
add_index :people, [:user_id, :project_id]
end
end
| class AddUniquenessIndexToPeople < ActiveRecord::Migration
def self.up
remove_index :people, [:user_id, :project_id]
Person.connection.execute <<-EOF
DELETE FROM #{Person.table_name}
WHERE id NOT IN
(SELECT id FROM (SELECT MIN(id) as id, user_id, project_id
FROM #{Person.table_name}
GROUP BY user_id, project_id) KeepRows)
EOF
add_index :people, [:user_id, :project_id], :unique => true
end
def self.down
remove_index :people, [:user_id, :project_id]
add_index :people, [:user_id, :project_id]
end
end
|
Add rspec as dev dependency | lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'version'
Gem::Specification.new do |spec|
spec.name = "jekyll-conrefifier"
spec.version = JekyllConrefifier::VERSION
spec.authors = ["Garen J. Torikian"]
spec.email = ["gjtorikian@gmail.com"]
spec.summary = %q{Allows you to use Liquid variables in various places in Jekyll}
spec.description = %q{A set of monkey patches that allows you to use Liquid variables in a variety of places in Jekyll, like frontmatter or data files.}
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.require_paths = ["lib"]
spec.add_development_dependency "jekyll", "~> 2.0"
spec.add_development_dependency "rake"
spec.add_development_dependency 'minitest', "~> 5.0"
end
| lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'version'
Gem::Specification.new do |spec|
spec.name = "jekyll-conrefifier"
spec.version = JekyllConrefifier::VERSION
spec.authors = ["Garen J. Torikian"]
spec.email = ["gjtorikian@gmail.com"]
spec.summary = %q{Allows you to use Liquid variables in various places in Jekyll}
spec.description = %q{A set of monkey patches that allows you to use Liquid variables in a variety of places in Jekyll, like frontmatter or data files.}
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.require_paths = ["lib"]
spec.add_development_dependency "jekyll", "~> 2.0"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
end
|
Fix includes, specifically require roar/rails/hal or it does not load correctly | # encoding: utf-8
class HalApi::Representer < Roar::Decorator
require 'hal_api/representer/caches'
require 'hal_api/representer/curies'
require 'hal_api/representer/embeds'
require 'hal_api/representer/format_keys'
require 'hal_api/representer/link_serialize'
require 'hal_api/representer/uri_methods'
include Roar::JSON::HAL
include HalApi::Representer::FormatKeys
include HalApi::Representer::UriMethods
include HalApi::Representer::Curies
include HalApi::Representer::Embeds
include HalApi::Representer::Caches
include HalApi::Representer::LinkSerialize
self_link
profile_link
end
| # encoding: utf-8
class HalApi::Representer < Roar::Decorator
include Roar::Hypermedia
include Roar::JSON::HAL
include Roar::JSON::HAL::Links
include Roar::JSON
require 'roar/rails/hal'
require 'hal_api/representer/caches'
require 'hal_api/representer/curies'
require 'hal_api/representer/embeds'
require 'hal_api/representer/format_keys'
require 'hal_api/representer/link_serialize'
require 'hal_api/representer/uri_methods'
include HalApi::Representer::FormatKeys
include HalApi::Representer::UriMethods
include HalApi::Representer::Curies
include HalApi::Representer::Embeds
include HalApi::Representer::Caches
include HalApi::Representer::LinkSerialize
self_link
profile_link
end
|
Remove code that supported rails 5.1 | require 'set'
require 'active_record/attributes'
require 'active_record/define_callbacks' if ActiveRecord.version >= Gem::Version.new('5.1.0')
require 'superstore/types'
module Superstore
class Base
extend ActiveModel::Naming
include ActiveModel::Conversion
extend ActiveSupport::DescendantsTracker
include ActiveModel::Serializers::JSON
include GlobalID::Identification
extend ActiveRecord::ConnectionHandling
self.connection_specification_name = 'primary'
extend ActiveRecord::Querying
extend ActiveRecord::Translation
extend ActiveRecord::Delegation::DelegateCache
include ActiveRecord::Core
include Persistence
include ActiveRecord::ReadonlyAttributes
include ModelSchema
include Inheritance
include ActiveRecord::Scoping
include ActiveRecord::Sanitization
include AttributeAssignment
include ActiveRecord::Integration
include ActiveRecord::Validations
include Attributes
include ActiveRecord::AttributeDecorators
include ActiveRecord::DefineCallbacks
include AttributeMethods
include ActiveRecord::Callbacks
include Timestamp
include Associations
include ActiveRecord::AutosaveAssociation
include ActiveRecord::Reflection
include ActiveRecord::Transactions
include Core
include Connection
include Identity
end
end
ActiveSupport.run_load_hooks(:superstore, Superstore::Base)
| require 'set'
require 'active_record/define_callbacks'
require 'superstore/types'
module Superstore
class Base
extend ActiveModel::Naming
include ActiveModel::Conversion
extend ActiveSupport::DescendantsTracker
include ActiveModel::Serializers::JSON
include GlobalID::Identification
extend ActiveRecord::ConnectionHandling
self.connection_specification_name = 'primary'
extend ActiveRecord::Querying
extend ActiveRecord::Translation
extend ActiveRecord::Delegation::DelegateCache
include ActiveRecord::Core
include Persistence
include ActiveRecord::ReadonlyAttributes
include ModelSchema
include Inheritance
include ActiveRecord::Scoping
include ActiveRecord::Sanitization
include AttributeAssignment
include ActiveRecord::Integration
include ActiveRecord::Validations
include Attributes
include ActiveRecord::AttributeDecorators
include ActiveRecord::DefineCallbacks
include AttributeMethods
include ActiveRecord::Callbacks
include Timestamp
include Associations
include ActiveRecord::AutosaveAssociation
include ActiveRecord::Reflection
include ActiveRecord::Transactions
include Core
include Connection
include Identity
end
end
ActiveSupport.run_load_hooks(:superstore, Superstore::Base)
|
Fix installed version detection for Drupal 7 |
module Versionator
module Detector
# Detects {Drupal 7}[http://drupal.org].
class Drupal7 < Base
set :app_name, "Drupal 7"
set :project_url, "http://drupal.org"
set :detect_dirs, %w{includes misc modules profiles scripts sites themes}
set :detect_files, %w{CHANGELOG.txt cron.php index.php install.php xmlrpc.php}
set :installed_version_file, "CHANGELOG.txt"
set :installed_version_regexp, /^Drupal (7.+), .*$/
set :newest_version_url, 'http://drupal.org/project/drupal'
set :newest_version_selector, '.download-table .project-release .views-row-first .views-field-version a'
set :newest_version_regexp, /^(7.+)$/
# Overridden to make sure that we do only detect Drupal7
def contents_detected?
installed_version.major >= 7
end
def project_url_for_version(version)
"#{project_url}/drupal-#{version}"
end
end
end
end
|
module Versionator
module Detector
# Detects {Drupal 7}[http://drupal.org].
class Drupal7 < Base
set :app_name, "Drupal 7"
set :project_url, "http://drupal.org"
set :detect_dirs, %w{includes misc modules profiles scripts sites themes}
set :detect_files, %w{CHANGELOG.txt cron.php index.php install.php xmlrpc.php}
set :installed_version_file, "CHANGELOG.txt"
set :installed_version_regexp, /^Drupal (.+), .*$/
set :newest_version_url, 'http://drupal.org/project/drupal'
set :newest_version_selector, '.download-table .project-release .views-row-first .views-field-version a'
set :newest_version_regexp, /^(7.+)$/
# Overridden to make sure that we do only detect Drupal7
def contents_detected?
installed_version.major >= 7 if super
end
def project_url_for_version(version)
"#{project_url}/drupal-#{version}"
end
end
end
end
|
Replace array search with hash lookup | require 'dry/types/decorator'
module Dry
module Types
class Enum
include Type
include Dry::Equalizer(:type, :options, :mapping)
include Decorator
# @return [Array]
attr_reader :values
# @return [Hash]
attr_reader :mapping
# @param [Type] type
# @param [Hash] options
# @option options [Array] :values
def initialize(type, options)
super
@mapping = options.fetch(:mapping).freeze
@values = @mapping.keys.freeze.each(&:freeze)
end
# @param [Object] input
# @return [Object]
def call(input = Undefined)
value =
if input.equal?(Undefined)
type.call
elsif values.include?(input)
input
elsif mapping.key?(input)
mapping[input]
elsif mapping.values.include?(input)
mapping.key(input)
else
input
end
type[value]
end
alias_method :[], :call
def default(*)
raise '.enum(*values).default(value) is not supported. Call '\
'.default(value).enum(*values) instead'
end
# Check whether a value is in the enum
# @param [Object] value
# @return [Boolean]
alias_method :include?, :valid?
# @api public
#
# @see Definition#to_ast
def to_ast(meta: true)
[:enum, [type.to_ast(meta: meta),
mapping,
meta ? self.meta : EMPTY_HASH]]
end
end
end
end
| require 'dry/types/decorator'
module Dry
module Types
class Enum
include Type
include Dry::Equalizer(:type, :options, :mapping)
include Decorator
# @return [Array]
attr_reader :values
# @return [Hash]
attr_reader :mapping
# @return [Hash]
attr_reader :inverted_mapping
# @param [Type] type
# @param [Hash] options
# @option options [Array] :values
def initialize(type, options)
super
@mapping = options.fetch(:mapping).freeze
@values = @mapping.keys.freeze
@inverted_mapping = @mapping.invert.freeze
freeze
end
# @param [Object] input
# @return [Object]
def call(input = Undefined)
value =
if input.equal?(Undefined)
type.call
elsif mapping.key?(input)
input
else
inverted_mapping.fetch(input, input)
end
type[value]
end
alias_method :[], :call
def default(*)
raise '.enum(*values).default(value) is not supported. Call '\
'.default(value).enum(*values) instead'
end
# Check whether a value is in the enum
# @param [Object] value
# @return [Boolean]
alias_method :include?, :valid?
# @api public
#
# @see Definition#to_ast
def to_ast(meta: true)
[:enum, [type.to_ast(meta: meta),
mapping,
meta ? self.meta : EMPTY_HASH]]
end
end
end
end
|
Make sure to cast to string. | require "foreman/kicker/version"
require "foreman/kicker/executor"
require "foreman/kicker/watchdog"
module Foreman
module Kicker
def self.port=(port)
@port = port
end
def self.port
@port
end
def self.kick(*args)
if args.include?('-p') || args.include?('--port')
self.port = args[(args.find('-p') || args.find('--port')) + 1]
else
args += ['-p', port]
end
@watchdog = Foreman::Kicker::Watchdog.new
@watchdog.start(*args)
end
def self.stop
@watchdog.stop
end
end
end
| require "foreman/kicker/version"
require "foreman/kicker/executor"
require "foreman/kicker/watchdog"
module Foreman
module Kicker
def self.port=(port)
@port = port
end
def self.port
@port
end
def self.kick(*args)
if args.include?('-p') || args.include?('--port')
self.port = args[(args.find('-p') || args.find('--port')) + 1]
else
args += ['-p', port]
end
@watchdog = Foreman::Kicker::Watchdog.new
@watchdog.start(*args.map(&:to_s))
end
def self.stop
@watchdog.stop
end
end
end
|
Upgrade excon to version 0.71.0 or later | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "wwdc/version"
Gem::Specification.new do |s|
s.name = "wwdc"
s.license = "MIT"
s.authors = ["Mattt"]
s.email = "mattt@me.com"
s.homepage = "http://mat.tt"
s.version = WWDC::VERSION
s.platform = Gem::Platform::RUBY
s.summary = "WWDC"
s.description = "A command-line interface for accessing WWDC session content"
s.add_dependency "commander", "~> 4.1"
s.add_dependency "excon", "~> 0.25"
s.add_development_dependency "rspec"
s.add_development_dependency "rake"
s.files = Dir["./**/*"].reject { |file| file =~ /\.\/(log|pkg|script|spec|test|vendor)/ }
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
end
| # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "wwdc/version"
Gem::Specification.new do |s|
s.name = "wwdc"
s.license = "MIT"
s.authors = ["Mattt"]
s.email = "mattt@me.com"
s.homepage = "http://mat.tt"
s.version = WWDC::VERSION
s.platform = Gem::Platform::RUBY
s.summary = "WWDC"
s.description = "A command-line interface for accessing WWDC session content"
s.add_dependency "commander", "~> 4.1"
s.add_dependency "excon", ">= 0.71.0"
s.add_development_dependency "rspec"
s.add_development_dependency "rake"
s.files = Dir["./**/*"].reject { |file| file =~ /\.\/(log|pkg|script|spec|test|vendor)/ }
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
end
|
Fix matching "(" in tests | title 'Add to list'
describe file('/tmp/dangerfile3') do
its(:content) { should match(/empty_list=newentry/) }
end
describe file('/tmp/dangerfile3') do
its(:content) { should match(/empty_list=newentry/) }
end
# It should not re-add an existing item
describe file('/tmp/dangerfile3') do
its(:content) { should match(%r{DEFAULT_APPEND="resume=/dev/sda2 splash=silent crashkernel=256M-:128M showopts addtogrub"}) }
end
# Add to an empty list
describe file('/tmp/dangerfile3') do
its(:content) { should match(%r{empty_delimited_list=("newentry")}) }
end
| title 'Add to list'
describe file('/tmp/dangerfile3') do
its(:content) { should match(/empty_list=newentry/) }
end
describe file('/tmp/dangerfile3') do
its(:content) { should match(/empty_list=newentry/) }
end
# It should not re-add an existing item
describe file('/tmp/dangerfile3') do
its(:content) { should match(%r{DEFAULT_APPEND="resume=/dev/sda2 splash=silent crashkernel=256M-:128M showopts addtogrub"}) }
end
# Add to an empty list
describe file('/tmp/dangerfile3') do
its(:content) { should match(%r{empty_delimited_list=\("newentry"\)}) }
end
|
Handle nil restricted visibility settings | # Gitlab::VisibilityLevel module
#
# Define allowed public modes that can be used for
# GitLab projects to determine project public mode
#
module Gitlab
module VisibilityLevel
extend CurrentSettings
PRIVATE = 0 unless const_defined?(:PRIVATE)
INTERNAL = 10 unless const_defined?(:INTERNAL)
PUBLIC = 20 unless const_defined?(:PUBLIC)
class << self
def values
options.values
end
def options
{
'Private' => PRIVATE,
'Internal' => INTERNAL,
'Public' => PUBLIC
}
end
def allowed_for?(user, level)
user.is_admin? || allowed_level?(level.to_i)
end
# Return true if the specified level is allowed for the current user.
# Level should be a numeric value, e.g. `20`.
def allowed_level?(level)
valid_level?(level) && non_restricted_level?(level)
end
def non_restricted_level?(level)
! current_application_settings.restricted_visibility_levels.include?(level)
end
def valid_level?(level)
options.has_value?(level)
end
end
def private?
visibility_level_field == PRIVATE
end
def internal?
visibility_level_field == INTERNAL
end
def public?
visibility_level_field == PUBLIC
end
end
end
| # Gitlab::VisibilityLevel module
#
# Define allowed public modes that can be used for
# GitLab projects to determine project public mode
#
module Gitlab
module VisibilityLevel
extend CurrentSettings
PRIVATE = 0 unless const_defined?(:PRIVATE)
INTERNAL = 10 unless const_defined?(:INTERNAL)
PUBLIC = 20 unless const_defined?(:PUBLIC)
class << self
def values
options.values
end
def options
{
'Private' => PRIVATE,
'Internal' => INTERNAL,
'Public' => PUBLIC
}
end
def allowed_for?(user, level)
user.is_admin? || allowed_level?(level.to_i)
end
# Return true if the specified level is allowed for the current user.
# Level should be a numeric value, e.g. `20`.
def allowed_level?(level)
valid_level?(level) && non_restricted_level?(level)
end
def non_restricted_level?(level)
if current_application_settings.restricted_visibility_levels.nil?
true
else
! current_application_settings.restricted_visibility_levels.include?(level)
end
end
def valid_level?(level)
options.has_value?(level)
end
end
def private?
visibility_level_field == PRIVATE
end
def internal?
visibility_level_field == INTERNAL
end
def public?
visibility_level_field == PUBLIC
end
end
end
|
Add BER integration test for true value | require_relative '../test_helper'
class TestBERIntegration < LDAPIntegrationTestCase
# Test whether the TRUE boolean value is encoded correctly by performing a
# search operation.
def test_true_ber_encoding
# request these attrs to simplify test; use symbols to match Entry#attribute_names
attrs = [:dn, :uid, :cn, :mail]
assert types_entry = @ldap.search(
base: "dc=rubyldap,dc=com",
filter: "(uid=user1)",
size: 1,
attributes: attrs,
attributes_only: true
).first
# matches attributes we requested
assert_equal attrs, types_entry.attribute_names
# assert values are empty
types_entry.each do |name, values|
next if name == :dn
assert values.empty?
end
assert_includes Net::LDAP::ResultCodesSearchSuccess,
@ldap.get_operation_result.code, "should be a successful search operation"
end
end
| |
Use correct config to specify allowed routes | require 'strong_routes/rails/route_mapper'
module StrongRoutes
module Rails
class Railtie < ::Rails::Railtie
config.strong_routes = ::StrongRoutes.config
initializer 'strong_routes.initialize' do |app|
config.allowed_routes ||= []
config.allowed_routes += ::StrongRoutes::Rails::RouteMapper.map(app.routes)
case
when config.strong_routes.insert_before? then
app.config.middleware.insert_before(config.strong_routes.insert_before, ::StrongRoutes::Allow)
when config.strong_routes.insert_after? then
app.config.middleware.insert_after(config.strong_routes.insert_after, ::StrongRoutes::Allow)
else
app.config.middleware.insert_before(::Rails::Rack::Logger, ::StrongRoutes::Allow)
end
end
end
end
end
| require 'strong_routes/rails/route_mapper'
module StrongRoutes
module Rails
class Railtie < ::Rails::Railtie
config.strong_routes = ::StrongRoutes.config
initializer 'strong_routes.initialize' do |app|
config.strong_routes.allowed_routes ||= []
config.strong_routes.allowed_routes += ::StrongRoutes::Rails::RouteMapper.map(app.routes)
case
when config.strong_routes.insert_before? then
app.config.middleware.insert_before(config.strong_routes.insert_before, ::StrongRoutes::Allow)
when config.strong_routes.insert_after? then
app.config.middleware.insert_after(config.strong_routes.insert_after, ::StrongRoutes::Allow)
else
app.config.middleware.insert_before(::Rails::Rack::Logger, ::StrongRoutes::Allow)
end
end
end
end
end
|
Update pods to version 0.0.3 | Pod::Spec.new do |s|
s.name = "MenuPopOverView"
s.version = "0.0.2"
s.summary = "A custom PopOverView looks like UIMenuController works on iPhone."
s.homepage = "https://github.com/camelcc/MenuPopOverView"
s.screenshots = "https://github.com/camelcc/MenuPopOverView/blob/master/popOver.png"
s.license = 'MIT'
s.author = { "camel_young" => "camel.young@gmail.com" }
s.social_media_url = "http://twitter.com/camel_young"
s.platform = :ios, '7.0'
s.source = { :git => "https://github.com/camelcc/MenuPopOverView.git", :tag => "0.0.2" }
s.source_files = 'MenuPopOverView'
s.requires_arc = true
end
| Pod::Spec.new do |s|
s.name = "MenuPopOverView"
s.version = "0.0.3"
s.summary = "A custom PopOverView looks like UIMenuController works on iPhone."
s.homepage = "https://github.com/camelcc/MenuPopOverView"
s.screenshots = "https://github.com/camelcc/MenuPopOverView/blob/master/popOver.png"
s.license = 'MIT'
s.author = { "camel_young" => "camel.young@gmail.com" }
s.social_media_url = "http://twitter.com/camel_young"
s.platform = :ios, '7.0'
s.source = { :git => "https://github.com/camelcc/MenuPopOverView.git", :tag => "0.0.3" }
s.source_files = 'MenuPopOverView'
s.requires_arc = true
end
|
Add get all metadata with certain field method | class Repository
include Tire::Model::Persistence
include Tire::Model::Search
include Tire::Model::Callbacks
validates_presence_of :name, :type, :url, :datasets, :latitude, :longitude
property :name
property :type
property :url
property :latitude
property :longitude
property :datasets
property :completeness
property :weighted_completeness
property :richness_of_information
property :accuracy
property :accessibility
def metadata
total = Tire.search('metadata', :search_type => 'count') do
query { all }
end.results.total
name = @name
Tire.search 'metadata' do
query { string 'repository:' + name }
size total
end.results.map { |entry| entry.to_hash }
end
def update_score(metric, score)
self.send("#{metric.name}=", score)
end
def best_record(metric)
sort_metric_scores(metric, 'desc').first.to_hash
end
def worst_record(metric)
sort_metric_scores(metric, 'asc').first.to_hash
end
private
def sort_metric_scores(metric, sorting_order)
name = @name
search = Tire.search 'metadata' do
query { string "repository:#{name}" }
sort { by metric, sorting_order }
end.results
end
end
| class Repository
include Tire::Model::Persistence
include Tire::Model::Search
include Tire::Model::Callbacks
validates_presence_of :name, :type, :url, :datasets, :latitude, :longitude
property :name
property :type
property :url
property :latitude
property :longitude
property :datasets
property :completeness
property :weighted_completeness
property :richness_of_information
property :accuracy
property :accessibility
def metadata
name = @name
max = total
Tire.search 'metadata' do
query { string 'repository:' + name }
size max
end.results.map { |entry| entry.to_hash }
end
def total
name = @name
total = Tire.search('metadata', :search_type => 'count') do
query { string 'repository:' + name }
end.results.total
end
def metadata_with_field(field, value="*")
name = @name
max = total
Tire.search 'metadata' do
query do
boolean do
must { string 'repository:' + name }
must { string field + ":" + value }
end
end
size max
end.results.map { |entry| entry.to_hash }
end
def update_score(metric, score)
self.send("#{metric.name}=", score)
end
def best_record(metric)
sort_metric_scores(metric, 'desc').first.to_hash
end
def worst_record(metric)
sort_metric_scores(metric, 'asc').first.to_hash
end
private
def sort_metric_scores(metric, sorting_order)
name = @name
search = Tire.search 'metadata' do
query { string "repository:#{name}" }
sort { by metric, sorting_order }
end.results
end
end
|
Fix the uninitialized constant ActiveFedora::ObjectNotFoundError NameError. | module Hyrax
# Generic Hyrax exception class.
class HyraxError < StandardError; end
# Error that is raised when an active workflow can't be found
class MissingWorkflowError < HyraxError; end
class WorkflowAuthorizationException < HyraxError; end
class SingleUseError < HyraxError; end
class ObjectNotFoundError < ActiveFedora::ObjectNotFoundError; end
end
| module Hyrax
require 'active_fedora/errors'
# Generic Hyrax exception class.
class HyraxError < StandardError; end
# Error that is raised when an active workflow can't be found
class MissingWorkflowError < HyraxError; end
class WorkflowAuthorizationException < HyraxError; end
class SingleUseError < HyraxError; end
class ObjectNotFoundError < ActiveFedora::ObjectNotFoundError; end
end
|
Add unique visualization_id to migration | require 'carto/db/migration_helper'
include Carto::Db::MigrationHelper
migration(
Proc.new do
alter_table :states do
drop_column :user_id
add_index :visualization_id
end
end,
Proc.new do
alter_table :states do
drop_index :visualization_id
add_foreign_key :user_id,
:users,
type: :uuid,
on_delete: :cascade
add_index [:visualization_id, :user_id]
end
end
)
| require 'carto/db/migration_helper'
include Carto::Db::MigrationHelper
migration(
Proc.new do
Rails::Sequel::connection.run(
'DELETE FROM states WHERE id NOT IN (SELECT state_id FROM visualizations WHERE state_id IS NOT NULL);'
)
alter_table :states do
drop_column :user_id
add_index :visualization_id, unique: true
end
end,
Proc.new do
alter_table :states do
drop_index :visualization_id
add_foreign_key :user_id,
:users,
type: :uuid,
on_delete: :cascade
add_index [:visualization_id, :user_id]
end
end
)
|
Add tests for code block | # encoding: utf-8
require './spec/spec_helper'
require './lib/gimli'
require './lib/gimli/markup'
describe Gimli::Markup::CodeBlock do
it 'should highlight code if language is supplied' do
code_block = Gimli::Markup::CodeBlock.new('1', 'ruby', 'puts "hi"')
code_block.highlighted.should include('class="CodeRay"')
code_block.highlighted.should include('class="delimiter"')
end
it 'should highlight code if no language is supplied' do
code_block = Gimli::Markup::CodeBlock.new('1', nil, 'puts "hi"')
code_block.highlighted.should include('class="CodeRay"')
end
end
| |
Use latest available version of ZooKeeper | require 'spec_helper_acceptance'
describe 'zookeeper prereq' do
zookeeper = <<-EOS
if $::osfamily == 'RedHat' {
class { 'java' :
package => 'java-1.8.0-openjdk-devel',
}
exec { 'create pid dir':
command => '/bin/mkdir -p /var/run/',
creates => '/var/run/',
}
file { '/var/run/zookeeper/':
ensure => directory,
owner => 'zookeeper',
group => 'zookeeper',
}
$zookeeper_service_provider = $facts['os']['release']['major'] ? {
'6' => 'redhat',
'7' => 'systemd',
}
class { 'zookeeper':
install_method => 'archive',
archive_version => '3.6.0',
service_provider => $zookeeper_service_provider,
manage_service_file => true,
}
} else {
include zookeeper
}
EOS
it 'installs zookeeper with no errors' do
apply_manifest(zookeeper, catch_failures: true)
apply_manifest(zookeeper, catch_changes: true)
end
end
| require 'spec_helper_acceptance'
describe 'zookeeper prereq' do
zookeeper = <<-EOS
if $::osfamily == 'RedHat' {
class { 'java' :
package => 'java-1.8.0-openjdk-devel',
}
exec { 'create pid dir':
command => '/bin/mkdir -p /var/run/',
creates => '/var/run/',
}
file { '/var/run/zookeeper/':
ensure => directory,
owner => 'zookeeper',
group => 'zookeeper',
}
$zookeeper_service_provider = $facts['os']['release']['major'] ? {
'6' => 'redhat',
'7' => 'systemd',
}
class { 'zookeeper':
install_method => 'archive',
archive_version => '3.6.1',
service_provider => $zookeeper_service_provider,
manage_service_file => true,
}
} else {
include zookeeper
}
EOS
it 'installs zookeeper with no errors' do
apply_manifest(zookeeper, catch_failures: true)
apply_manifest(zookeeper, catch_changes: true)
end
end
|
Improve error message when database configuration can't be read | module InvisionBridge
module Base
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def establish_bridge()
if Rails
config = YAML::load(File.open(Rails.configuration.database_configuration_file))
config = config["invision_bridge_#{Rails.env}"]
else
config = YAML::load(File.open(File.join(File.dirname(__FILE__), '..', '..', 'config', 'database.yml')))
config = config["invision_bridge"]
end
config['prefix'] ||= 'ibf_'
establish_connection(config)
unloadable # http://www.dansketcher.com/2009/05/11/cant-dup-nilclass/
set_table_name "#{config['prefix']}members"
set_primary_key "member_id"
end
end
end
end
| module InvisionBridge
module Base
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def establish_bridge()
if Rails
config_file = Rails.configuration.database_configuration_file
config_group = "invision_bridge_#{Rails.env}"
else
config_file = File.join(File.dirname(__FILE__), '..', '..', 'config', 'database.yml')
config_group = "invision_bridge"
end
begin
config = YAML::load(config_file)
config = config[config_group]
config['prefix'] ||= 'ibf_'
rescue NoMethodError
raise "Unable to read database configuration from #{config_file} -- Make sure an #{config_group} definition exists."
end
establish_connection(config)
unloadable # http://www.dansketcher.com/2009/05/11/cant-dup-nilclass/
set_table_name "#{config['prefix']}members"
set_primary_key "member_id"
end
end
end
end
|
Drop removed spec property rubyforge_project | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "keycutter/version"
Gem::Specification.new do |s|
s.name = "keycutter"
s.version = Keycutter::VERSION
s.platform = Gem::Platform::RUBY
s.licenses = ['MIT']
s.authors = ["Josh French"]
s.email = ["josh@vitamin-j.com"]
s.homepage = "http://github.com/joshfrench/keycutter"
s.summary = %q{Gemcutter key management}
s.description = %q{Multiple gemcutter accounts? Manage your keys with ease.}
s.rubyforge_project = "keycutter"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {spec,features}/*`.split("\n")
s.require_paths = ["lib"]
end
| # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "keycutter/version"
Gem::Specification.new do |s|
s.name = "keycutter"
s.version = Keycutter::VERSION
s.platform = Gem::Platform::RUBY
s.licenses = ['MIT']
s.authors = ["Josh French"]
s.email = ["josh@vitamin-j.com"]
s.homepage = "http://github.com/joshfrench/keycutter"
s.summary = %q{Gemcutter key management}
s.description = %q{Multiple gemcutter accounts? Manage your keys with ease.}
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {spec,features}/*`.split("\n")
s.require_paths = ["lib"]
end
|
Move test subject to beginning of describe | describe 'config/default.yml' do
let(:cop_names) do
glob = SpecHelper::ROOT.join('lib', 'rubocop', 'cop', 'rspec', '*.rb')
Pathname.glob(glob).map do |file|
file_name = file.basename('.rb').to_s
cop_name = file_name.gsub(/(^|_)(.)/) { Regexp.last_match(2).upcase }
"RSpec/#{cop_name}"
end
end
let(:config_keys) do
cop_names + %w(AllCops)
end
subject(:default_config) do
RuboCop::ConfigLoader.load_file('config/default.yml')
end
it 'has configuration for all cops' do
expect(default_config.keys.sort).to eq(config_keys.sort)
end
it 'has a nicely formatted description for all cops' do
cop_names.each do |name|
description = default_config[name]['Description']
expect(description).not_to be_nil
expect(description).not_to include("\n")
end
end
end
| describe 'config/default.yml' do
subject(:default_config) do
RuboCop::ConfigLoader.load_file('config/default.yml')
end
let(:cop_names) do
glob = SpecHelper::ROOT.join('lib', 'rubocop', 'cop', 'rspec', '*.rb')
Pathname.glob(glob).map do |file|
file_name = file.basename('.rb').to_s
cop_name = file_name.gsub(/(^|_)(.)/) { Regexp.last_match(2).upcase }
"RSpec/#{cop_name}"
end
end
let(:config_keys) do
cop_names + %w(AllCops)
end
it 'has configuration for all cops' do
expect(default_config.keys.sort).to eq(config_keys.sort)
end
it 'has a nicely formatted description for all cops' do
cop_names.each do |name|
description = default_config[name]['Description']
expect(description).not_to be_nil
expect(description).not_to include("\n")
end
end
end
|
Add method to fetch instantiated engine directly from App. | module Fewer
class App
class << self
def [](name)
apps[name]
end
def apps
@apps ||= {}
end
end
attr_reader :name, :engine_klass, :cache, :root
def initialize(name, options = {})
@engine_klass = options[:engine]
@mount = options[:mount]
@root = options[:root]
@cache = options[:cache] || 3600 * 24 * 365
raise 'You need to define an :engine class' unless @engine_klass
raise 'You need to define a :root path' unless @root
self.class.apps[name] = self
end
def call(env)
names = names_from_path(env['PATH_INFO'])
engine = engine_klass.new(root, names)
headers = {
'Content-Type' => engine.content_type,
'Cache-Control' => "public, max-age=#{cache}"
}
[200, headers, [engine.read]]
rescue Fewer::MissingSourceFileError => e
[404, { 'Content-Type' => 'text/plain' }, [e.message]]
rescue => e
[500, { 'Content-Type' => 'text/plain' }, ["#{e.class}: #{e.message}"]]
end
private
def names_from_path(path)
encoded = File.basename(path, '.*')
Serializer.decode(encoded)
end
end
end
| module Fewer
class App
class << self
def [](name)
apps[name]
end
def apps
@apps ||= {}
end
end
attr_reader :name, :engine_klass, :cache, :root
def initialize(name, options = {})
@engine_klass = options[:engine]
@mount = options[:mount]
@root = options[:root]
@cache = options[:cache] || 3600 * 24 * 365
raise 'You need to define an :engine class' unless @engine_klass
raise 'You need to define a :root path' unless @root
self.class.apps[name] = self
end
def call(env)
eng = engine(names_from_path(env['PATH_INFO']))
headers = {
'Content-Type' => eng.content_type,
'Cache-Control' => "public, max-age=#{cache}"
}
[200, headers, [eng.read]]
rescue Fewer::MissingSourceFileError => e
[404, { 'Content-Type' => 'text/plain' }, [e.message]]
rescue => e
[500, { 'Content-Type' => 'text/plain' }, ["#{e.class}: #{e.message}"]]
end
def engine(names)
engine_klass.new(root, names)
end
private
def names_from_path(path)
encoded = File.basename(path, '.*')
Serializer.decode(encoded)
end
end
end
|
Remove multiple references to "segment" in docs | module SubDiff
# Performs a {String#sub} or {String#gsub} replacement
# while yielding each match "diff payload" to a block.
#
# The payload contains:
#
# match - the string segment matching the search.
# prefix - the string segment preceding the match.
# suffix - the string segment trailing the match.
# replacement - the string segment replacing the match.
#
# This class uses some special global variables: $` and $'.
# See http://ruby-doc.org/core-2.2.0/doc/globals_rdoc.html
#
# Used internally by {Sub}.
#
# @api private
class Differ
include Buildable
def each_diff(search, *args, block)
string.send(diff_method, search) do |match|
diff = { match: match, prefix: $`, suffix: $' }
diff[:replacement] = match.sub(search, *args, &block)
yield(diff)
end
end
end
end
| module SubDiff
# Performs a {String#sub} or {String#gsub} replacement
# while yielding each match "diff payload" to a block.
#
# The payload contains:
#
# match - the string matching the search.
# prefix - the string preceding the match.
# suffix - the string trailing the match.
# replacement - the string replacing the match.
#
# This class uses some special global variables: $` and $'.
# See http://ruby-doc.org/core-2.2.0/doc/globals_rdoc.html
#
# Used internally by {Sub}.
#
# @api private
class Differ
include Buildable
def each_diff(search, *args, block)
string.send(diff_method, search) do |match|
diff = { match: match, prefix: $`, suffix: $' }
diff[:replacement] = match.sub(search, *args, &block)
yield(diff)
end
end
end
end
|
Test for an ohai_hint resource | require 'spec_helper'
describe 'aws::ec2_hints' do
let(:chef_run) { ChefSpec::SoloRunner.converge(described_recipe) }
it 'sets up the directory' do
expect(chef_run).to create_directory('/etc/chef/ohai/hints').at_compile_time
end
it 'adds the hint file' do
expect(chef_run).to create_file('/etc/chef/ohai/hints/ec2.json').at_compile_time
end
it 'reloads ohai' do
expect(chef_run).to reload_ohai('reload')
end
end
| require 'spec_helper'
describe 'aws::ec2_hints' do
let(:chef_run) { ChefSpec::SoloRunner.converge(described_recipe) }
it 'adds the hint file' do
expect(chef_run).to create_ohai_hint('ec2').at_compile_time
end
it 'reloads ohai' do
expect(chef_run).to reload_ohai('reload')
end
end
|
Add performance test for /api/magazines | # frozen_string_literal: true
RSpec.describe MagazinesController, type: :controller, bench: true do
before do
ApplicationRecord.transaction do
3.times do
magazine = create_force(:magazine, source: nil)
episode = create_list(:episode, 60, magazine: magazine)
0.upto(300) do |i|
create_force(:page, magazine: magazine, episode: episode[i % 5], content: nil)
end
end
end
end
it do
expect { get :index }.to perform_under(1500).ms.and_sample(3)
end
end
| |
Fix syntactically invalid Machete pattern in a check used in specs | module Scanny
module Checks
class ExtendCheck < Check; end
class MyCheck < ExtendCheck
def pattern
''
end
end
end
end | module Scanny
module Checks
class ExtendCheck < Check; end
class MyCheck < ExtendCheck
def pattern
'NilClass'
end
end
end
end
|
Fix race condition when tenant is not set in tests | # Brimir is a helpdesk system to handle email support requests.
# Copyright (C) 2012-2015 Ivaldi https://ivaldi.nl/
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class AttachmentsControllerTest < ActionController::TestCase
setup do
sign_in users(:alice)
@attachment = attachments(:default_page)
@attachment.update_attributes!({
file: fixture_file_upload('attachments/default-testpage.pdf', 'application/pdf')
})
end
test 'should get new' do
sign_out users(:alice)
xhr :get, :new
assert_response :success
end
test 'should show thumb' do
get :show, format: :thumb, id: @attachment.id
assert_response :success
end
test 'should download original' do
get :show, format: :original, id: @attachment.id
assert_response :success
end
end
| # Brimir is a helpdesk system to handle email support requests.
# Copyright (C) 2012-2015 Ivaldi https://ivaldi.nl/
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class AttachmentsControllerTest < ActionController::TestCase
setup do
sign_in users(:alice)
Tenant.current_domain = Tenant.first.domain
@attachment = attachments(:default_page)
@attachment.update_attributes!({
file: fixture_file_upload('attachments/default-testpage.pdf', 'application/pdf')
})
end
test 'should get new' do
sign_out users(:alice)
xhr :get, :new
assert_response :success
end
test 'should show thumb' do
get :show, format: :thumb, id: @attachment.id
assert_response :success
end
test 'should download original' do
get :show, format: :original, id: @attachment.id
assert_response :success
end
end
|
Make these readers (but maybe they aren't even needed) | module QuickTravel
class Party < Adapter
LOGIN_URL = '/login.json'
attr_accessor :phone, :mobile, :email # if has a contact
attr_accessor :post_code, :country_id # if has an address
def initialize(hash = {})
super
if type.blank?
self.type = 'Person'
end
end
self.api_base = '/parties'
def self.find_by_login(options)
get_and_validate('/parties/find_by_login.json', options)
end
# Asks QuickTravel to check the credentials
#
# @returns: Party: Valid Credentials
# Nil: Invalid Credentialss
def self.login(options = { login: nil, password: nil })
unless options[:login] && options[:password]
fail ArgumentError, 'You must specify :login and :password'
end
response = post_and_validate(LOGIN_URL, options)
Party.new(response) unless response[:error]
end
def self.request_password(login, url)
options = { login: login, url: url }
post_and_validate('/sessions/request_password_reset', options)
end
def self.set_password_via_token(token, password)
post_and_validate('/sessions/set_password_via_token', token: token, password: password)
rescue QuickTravel::AdapterError => e
{ error: e.message }
end
end
end
| module QuickTravel
class Party < Adapter
LOGIN_URL = '/login.json'
attr_reader :phone, :mobile, :email # if has a contact
attr_reader :post_code, :country_id # if has an address
def initialize(hash = {})
super
if type.blank?
self.type = 'Person'
end
end
self.api_base = '/parties'
def self.find_by_login(options)
get_and_validate('/parties/find_by_login.json', options)
end
# Asks QuickTravel to check the credentials
#
# @returns: Party: Valid Credentials
# Nil: Invalid Credentialss
def self.login(options = { login: nil, password: nil })
unless options[:login] && options[:password]
fail ArgumentError, 'You must specify :login and :password'
end
response = post_and_validate(LOGIN_URL, options)
Party.new(response) unless response[:error]
end
def self.request_password(login, url)
options = { login: login, url: url }
post_and_validate('/sessions/request_password_reset', options)
end
def self.set_password_via_token(token, password)
post_and_validate('/sessions/set_password_via_token', token: token, password: password)
rescue QuickTravel::AdapterError => e
{ error: e.message }
end
end
end
|
Update DataModel::Gene to use the new schema changes | module DataModel
class GeneGroup < ::ActiveRecord::Base
include Genome::Extensions::UUIDPrimaryKey
self.table_name = 'gene_name_group'
has_and_belongs_to_many :genes, join_table: :gene_name_group_bridge, foreign_key: :gene_name_group_id, association_foreign_key: :gene_name_report_id
class << self
def for_search
eager_load{[genes, genes.interactions, genes.interactions.drug, genes.interactions.drug.drug_alternate_names, genes.interactions.drug.drug_categories, genes.interactions.citation, genes.interactions.interaction_attributes ]}
end
def for_gene_categories
eager_load{[genes, genes.gene_alternate_names]}
end
end
def potentially_druggable_genes
#return Go or other potentially druggable categories
citation_ids = DataModel::Source.potentially_druggable_sources.map{|c| c.id}
genes.select{|g| citation_ids.include?(g.citation.id)}
end
def display_name
alternate_names = Maybe(genes).map{|g| g.gene_alternate_names}.flatten.select{|a| a.nomenclature == 'Gene Description'}
if alternate_names.empty?
name
else
[name, ' (', alternate_names[0].alternate_name, ')'].join("")
end
end
end
end
| module DataModel
class GeneGroup < ::ActiveRecord::Base
include Genome::Extensions::UUIDPrimaryKey
self.table_name = 'gene_name_group'
has_and_belongs_to_many :genes, join_table: :gene_name_group_bridge, foreign_key: :gene_name_group_id, association_foreign_key: :gene_name_report_id
class << self
def for_search
eager_load{[genes, genes.interactions, genes.interactions.drug, genes.interactions.drug.drug_alternate_names, genes.interactions.drug.drug_categories, genes.interactions.citation, genes.interactions.interaction_attributes ]}
end
def for_gene_categories
eager_load{[genes, genes.gene_alternate_names]}
end
end
def potentially_druggable_genes
#return Go or other potentially druggable categories
source_ids = DataModel::Source.potentially_druggable_sources.map{|s| s.id}
genes.select{|g| source_ids.include?(g.citation.id)}
end
def display_name
alternate_names = Maybe(genes).map{|g| g.gene_claim_aliases}.flatten.select{|a| a.nomenclature == 'Gene Description'}
if alternate_names.empty?
name
else
[name, ' (', alternate_names[0].alias, ')'].join("")
end
end
end
end
|
Change resource listing at sidebar of administrate | # DashboardManifest tells Administrate which dashboards to display
class DashboardManifest
# `DASHBOARDS`
# a list of dashboards to display in the side navigation menu
#
# These are all of the rails models that we found in your database
# at the time you installed Administrate.
#
# To show or hide dashboards, add or remove the model name from this list.
# Dashboards returned from this method must be Rails models for Administrate
# to work correctly.
DASHBOARDS = [
:users,
:categories,
:choirs
]
# `ROOT_DASHBOARD`
# the name of the dashboard that will be displayed
# at "http://your_site.com/admin"
#
# This dashboard will likely be the first page that admins see
# when they log into the dashboard.
ROOT_DASHBOARD = DASHBOARDS.first
end
| # DashboardManifest tells Administrate which dashboards to display
class DashboardManifest
# `DASHBOARDS`
# a list of dashboards to display in the side navigation menu
#
# These are all of the rails models that we found in your database
# at the time you installed Administrate.
#
# To show or hide dashboards, add or remove the model name from this list.
# Dashboards returned from this method must be Rails models for Administrate
# to work correctly.
DASHBOARDS = [
:choirs,
:categories,
:users
]
# `ROOT_DASHBOARD`
# the name of the dashboard that will be displayed
# at "http://your_site.com/admin"
#
# This dashboard will likely be the first page that admins see
# when they log into the dashboard.
ROOT_DASHBOARD = DASHBOARDS.first
end
|
Simplify match scoring a bit | class StarScope::Datum
attr_reader :key, :scope, :file, :line
def initialize(fqn, file, line)
@key = fqn[-1].to_sym
@scope = fqn[0...-1].map {|x| x.to_sym}
@file = file
@line = line
end
def score_match(fqn)
score = 0
i = -1
fqn[0...-1].reverse.each do |test|
if test.to_sym == @scope[i]
score += 5
elsif Regexp.new(test).match(@scope[i])
score += 3
elsif Regexp.new(test, Regexp::IGNORECASE).match(@scope[i])
score += 1
end
i -= 1
end
score - @scope.count - i + 1
end
def location
"#{file}:#{line}"
end
def to_s
if @scope.empty?
"#{key} -- #{location}"
else
"#{@scope.join " "} #{@key} -- #{location}"
end
end
end
| class StarScope::Datum
attr_reader :key, :scope, :file, :line
def initialize(fqn, file, line)
@key = fqn[-1].to_sym
@scope = fqn[0...-1].map {|x| x.to_sym}
@file = file
@line = line
end
def score_match(fqn)
score = 0
i = -1
fqn[0...-1].reverse.each do |test|
if test.to_sym == @scope[i]
score += 5
elsif Regexp.new(test, Regexp::IGNORECASE).match(@scope[i])
score += 2
end
i -= 1
end
score - @scope.count - i + 1
end
def location
"#{file}:#{line}"
end
def to_s
if @scope.empty?
"#{key} -- #{location}"
else
"#{@scope.join " "} #{@key} -- #{location}"
end
end
end
|
Fix weird failing test case | class ConversationSummarizer
include ActionView::Helpers::TextHelper
LENGTH = 200
attr_accessor :conversation
def self.summary(conversation)
new(conversation).summary
end
def initialize(conversation)
self.conversation = conversation
end
def summary
if subject
subject
elsif first_sentence.size <= LENGTH
first_sentence
else
truncated_message
end
end
def subject
conversation.subject
end
def first_sentence
sentence = first_message && first_message.partition(/\.|\?|\!|\s\-\s/)[0..1].join
sentence.strip.chomp('-').strip
end
def truncated_message
first_message && truncate(first_message, length: LENGTH, separator: ' ').html_safe
end
def first_message
conversation.first_message && conversation.first_message.content
end
end
| class ConversationSummarizer
include ActionView::Helpers::TextHelper
LENGTH = 200
attr_accessor :conversation
def self.summary(conversation)
new(conversation).summary
end
def initialize(conversation)
self.conversation = conversation
end
def summary
if subject.present?
subject
elsif first_sentence.size <= LENGTH
first_sentence
else
truncated_message
end
end
def subject
conversation.subject
end
def first_sentence
sentence = first_message && first_message.partition(/\.|\?|\!|\s\-\s/)[0..1].join
sentence.to_s.strip.chomp('-').strip
end
def truncated_message
first_message && truncate(first_message, length: LENGTH, separator: ' ').html_safe
end
def first_message
conversation.first_message && conversation.first_message.content
end
end
|
Read from Spree config to determine whether Fishbowl integration is enabled, always | require 'spree_core'
require 'spree_fishbowl/engine'
module SpreeFishbowl
@@fishbowl = nil
def self.connection
@@fishbowl
end
def self.enabled?
defined? @@enabled ?
@@enabled :
Spree::Config[:enable_fishbowl]
end
def self.client_from_config
@@fishbowl ||= SpreeFishbowl::Client.from_config
end
end
| require 'spree_core'
require 'spree_fishbowl/engine'
module SpreeFishbowl
@@fishbowl = nil
def self.connection
@@fishbowl
end
def self.enabled?
Spree::Config[:enable_fishbowl]
end
def self.client_from_config
@@fishbowl ||= SpreeFishbowl::Client.from_config
end
end
|
Create method added to the mentors controller for when new mentors sign up. | class MentorsController < ApplicationController
def create
end
end
| class MentorsController < ApplicationController
def create
details = mentor_params
user_id = {user_id:current_user.id}
email = {email:current_user.email}
parameters = details.merge(user_id).merge(email)
@mentor = Mentor.new(parameters)
if @mentor.save
current_user.update(complete:true)
if @mentor.counry_of_origin == 1
@mentor.update(counry_of_origin:@mentor.current_country)
end
redirect_to edit_user_registration_path
else
flash[:error] = "An Error Occurred. Try Again."
redirect_to join_mentor_path
end
end
private
def mentor_params
params.require(:mentor).permit(:f_name,:l_name,:address_1,:address_2,
:city,:state_province,:zip_postal,:phone_no,:company,
:job_title,:industry_type,:gender,
:current_country,:counry_of_origin)
end
end
|
Add missing libffi dep to pyopenssl | name "python-pyopenssl"
default_version "0.14"
dependency 'pip'
pip_install = "embedded/bin/pip install -I --build #{project_dir}"
env = {
"CFLAGS" => ["-I#{install_dir}/embedded/include",
"-I#{install_dir}/embedded/include/openssl",
"-I#{install_dir}/embedded/include/curl"].join(" "),
"LDFLAGS" => "-L#{install_dir}/embedded/lib",
"PATH" => "#{install_dir}/embedded/bin:#{ENV["PATH"]}"
}
build do
command "#{install_dir}/#{pip_install} pyOpenSSL==#{default_version}", :env => env
end
| name "python-pyopenssl"
default_version "0.14"
dependency 'pip'
dependency 'libffi'
pip_install = "embedded/bin/pip install -I --build #{project_dir}"
env = {
"CFLAGS" => ["-I#{install_dir}/embedded/include",
"-I#{install_dir}/embedded/include/openssl",
"-I#{install_dir}/embedded/include/curl"].join(" "),
"LDFLAGS" => "-L#{install_dir}/embedded/lib",
"PATH" => "#{install_dir}/embedded/bin:#{ENV["PATH"]}"
}
build do
command "#{install_dir}/#{pip_install} pyOpenSSL==#{default_version}", :env => env
end
|
Use Octokit client for now | class PullRequestDownloader
attr_reader :login, :oauth_token
def initialize(login, oauth_token)
@login, @oauth_token = login, oauth_token
end
def pull_requests
@pull_requests ||= download_pull_requests
end
private
def github_client
@github_client ||= Octokit::Client.new(:login => login, :access_token => oauth_token, :auto_paginate => true)
end
def download_pull_requests
begin
events = github_client.user_events(login)
events.select do |e|
event_date = e['created_at']
e.type == 'PullRequestEvent' &&
e.payload.action == 'opened' &&
event_date >= PullRequest::EARLIEST_PULL_DATE &&
event_date <= PullRequest::LATEST_PULL_DATE
end
rescue => e
puts e.inspect
puts 'likely a Github api error occurred'
[]
end
end
end
| class PullRequestDownloader
attr_reader :login, :oauth_token
def initialize(login, oauth_token)
@login, @oauth_token = login, oauth_token
end
def pull_requests
@pull_requests ||= download_pull_requests
end
private
def github_client
@github_client ||= Octokit::Client.new(:login => login, :access_token => oauth_token, :auto_paginate => true)
end
def download_pull_requests
begin
events = Octokit.user_events(login)
events.select do |e|
event_date = e['created_at']
e.type == 'PullRequestEvent' &&
e.payload.action == 'opened' &&
event_date >= PullRequest::EARLIEST_PULL_DATE &&
event_date <= PullRequest::LATEST_PULL_DATE
end
rescue => e
puts e.inspect
puts 'likely a Github api error occurred'
[]
end
end
end
|
Copy over images when building slides | desc 'Build presentation'
task :presentation => [ 'slides', 'slides.html'] do
cp 'slides.html', 'slides'
cp_r REVEAL_FILES, 'slides'
line_nums = {
default_slides: {
first: 37,
last: 338
}
}
default_slides = line_nums[:default_slides][:first]..line_nums[:default_slides][:last]
FileSlicer.remove! 'slides/index.html', default_slides
FileSplicer.insert! 'slides.html', into: 'slides/index.html', after: '<div class="slides">'
end
|
DIR_IMAGES_FILES = FileList["images/**/*"]
desc 'Build presentation'
task :presentation => [ 'slides', 'slides.html'] do
cp 'slides.html', 'slides'
cp_r REVEAL_FILES, 'slides'
mkdir_p 'slides/images'
cp_r DIR_IMAGES_FILES, 'slides/images'
line_nums = {
default_slides: {
first: 37,
last: 338
}
}
default_slides = line_nums[:default_slides][:first]..line_nums[:default_slides][:last]
FileSlicer.remove! 'slides/index.html', default_slides
FileSplicer.insert! 'slides.html', into: 'slides/index.html', after: '<div class="slides">'
end
|
Fix generating training data locally | require "csv"
module Relevancy
module LoadJudgements
def self.from_csv(datafile)
data = []
last_query = ""
CSV.foreach(datafile, headers: true) do |row|
query = (row["query"] || last_query).strip
score = row["score"]
content_id = row["content_id"]
link = row["link"]
raise "missing query for row '#{row}'" if query.nil?
raise "missing score for row '#{row}'" if score.nil?
raise "missing link|content_id for row '#{row}" if content_id.nil? && link.nil?
data << { rank: score.to_i, content_id: content_id, link: link, query: query }
last_query = query
end
data
end
end
end
| require "csv"
module Relevancy
module LoadJudgements
def self.from_csv(datafile)
data = []
last_query = ""
CSV.foreach(datafile, headers: true) do |row|
query = (row["query"] || last_query).strip
score = row["score"]
content_id = row["content_id"]
link = row["link"]
raise "missing query for row '#{row}'" if query.nil?
raise "missing score for row '#{row}'" if score.nil?
raise "missing link|content_id for row '#{row}" if content_id.nil? && link.nil?
data << { score: score.to_i, content_id: content_id, link: link, query: query }
last_query = query
end
data
end
end
end
|
Remove currentIndex as its no longer needed. | module SalesforceBulk
class QueryResultCollection < Array
attr_reader :client
attr_reader :currentIndex
attr_reader :batchId
attr_reader :jobId
attr_reader :totalSize
attr_reader :resultId
attr_reader :previousResultId
attr_reader :nextResultId
def initialize(client, jobId, batchId, totalSize=0, resultId=nil, previousResultId=nil, nextResultId=nil)
@client = client
@jobId = jobId
@batchId = batchId
@totalSize = totalSize
@resultId = resultId
@previousResultId = previousResultId
@nextResultId = nextResultId
end
def next?
@nextResultId.present?
end
def next
# if calls method on client to fetch data and returns new collection instance
SalesforceBulk::QueryResultCollection.new(self.client, self.jobId, self.batchId)
end
def previous?
@previousResultId.present?
end
def previous
# if has previous, calls method on client to fetch data and returns new collection instance
SalesforceBulk::QueryResultCollection.new(self.client, self.jobId, self.batchId)
end
end
end | module SalesforceBulk
class QueryResultCollection < Array
attr_reader :client
attr_reader :batchId
attr_reader :jobId
attr_reader :totalSize
attr_reader :resultId
attr_reader :previousResultId
attr_reader :nextResultId
def initialize(client, jobId, batchId, totalSize=0, resultId=nil, previousResultId=nil, nextResultId=nil)
@client = client
@jobId = jobId
@batchId = batchId
@totalSize = totalSize
@resultId = resultId
@previousResultId = previousResultId
@nextResultId = nextResultId
end
def next?
@nextResultId.present?
end
def next
# if calls method on client to fetch data and returns new collection instance
SalesforceBulk::QueryResultCollection.new(self.client, self.jobId, self.batchId)
end
def previous?
@previousResultId.present?
end
def previous
# if has previous, calls method on client to fetch data and returns new collection instance
SalesforceBulk::QueryResultCollection.new(self.client, self.jobId, self.batchId)
end
end
end |
Fix output when using with airbrussh | module SSHKit
module Sudo
class DefaultInteractionHandler
def wrong_password; self.class.wrong_password; end
def password_prompt; self.class.password_prompt; end
def on_data(command, stream_name, data, channel)
if data =~ wrong_password
SSHKit::Sudo.password_cache[password_cache_key(command.host)] = nil
end
if data =~ password_prompt
key = password_cache_key(command.host)
pass = SSHKit::Sudo.password_cache[key]
unless pass
print data
pass = $stdin.noecho(&:gets)
puts ''
SSHKit::Sudo.password_cache[key] = pass
end
channel.send_data(pass)
end
end
def password_cache_key(host)
"#{host.user}@#{host.hostname}"
end
class << self
def wrong_password
@wrong_password ||= /Sorry.*\stry\sagain/
end
def password_prompt
@password_prompt ||= /[Pp]assword.*:/
end
def wrong_password_regexp(regexp)
@wrong_password = regexp
end
def password_prompt_regexp(regexp)
@password_prompt = regexp
end
def use_same_password!
class_eval <<-METHOD, __FILE__, __LINE__ + 1
def password_cache_key(host)
'0'
end
METHOD
end
end
end
class InteractionHandler < DefaultInteractionHandler
end
end
end
| module SSHKit
module Sudo
class DefaultInteractionHandler
def wrong_password; self.class.wrong_password; end
def password_prompt; self.class.password_prompt; end
def on_data(command, stream_name, data, channel)
if data =~ wrong_password
puts data if defined?(Airbrussh) and
Airbrussh.configuration.command_output != :stdout and
data !~ password_prompt
SSHKit::Sudo.password_cache[password_cache_key(command.host)] = nil
end
if data =~ password_prompt
key = password_cache_key(command.host)
pass = SSHKit::Sudo.password_cache[key]
unless pass
print data
pass = $stdin.noecho(&:gets)
puts ''
SSHKit::Sudo.password_cache[key] = pass
end
channel.send_data(pass)
end
end
def password_cache_key(host)
"#{host.user}@#{host.hostname}"
end
class << self
def wrong_password
@wrong_password ||= /Sorry.*\stry\sagain/
end
def password_prompt
@password_prompt ||= /[Pp]assword.*:/
end
def wrong_password_regexp(regexp)
@wrong_password = regexp
end
def password_prompt_regexp(regexp)
@password_prompt = regexp
end
def use_same_password!
class_eval <<-METHOD, __FILE__, __LINE__ + 1
def password_cache_key(host)
'0'
end
METHOD
end
end
end
class InteractionHandler < DefaultInteractionHandler
end
end
end
|
Use exclamation sign icon for order events tab | Deface::Override.new(:virtual_path => "spree/admin/shared/_order_tabs",
:name => "add_events_to_order_tabs",
:insert_bottom => "[data-hook='admin_order_tabs']",
:text => %q{
<li<%== ' class="active"' if current == 'Events' %>>
<%= link_to_with_icon 'icon-cogs', t(:order_events), spree.admin_order_events_url(@order) %>
</li>
},
:disabled => false)
| Deface::Override.new(:virtual_path => "spree/admin/shared/_order_tabs",
:name => "add_events_to_order_tabs",
:insert_bottom => "[data-hook='admin_order_tabs']",
:text => %q{
<li<%== ' class="active"' if current == 'Events' %>>
<%= link_to_with_icon 'icon-exclamation-sign', t(:order_events), spree.admin_order_events_url(@order) %>
</li>
},
:disabled => false)
|
Set Ubuntu 18.04 for unit tests | require 'chefspec'
require 'chefspec/berkshelf'
require 'coveralls'
Coveralls.wear!
RSpec.configure do |config|
config.formatter = :documentation
config.color = true
config.platform = 'ubuntu'
config.version = '14.04'
config.log_level = :fatal
end
at_exit { ChefSpec::Coverage.report! }
| require 'chefspec'
require 'chefspec/berkshelf'
require 'coveralls'
Coveralls.wear!
RSpec.configure do |config|
config.formatter = :documentation
config.color = true
config.platform = 'ubuntu'
config.version = '18.04'
config.log_level = :fatal
end
at_exit { ChefSpec::Coverage.report! }
|
Use camelCase in /performances API response | json.array! @performances do |performance|
json.id performance.id.to_s
json.stage_time performance.stage_time
json.category_name performance.category.name
json.age_group performance.age_group
json.associated_host_name performance.associated_host.name
json.associated_host_country performance.associated_host.country.country_code.upcase
json.appearances performance.appearances.role_order do |appearance|
json.participant_name appearance.participant.full_name
json.instrument_name appearance.instrument.name
json.role appearance.role.slug
end
end
| json.array! @performances do |performance|
json.id performance.id.to_s
json.stageTime performance.stage_time
json.categoryName performance.category.name
json.ageGroup performance.age_group
json.associatedHostName performance.associated_host.name
json.associatedHostCountry performance.associated_host.country.country_code.upcase
json.appearances performance.appearances.role_order do |appearance|
json.participantName appearance.participant.full_name
json.instrumentName appearance.instrument.name
json.role appearance.role.slug
end
end
|
Add appsignal require to Sinatra integration | Appsignal.logger.info('Loading Sinatra integration')
app_settings = ::Sinatra::Application.settings
Appsignal.config = Appsignal::Config.new(
app_settings.root,
app_settings.environment.to_s
)
Appsignal.logger = Logger.new(File.join(app_settings.root, 'appsignal.log')).tap do |l|
l.level = Logger::DEBUG
end
Appsignal.flush_in_memory_log
if Appsignal.active?
Appsignal.start
::Sinatra::Application.use(Appsignal::Rack::Listener)
::Sinatra::Application.use(Appsignal::Rack::Instrumentation)
end
| require 'appsignal'
Appsignal.logger.info('Loading Sinatra integration')
app_settings = ::Sinatra::Application.settings
Appsignal.config = Appsignal::Config.new(
app_settings.root,
app_settings.environment.to_s
)
Appsignal.logger = Logger.new(File.join(app_settings.root, 'appsignal.log')).tap do |l|
l.level = Logger::DEBUG
end
Appsignal.flush_in_memory_log
if Appsignal.active?
Appsignal.start
::Sinatra::Application.use(Appsignal::Rack::Listener)
::Sinatra::Application.use(Appsignal::Rack::Instrumentation)
end
|
Fix nil spec for entitle. | require 'spec_helper'
describe NilClass do
it "should respond to entitle" do
expect(nil.entitle).to eq nil
end
it "should respond to tex_quote" do
expect(nil.tex_quote).to eq ''
end
end
| require 'spec_helper'
describe NilClass do
it "should respond to entitle" do
expect(nil.entitle).to eq ''
end
it "should respond to tex_quote" do
expect(nil.tex_quote).to eq ''
end
end
|
Add char attribute back to computer player | class ComputerPlayer
attr_accessor :minimax
def initialize(minimax = Minimax)
self.minimax = minimax
end
def get_next_move(board)
minimax_result = self.minimax.run(board)
best_move_from minimax_result
end
private
def best_move_from(scores)
scores.each_with_index.max[1].to_s
end
end
| class ComputerPlayer
attr_accessor :minimax, :char
def initialize(char, minimax = Minimax)
self.minimax = minimax
self.char = char
end
def get_next_move(board)
minimax_result = self.minimax.run(board)
(0..8).each do |i|
minimax_result[i] -= 2 if minimax_result[i] == 0
end
best_move_from minimax_result
end
private
def best_move_from(scores)
scores.each_with_index.max[1].to_s
end
end
|
Add back the accidentally deleted spec | # frozen_string_literal: true
require 'spec_helper'
require 'ostruct'
RSpec.describe ActiveSet::SortProcessor do
let(:processor) { described_class.new(set, filter_structure) }
context 'when set is Enumerable' do
include_context 'for enumerable sets'
before(:each) do
foo.tap do |foo|
foo.bignum = 2**64
foo.boolean = true
foo.date = 1.day.from_now.to_date
foo.datetime = 1.day.from_now.to_datetime
foo.float = 1.11
foo.integer = 1
foo.nil = nil
foo.string = 'aaa'
foo.symbol = :aaa
foo.time = 1.day.from_now.to_time
end
foo.assoc = foo
bar.tap do |bar|
bar.bignum = 3**64
bar.boolean = false
bar.date = 1.day.ago.to_date
bar.datetime = 1.day.ago.to_datetime
bar.float = 2.22
bar.integer = 2
bar.nil = ''
bar.string = 'zzz'
bar.symbol = :zzz
bar.time = 1.day.ago.to_time
end
bar.assoc = bar
end
let(:set) { enumerable_set }
describe '#process' do
subject { processor.process }
context 'with a complex query' do
context do
let(:filter_structure) do
{
string: :asc,
assoc: {
string: :asc
}
}
end
it { expect(subject.map(&:id)).to eq [foo.id, bar.id] }
end
context do
let(:filter_structure) do
{
string: :asc,
assoc: {
string: :desc
}
}
end
it { expect(subject.map(&:id)).to eq [bar.id, foo.id] }
end
end
end
end
context 'when set is ActiveRecord::Relation' do
include_context 'for active record sets'
let(:set) { active_record_set }
describe '#process' do
subject { processor.process }
context 'with a complex query' do
context do
let(:filter_structure) do
{
string: :asc,
assoc: {
string: :asc
}
}
end
it { expect(subject.map(&:id)).to eq [foo.id, bar.id] }
end
context do
let(:filter_structure) do
{
string: :asc,
assoc: {
string: :desc
}
}
end
it { expect(subject.map(&:id)).to eq [foo.id, bar.id] }
end
end
end
end
end
| |
Remove addressable gem, we don't need it | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'walmart_open/version'
Gem::Specification.new do |spec|
spec.name = "walmart_open"
spec.version = WalmartOpen::VERSION
spec.authors = ["Ngan Pham"]
spec.email = ["ngan@listia.com"]
spec.description = %q{Ruby implementation for Walmart Open API.}
spec.summary = %q{Ruby implementation for Walmart Open API}
spec.homepage = "https://github.com/listia/walmart_open"
spec.license = "MIT"
spec.files = Dir["{lib,spec}/**/*"].select { |f| File.file?(f) } +
%w(LICENSE.txt Rakefile README.md)
spec.test_files = spec.files.grep(%r{^spec/})
spec.require_paths = ["lib"]
spec.add_dependency "httparty", "~> 0.10"
spec.add_dependency "addressable", "~> 2.0"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec", "~> 3.0.0.beta1"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'walmart_open/version'
Gem::Specification.new do |spec|
spec.name = "walmart_open"
spec.version = WalmartOpen::VERSION
spec.authors = ["Ngan Pham"]
spec.email = ["ngan@listia.com"]
spec.description = %q{Ruby implementation for Walmart Open API.}
spec.summary = %q{Ruby implementation for Walmart Open API}
spec.homepage = "https://github.com/listia/walmart_open"
spec.license = "MIT"
spec.files = Dir["{lib,spec}/**/*"].select { |f| File.file?(f) } +
%w(LICENSE.txt Rakefile README.md)
spec.test_files = spec.files.grep(%r{^spec/})
spec.require_paths = ["lib"]
spec.add_dependency "httparty", "~> 0.10"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec", "~> 3.0.0.beta1"
end
|
Allow application name configuration, use reload | Capistrano::Configuration.instance.load do
namespace :puma do
namespace :upstart do
%w(start stop status).each do |t|
desc "Perform #{t} of the api_puma service"
task t, roles: :app, except: { no_release: true } do
sudo "#{t} api_puma"
end
end
desc 'Perform a restart of the api_puma service'
task :restart, roles: :app, except: { no_release: true } do
run <<-CMD
pid=`status api_puma | grep -o -E '[0-9]+'`;
if [ -z $pid ]; then
sudo start api_puma;
else
kill -USR1 $pid;
fi
CMD
end
end
end
end
| Capistrano::Configuration.instance.load do
set(:puma_application_name) { "#{application}_puma" }
namespace :puma do
namespace :upstart do
%w(reload start stop status).each do |t|
desc "Perform #{t} of the _puma service"
task t, roles: :app, except: { no_release: true } do
sudo "#{t} #{puma_application_name}"
end
end
desc 'Perform a restart of the application puma service'
task :restart, roles: :app, except: { no_release: true } do
run <<-CMD
pid=`status #{puma_application_name} | grep -o -E '[0-9]+'`;
if [ -z $pid ]; then
sudo start #{puma_application_name};
else
sudo reload #{puma_application_name};
fi
CMD
end
end
end
end
|
Drop support for unmaintained Ruby versions | require File.expand_path("../lib/htmlbeautifier/version", __FILE__)
spec = Gem::Specification.new do |s|
s.name = "htmlbeautifier"
s.version = HtmlBeautifier::VERSION::STRING
s.summary = "HTML/ERB beautifier"
s.description = "A normaliser/beautifier for HTML that also understands embedded Ruby."
s.author = "Paul Battley"
s.email = "pbattley@gmail.com"
s.homepage = "http://github.com/threedaymonk/htmlbeautifier"
s.license = "MIT"
s.files = %w(Rakefile README.md) + Dir.glob("{bin,test,lib}/**/*")
s.executables = Dir["bin/**"].map { |f| File.basename(f) }
s.require_paths = ["lib"]
s.required_ruby_version = '>= 1.9.2'
s.add_development_dependency "rake", "~> 0"
s.add_development_dependency "rspec", "~> 3"
s.add_development_dependency "rubocop", "~> 0.30.0"
end
| require File.expand_path("../lib/htmlbeautifier/version", __FILE__)
spec = Gem::Specification.new do |s|
s.name = "htmlbeautifier"
s.version = HtmlBeautifier::VERSION::STRING
s.summary = "HTML/ERB beautifier"
s.description = "A normaliser/beautifier for HTML that also understands embedded Ruby."
s.author = "Paul Battley"
s.email = "pbattley@gmail.com"
s.homepage = "http://github.com/threedaymonk/htmlbeautifier"
s.license = "MIT"
s.files = %w(Rakefile README.md) + Dir.glob("{bin,test,lib}/**/*")
s.executables = Dir["bin/**"].map { |f| File.basename(f) }
s.require_paths = ["lib"]
s.required_ruby_version = '>= 2.6.0'
s.add_development_dependency "rake", "~> 0"
s.add_development_dependency "rspec", "~> 3"
s.add_development_dependency "rubocop", "~> 0.30.0"
end
|
Add unit tests for validate_ip_address_array | # Rspec function: validate_ip_address_array
#
# This file is part of the test suite for the nsd module.
#
# === Authors
#
# Mario Finelli <mario@finel.li>
#
# === Copyright
#
# Copyright 2015 Mario Finelli
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'spec_helper'
describe 'the validate_ip_address_array function' do
before :all do
Puppet::Parser::Functions.autoloader.loadall
end
let(:scope) { PuppetlabsSpec::PuppetInternals.scope }
it 'should exist' do
expect(Puppet::Parser::Functions.function('validate_ip_address_array'))
.to eq('function_validate_ip_address_array')
end
it 'should raise a ParseError if there is less than 1 arguments' do
expect { scope.function_validate_ip_address_array([]) }
.to(raise_error(Puppet::ParseError))
end
end
| |
Use find instead of where | require 'hashie'
module Refinery
module Elasticsearch
class Result
def initialize(attributes={})
@result = Hashie::Mash.new(attributes)
end
def has_highlight?
@result.respond_to?(:highlight)
end
def klass
@klass ||= @result['_type'].gsub('-', '/').camelize.constantize
end
def record
@record ||= klass.where(id:@result['_id']).first
end
# Delegate methods to `@result` or `@result._source`
#
def method_missing(method_name, *arguments)
case
when @result.respond_to?(method_name.to_sym)
@result.__send__ method_name.to_sym, *arguments
when @result._source && @result._source.respond_to?(method_name.to_sym)
@result._source.__send__ method_name.to_sym, *arguments
else
super
end
end
# Respond to methods from `@result` or `@result._source`
#
def respond_to?(method_name, include_private = false)
@result.respond_to?(method_name.to_sym) || \
@result._source && @result._source.respond_to?(method_name.to_sym) || \
super
end
def as_json(options={})
@result.as_json(options)
end
end
end
end
| require 'hashie'
module Refinery
module Elasticsearch
class Result
def initialize(attributes={})
@result = Hashie::Mash.new(attributes)
end
def has_highlight?
@result.respond_to?(:highlight)
end
def klass
@klass ||= @result['_type'].gsub('-', '/').camelize.constantize
end
def record
@record ||= klass.find(@result['_id']) rescue nil
end
# Delegate methods to `@result` or `@result._source`
#
def method_missing(method_name, *arguments)
case
when @result.respond_to?(method_name.to_sym)
@result.__send__ method_name.to_sym, *arguments
when @result._source && @result._source.respond_to?(method_name.to_sym)
@result._source.__send__ method_name.to_sym, *arguments
else
super
end
end
# Respond to methods from `@result` or `@result._source`
#
def respond_to?(method_name, include_private = false)
@result.respond_to?(method_name.to_sym) || \
@result._source && @result._source.respond_to?(method_name.to_sym) || \
super
end
def as_json(options={})
@result.as_json(options)
end
end
end
end
|
Fix Rails 5 deprecation warning for skip_before_action | class WelcomeController < ApplicationController
skip_before_filter :authenticate_user!, only: [:index]
def index
end
def secure_page
end
end
| class WelcomeController < ApplicationController
skip_before_action :authenticate_user!, only: [:index]
def index
end
def secure_page
end
end
|
Make sure that global Launchy constant is used. | require "digest/sha1"
require "launchy"
module LetterOpener
class DeliveryMethod
class InvalidOption < StandardError; end
attr_accessor :settings
def initialize(options = {})
options[:message_template] ||= LetterOpener.configuration.message_template
options[:location] ||= LetterOpener.configuration.location
options[:file_uri_scheme] ||= LetterOpener.configuration.file_uri_scheme
raise InvalidOption, "A location option is required when using the Letter Opener delivery method" if options[:location].nil?
self.settings = options
end
def deliver!(mail)
validate_mail!(mail)
location = File.join(settings[:location], "#{Time.now.to_f.to_s.tr('.', '_')}_#{Digest::SHA1.hexdigest(mail.encoded)[0..6]}")
messages = Message.rendered_messages(mail, location: location, message_template: settings[:message_template])
Launchy.open("#{settings[:file_uri_scheme]}#{messages.first.filepath}")
end
private
def validate_mail!(mail)
if !mail.smtp_envelope_from || mail.smtp_envelope_from.empty?
raise ArgumentError, "SMTP From address may not be blank"
end
if !mail.smtp_envelope_to || mail.smtp_envelope_to.empty?
raise ArgumentError, "SMTP To address may not be blank"
end
end
end
end
| require "digest/sha1"
require "launchy"
module LetterOpener
class DeliveryMethod
class InvalidOption < StandardError; end
attr_accessor :settings
def initialize(options = {})
options[:message_template] ||= LetterOpener.configuration.message_template
options[:location] ||= LetterOpener.configuration.location
options[:file_uri_scheme] ||= LetterOpener.configuration.file_uri_scheme
raise InvalidOption, "A location option is required when using the Letter Opener delivery method" if options[:location].nil?
self.settings = options
end
def deliver!(mail)
validate_mail!(mail)
location = File.join(settings[:location], "#{Time.now.to_f.to_s.tr('.', '_')}_#{Digest::SHA1.hexdigest(mail.encoded)[0..6]}")
messages = Message.rendered_messages(mail, location: location, message_template: settings[:message_template])
::Launchy.open("#{settings[:file_uri_scheme]}#{messages.first.filepath}")
end
private
def validate_mail!(mail)
if !mail.smtp_envelope_from || mail.smtp_envelope_from.empty?
raise ArgumentError, "SMTP From address may not be blank"
end
if !mail.smtp_envelope_to || mail.smtp_envelope_to.empty?
raise ArgumentError, "SMTP To address may not be blank"
end
end
end
end
|
Remove comment if description is empty | require 'puppet/provider/parsedfile'
oratab = case Facter.value(:operatingsystem)
when 'Solaris'
'/var/opt/oracle/oratab'
else
'/etc/oratab'
end
Puppet::Type.type(:oratab).provide(:parsed, :parent => Puppet::Provider::ParsedFile, :default_target => oratab, :filetype => :flat) do
text_line :comment, :match => /^\s*#/
text_line :blank, :match => /^\s*$/
record_line :parsed, :fields => %w{name home atboot description},
:optional => %w{description},
:match => /^\s*(.*?):(.*?):(.*?)\s*(?:#\s*(.*))?$/,
:post_parse => proc { |h|
h[:atboot] = :yes if h[:atboot] == 'Y'
h[:atboot] = :no if h[:atboot] == 'N'
h
},
:pre_gen => proc { |h|
h[:atboot] = 'Y' if h[:atboot] == :yes
h[:atboot] = 'N' if h[:atboot] == :no
h
},
:to_line => proc { |h|
str = "#{h[:name]}:#{h[:home]}:#{h[:atboot]}"
if h[:description] and h[:description] != :absent
str += " # #{description}"
end
str
}
end
| require 'puppet/provider/parsedfile'
oratab = case Facter.value(:operatingsystem)
when 'Solaris'
'/var/opt/oracle/oratab'
else
'/etc/oratab'
end
Puppet::Type.type(:oratab).provide(:parsed, :parent => Puppet::Provider::ParsedFile, :default_target => oratab, :filetype => :flat) do
text_line :comment, :match => /^\s*#/
text_line :blank, :match => /^\s*$/
record_line :parsed, :fields => %w{name home atboot description},
:optional => %w{description},
:match => /^\s*(.*?):(.*?):(.*?)\s*(?:#\s*(.*))?$/,
:post_parse => proc { |h|
h[:atboot] = :yes if h[:atboot] == 'Y'
h[:atboot] = :no if h[:atboot] == 'N'
h
},
:pre_gen => proc { |h|
h[:atboot] = 'Y' if h[:atboot] == :yes
h[:atboot] = 'N' if h[:atboot] == :no
h
},
:to_line => proc { |h|
str = "#{h[:name]}:#{h[:home]}:#{h[:atboot]}"
if description = h[:description] and description != :absent and !description.empty?
str += " # #{description}"
end
str
}
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.