Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Check that the reuse times is 0 by default | require 'spec_helper'
min_key_length = 16
describe Invite do
before { @invite = Invite.new(:description => 'Test invite') }
subject { @invite }
it 'should always have a key of reasonable length after creation' do
subject.key.should_not be_empty
subject.key.should satisfy { |key| key.length > min_key_length }
end
it 'should require a description' do
invite = Invite.create(:description => '').should_not be_valid
end
it "should consider keys shorter than #{ min_key_length } to be invalid" do
subject.key = 'hello'
expect { subject.save! }.to raise_error(ActiveRecord::RecordInvalid)
end
end
| require 'spec_helper'
min_key_length = 16
describe Invite do
before { @invite = Invite.new(:description => 'Test invite') }
subject { @invite }
it 'should always have a key of reasonable length after creation' do
subject.key.should_not be_empty
subject.key.should satisfy { |key| key.length > min_key_length }
end
it 'should require a description' do
invite = Invite.create(:description => '').should_not be_valid
end
it "should consider keys shorter than #{ min_key_length } to be invalid" do
subject.key = 'hello'
expect { subject.save! }.to raise_error(ActiveRecord::RecordInvalid)
end
it 'can only be used once by default' do
subject.reuse_times.should eq(0)
end
end
|
Remove unnecessary begin & end statements | class PublishingApiDraftSectionDiscarder
def initialize(services)
@services = services
end
def call(section, _manual)
begin
@services.publishing_api_v2.discard_draft(section.id)
rescue GdsApi::HTTPNotFound, GdsApi::HTTPUnprocessableEntity # rubocop:disable Lint/HandleExceptions
end
end
end
| class PublishingApiDraftSectionDiscarder
def initialize(services)
@services = services
end
def call(section, _manual)
@services.publishing_api_v2.discard_draft(section.id)
rescue GdsApi::HTTPNotFound, GdsApi::HTTPUnprocessableEntity # rubocop:disable Lint/HandleExceptions
end
end
|
Add max column lengths to sanity check. | namespace :simple_sanity_check do
task run: :environment do
connection = ActiveRecord::Base.connection
table_names = TableExporter.new.send(:get_table_names, all: true)
file_path = "#{Rails.root}/tmp/sanity_check.txt"
counts = table_names.map do |table_name|
{
table_name: table_name,
count: connection.execute("select count(*) from #{table_name}").values.flatten.first,
table_width: connection.execute("select count(*) from information_schema.columns where table_name='#{table_name}'").values.flatten.first
}
end
File.open(file_path, 'w') do |file|
counts.sort_by {|count| count[:count].to_i}.reverse.each do |count|
file.write("#{count[:table_name]}: #{count[:count]} records. #{count[:table_width]} columns in table.\n")
end
end
s3 = Aws::S3::Resource.new(region: ENV['AWS_REGION'])
obj = s3.bucket(ENV['S3_BUCKET_NAME']).object("#{Date.today}-sanity-check.txt")
obj.upload_file(file_path)
end
end
| namespace :simple_sanity_check do
task run: :environment do
connection = ActiveRecord::Base.connection
table_names = TableExporter.new.send(:get_table_names, all: true)
file_path = "#{Rails.root}/tmp/sanity_check.txt"
column_max_lengths = table_names.inject({}) do |table_hash, table_name|
@table_name = table_name
if table_name == 'study_references'
@table_name = 'references'
end
begin
column_counts = @table_name.classify.constantize.column_names.inject({}) do |column_hash, column|
column_hash[column] = connection.execute("select max(length('#{column}')) from \"#{table_name}\"").values.flatten.first
column_hash
end
rescue NameError
puts "skipping table that doesnt have model: #{@table_name}"
end
table_hash[table_name] = column_counts
table_hash
end
counts = table_names.map do |table_name|
{
table_name: table_name,
count: connection.execute("select count(*) from #{table_name}").values.flatten.first,
column_max_lengths: column_max_lengths[table_name]
}
end
File.open(file_path, 'w') do |file|
counts.sort_by {|count| count[:count].to_i}.reverse.each do |count|
file.write("#{count[:table_name]}: #{count[:count]} records.\n Max column lengths for #{count[:table_name]} #{count[:column_max_lengths]}\n\n\n")
end
end
s3 = Aws::S3::Resource.new(region: ENV['AWS_REGION'])
obj = s3.bucket(ENV['S3_BUCKET_NAME']).object("#{Date.today}-sanity-check.txt")
obj.upload_file(file_path)
end
end
|
Add logger to tell about invalid secrets | # frozen_string_literal: true
class NotificationsController < ApplicationController
# generally dangerious but this controller holds webhooks
skip_before_action :verify_authenticity_token, only: [:coinbase, :mover]
def coinbase
# If the secret is incorrect, drop it like it's hot
unless params[:secret] == Rails.application.secrets.coinbase_webhook_secret
return render json: { success: false, message: 'Invalid secret' }
end
# If the secret's good, just keep going
address = params['data']['address']
amount = params['additional_data']['amount']['amount']
coinbase_id = params['additional_data']['transaction']['id']
btc_address = BtcAddress.find_by(address: address)
btc_address.btc_txes << BtcTx.new(amount: amount, coinbase_id: coinbase_id)
render json: { success: true, message: 'Transaction noted' }
end
def mover
unless params[:secret] == Rails.application.secrets.mover_webhook_secret
return render json: { success: false, message: 'Invalid secret' }
end
# If the secret's good, just keep going
UpdateBtcTxStatusJob.perform_now
end
end
| # frozen_string_literal: true
class NotificationsController < ApplicationController
# generally dangerious but this controller holds webhooks
skip_before_action :verify_authenticity_token, only: [:coinbase, :mover]
def coinbase
# If the secret is incorrect, drop it like it's hot
unless params[:secret] == Rails.application.secrets.coinbase_webhook_secret
return render json: { success: false, message: 'Invalid secret' }
end
# If the secret's good, just keep going
address = params['data']['address']
amount = params['additional_data']['amount']['amount']
coinbase_id = params['additional_data']['transaction']['id']
btc_address = BtcAddress.find_by(address: address)
btc_address.btc_txes << BtcTx.new(amount: amount, coinbase_id: coinbase_id)
render json: { success: true, message: 'Transaction noted' }
end
def mover
unless params[:secret] == Rails.application.secrets.mover_webhook_secret
logger.info('Invalid secret for mover recieved', params[:secret])
return render json: { success: false, message: 'Invalid secret' }
end
# If the secret's good, just keep going
UpdateBtcTxStatusJob.perform_now
end
end
|
Add delete method type to cors | require File.expand_path('../boot', __FILE__)
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 ShowTracker2
class Application < Rails::Application
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
# 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.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| require File.expand_path('../boot', __FILE__)
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 ShowTracker2
class Application < Rails::Application
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options, :delete]
end
end
# 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.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
|
Add specs for stage update worker | require 'spec_helper'
describe StageUpdateWorker do
describe '#perform' do
context 'when stage exists' do
let(:stage) { create(:ci_stage_entity) }
it 'updates stage status' do
expect_any_instance_of(Ci::Stage).to receive(:update_status)
described_class.new.perform(stage.id)
end
end
context 'when stage does not exist' do
it 'does not raise exception' do
expect { described_class.new.perform(123) }
.not_to raise_error
end
end
end
end
| |
Improve handling of application.yml and env vars | # Load the Rails application.
require File.expand_path('../application', __FILE__)
require File.expand_path('../settings', __FILE__)
# Set ENV vars to defaults in application.yml
StarterKit::Settings.env.each do |k, v|
ENV[k] ||= v
end
# Initialize the Rails application.
Rails.application.initialize!
| # Load the Rails application.
require File.expand_path('../application', __FILE__)
require File.expand_path('../settings', __FILE__)
# Set ENV vars to defaults in application.yml
StarterKit::Settings.env.each do |k, v|
ENV[k] ||= (v.blank? ? '' : v.to_s)
end
# Initialize the Rails application.
Rails.application.initialize!
|
Switch to non-force deploy. Link tmp to shared folder. | #
# Cookbook Name:: lttapp
# Recipe:: default
#
# Copyright 2013, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
node.override['nginx']['install_method'] = 'source'
node.override['nginx']['default_site_enabled'] = false
include_recipe "nginx"
template "#{node['nginx']['dir']}/sites-available/target_site" do
source "nginx.conf.erb"
mode "0644"
end
nginx_site "target_site", :enable => true, :notifies => :immediately
directory "#{node[:application_path]}/shared/tmp" do
recursive true
end
application "lttapp" do
action :force_deploy
path node[:application_path]
owner "brain"
group "brain"
repository "git://github.com/brain-geek/load_test_target_app.git"
revision "master"
symlinks 'tmp' => 'tmp'
restart_command "cd #{node[:application_path]}/current && bundle exec rake unicorn:stop prepare_data ; sleep 3 && bundle exec rake unicorn:start"
rails do
database_template "database_sqlite.yml.erb"
bundler true
bundler_deployment true
precompile_assets true
end
end | #
# Cookbook Name:: lttapp
# Recipe:: default
#
# Copyright 2013, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
node.override['nginx']['install_method'] = 'source'
node.override['nginx']['default_site_enabled'] = false
include_recipe "nginx"
template "#{node['nginx']['dir']}/sites-available/target_site" do
source "nginx.conf.erb"
mode "0644"
end
nginx_site "target_site", :enable => true, :notifies => :immediately
application "lttapp" do
action :deploy
path node[:application_path]
owner "brain"
group "brain"
repository "git://github.com/brain-geek/load_test_target_app.git"
revision "master"
restart_command "cd #{node[:application_path]}/current && bundle exec rake unicorn:stop prepare_data ; sleep 3 && bundle exec rake unicorn:start"
rails do
database_template "database_sqlite.yml.erb"
bundler true
bundler_deployment true
precompile_assets true
end
before_migrate do
Chef::Log.info "Linking tmp"
directory "#{new_resource.path}/shared/tmp" do
owner new_resource.owner
group new_resource.group
mode '0755'
end
execute "rm -rf tmp" do
cwd new_resource.release_path
user new_resource.owner
environment new_resource.environment
end
link "#{new_resource.release_path}/tmp" do
to "#{new_resource.path}/shared/tmp"
end
end
end |
Use --local for bundler in CI | #!/usr/bin/env ruby
def bundle_without
ENV['HAS_JOSH_K_SEAL_OF_APPROVAL'] ? "--without development" : "" # aka: on travis
end
def run_build(build)
p "-----#{build}-----"
system("cd #{build} && bundle exec rspec spec") || raise(build)
end
system("bundle check || bundle #{bundle_without}")
if ENV['SUITE'] == "integration"
run_build('integration_tests')
else
builds = Dir['*'].select {|f| File.directory?(f) && File.exists?("#{f}/spec")}
builds -= ['bat']
builds -= ['integration_tests'] if ENV['SUITE'] == "unit"
redis_pid = fork { exec("redis-server --port 63790") }
at_exit { Process.kill("KILL", redis_pid) }
builds.each do |build|
run_build(build)
end
end
| #!/usr/bin/env ruby
def bundle_without
ENV['HAS_JOSH_K_SEAL_OF_APPROVAL'] ? "--local --without development" : "" # aka: on travis
end
def run_build(build)
p "-----#{build}-----"
system("cd #{build} && bundle exec rspec spec") || raise(build)
end
system("bundle check || bundle #{bundle_without}")
if ENV['SUITE'] == "integration"
run_build('integration_tests')
else
builds = Dir['*'].select {|f| File.directory?(f) && File.exists?("#{f}/spec")}
builds -= ['bat']
builds -= ['integration_tests'] if ENV['SUITE'] == "unit"
redis_pid = fork { exec("redis-server --port 63790") }
at_exit { Process.kill("KILL", redis_pid) }
builds.each do |build|
run_build(build)
end
end
|
Use object equality rather == to check for singleton DB_DEFAULT. | module SchemaPlus
module ActiveRecord
module Attribute
def self.included(base)
base.alias_method_chain :original_value, :schema_plus
end
def original_value_with_schema_plus
# prevent attempts to cast DB_DEFAULT to the attributes type.
# We want to keep it as DB_DEFAULT so that we can handle it when
# generating the sql.
return DB_DEFAULT if value_before_type_cast == DB_DEFAULT
original_value_without_schema_plus
end
end
end
end
| module SchemaPlus
module ActiveRecord
module Attribute
def self.included(base)
base.alias_method_chain :original_value, :schema_plus
end
def original_value_with_schema_plus
# prevent attempts to cast DB_DEFAULT to the attributes type.
# We want to keep it as DB_DEFAULT so that we can handle it when
# generating the sql.
return DB_DEFAULT if value_before_type_cast.equal? DB_DEFAULT
original_value_without_schema_plus
end
end
end
end
|
Add seed data for charities | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
| # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
charity_data = [["EFF", "eff.png"], ["Child's Play", "childsplay.png"], ["Red Cross", "redcross.png"], ["Oxfam", "oxfam.png"], ["Greenpeace", "greenpeace.png"]]
charity_data.each do |data|
Charity.create(name: data[0], image_name: data[1])
end
|
Add GitHub repo to gemspec as homepage | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'clearwater/version'
Gem::Specification.new do |spec|
spec.name = "clearwater"
spec.version = Clearwater::VERSION
spec.authors = ["Jamie Gaskins"]
spec.email = ["jgaskins@gmail.com"]
spec.summary = %q{Front-end web framework built on Opal}
spec.description = %q{Front-end web framework built on Opal}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency 'opal', '~> 0.7.0.beta1'
spec.add_dependency 'sprockets'
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'clearwater/version'
Gem::Specification.new do |spec|
spec.name = "clearwater"
spec.version = Clearwater::VERSION
spec.authors = ["Jamie Gaskins"]
spec.email = ["jgaskins@gmail.com"]
spec.summary = %q{Front-end web framework built on Opal}
spec.description = %q{Front-end web framework built on Opal}
spec.homepage = "https://github.com/jgaskins/clearwater"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency 'opal', '~> 0.7.0.beta1'
spec.add_dependency 'sprockets'
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
end
|
Fix valid on Certificates to really get all valid certs | module CloudModel
class Certificate
include Mongoid::Document
include Mongoid::Timestamps
include CloudModel::UsedInGuestsAs
field :name, type: String
field :ca, type: String
field :key, type: String
field :crt, type: String
field :valid_thru, type: Date
#has_many :services
used_in_guests_as 'services.ssl_cert_id'
scope :valid, -> { where(:valid_thru.gt => Time.now) }
def to_s
name
end
def x509
begin
OpenSSL::X509::Certificate.new crt
rescue
OpenSSL::X509::Certificate.new
end
end
def pkey
OpenSSL::PKey.read key
end
def valid_from
x509.not_before
end
def valid_thru
x509.not_after
end
def common_name
unless x509.subject.to_a.blank?
x509.subject.to_a.find{|x| x[0] == "CN"}[1]
end
end
def issuer
unless x509.issuer.to_a.blank?
x509.issuer.to_a.find{|x| x[0] == "CN"}[1]
end
end
def check_key
x509.check_private_key pkey
end
end
end | module CloudModel
class Certificate
include Mongoid::Document
include Mongoid::Timestamps
include CloudModel::UsedInGuestsAs
field :name, type: String
field :ca, type: String
field :key, type: String
field :crt, type: String
field :valid_thru, type: Date
#has_many :services
used_in_guests_as 'services.ssl_cert_id'
#scope :valid, -> { where(:valid_thru.gt => Time.now) }
def self.valid
all.select{|c| c.valid_now?}
end
def to_s
name
end
def x509
begin
OpenSSL::X509::Certificate.new crt
rescue
OpenSSL::X509::Certificate.new
end
end
def pkey
OpenSSL::PKey.read key
end
def valid_from
x509.not_before
end
def valid_thru
x509.not_after
end
def valid_now?
valid_from < Time.now and Time.now < valid_thru
end
def common_name
unless x509.subject.to_a.blank?
x509.subject.to_a.find{|x| x[0] == "CN"}[1]
end
end
def issuer
unless x509.issuer.to_a.blank?
x509.issuer.to_a.find{|x| x[0] == "CN"}[1]
end
end
def check_key
x509.check_private_key pkey
end
end
end |
Update development dependencies to fix travis build | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'fit/version'
Gem::Specification.new do |spec|
spec.name = "fit-parser"
spec.version = Fit::VERSION
spec.authors = ["Jeff Wallace"]
spec.email = ["jeff@tjwallace.ca"]
spec.description = %q{Ruby gem for reading Garmin FIT files}
spec.summary = %q{Ruby gem for reading Garmin FIT files}
spec.homepage = "https://github.com/tjwallace/fit"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "bindata", "~> 2.1.0"
spec.add_dependency "activesupport", "~> 4.2.0"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec", "~> 3.2.0"
spec.add_development_dependency "rspec-its"
spec.add_development_dependency "simplecov"
spec.add_development_dependency "pry"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'fit/version'
Gem::Specification.new do |spec|
spec.name = "fit-parser"
spec.version = Fit::VERSION
spec.authors = ["Jeff Wallace"]
spec.email = ["jeff@tjwallace.ca"]
spec.description = %q{Ruby gem for reading Garmin FIT files}
spec.summary = %q{Ruby gem for reading Garmin FIT files}
spec.homepage = "https://github.com/tjwallace/fit"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "bindata", "~> 2.1.0"
spec.add_dependency "activesupport", "~> 4.2.0"
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec", "~> 3.5.0"
spec.add_development_dependency "rspec-its"
spec.add_development_dependency "simplecov"
spec.add_development_dependency "pry"
end
|
Delete single and double period | module InteractiveS3::Commands
module InternalCommand
def self.fetch(name, default = nil)
COMMAND_CLASSES.fetch(name, default)
end
class Chdir < Base
def execute
state[:previous_stack] ||= []
if target.nil?
state[:previous_stack] = s3.stack
s3.reset
return
end
if target.strip == '-'
s3.stack, state[:previous_stack] = state[:previous_stack], s3.stack
else
target.sub!('s3://', '/')
state[:previous_stack] = s3.stack
s3.stack = InteractiveS3::S3Path.new(target, s3.stack).resolve
end
ensure
unless s3.exist?
s3.stack = state[:previous_stack]
end
end
private
def target
@target ||= arguments.first
end
end
class LocalList < Base
def execute
puts Dir.entries('.')
end
end
class Pwd < Base
def execute
puts s3.root? ? '/' : s3.current_path
end
end
class Exit < Base
def execute
exit
end
end
COMMAND_CLASSES = {
cd: Chdir,
lls: LocalList,
pwd: Pwd,
exit: Exit,
}.freeze
end
end
| module InteractiveS3::Commands
module InternalCommand
def self.fetch(name, default = nil)
COMMAND_CLASSES.fetch(name, default)
end
class Chdir < Base
def execute
state[:previous_stack] ||= []
if target.nil?
state[:previous_stack] = s3.stack
s3.reset
return
end
if target.strip == '-'
s3.stack, state[:previous_stack] = state[:previous_stack], s3.stack
else
target.sub!('s3://', '/')
state[:previous_stack] = s3.stack
s3.stack = InteractiveS3::S3Path.new(target, s3.stack).resolve
end
ensure
unless s3.exist?
s3.stack = state[:previous_stack]
end
end
private
def target
@target ||= arguments.first
end
end
class LocalList < Base
def execute
puts Dir.entries('.').delete_if {|file| file =~ /^(.|..)$/ }
end
end
class Pwd < Base
def execute
puts s3.root? ? '/' : s3.current_path
end
end
class Exit < Base
def execute
exit
end
end
COMMAND_CLASSES = {
cd: Chdir,
lls: LocalList,
pwd: Pwd,
exit: Exit,
}.freeze
end
end
|
Add a pagefile inspec test | describe file('C:\pagefile.sys') do
it { should exist }
end
describe command('wmic pagefileset') do
its('exit_status') { should eq 0 } # if it was system managed it would be 1
its('stderr') { should_not match (/No Instance\(s\) Available/) } # not system managed
end
| |
Add Batch class with properties, XML response for reference for other properties left to implement and create method. | module SalesforceBulk
class Batch
attr_reader :client
attr_accessor :data
attr_accessor :id
attr_accessor :jobId
attr_accessor :state
# <id>751D0000000004rIAA</id>
# <jobId>750D0000000002lIAA</jobId>
# <state>InProgress</state>
# <createdDate>2009-04-14T18:15:59.000Z</createdDate>
# <systemModstamp>2009-04-14T18:15:59.000Z</systemModstamp>
# <numberRecordsProcessed>0</numberRecordsProcessed>
def initialize(client)
@client = client
end
def create(job)
if data.is_a? String
# query
else
# all other operations
#keys = data.reduce({}) {|h,pairs| puts 'reduce'; pairs.each {|k,v| puts 'pairs.each'; (h[k] ||= []) << v}; h}.keys
keys = data.first.keys
output_csv = keys.to_csv
#puts "", keys.inspect,"",""
data.each do |item|
item_values = keys.map { |key| item[key] }
output_csv += item_values.to_csv
end
headers = {"Content-Type" => "text/csv; charset=UTF-8"}
#puts "","",output_csv,"",""
response = @client.http_post("job/#{job.id}123/batch/", output_csv, headers)
puts "","",response,"",""
raise SalesforceError.new(response) unless response.is_a?(Net::HTTPSuccess)
result = XmlSimple.xml_in(response.body, 'ForceArray' => false)
puts "","",result,"",""
@id = result["id"]
@state = result["state"]
end
end
end
end | |
Remove new method test for submission controller spec | require "rails_helper"
RSpec.describe SubmissionsController, type: :controller do
describe "GET #new" do
it "returns http success" do
get :new
expect(response).to have_http_status(:success)
end
end
describe "POST #create" do
subject { post :create, submission: submission_attributes }
context "with vaild submission parameters" do
let(:submission_attributes) do
FactoryGirl.attributes_for(:submission)
end
it "redirects to thank you page" do
expect(subject).to redirect_to("/submissions/thank_you")
end
it "saves the new submission" do
expect{subject}.to change(Submission, :count).by(1)
end
end
context "with invaild submission parameters" do
let(:submission_attributes) do
{ full_name: "NN", email: "nn", age: 200 }
end
it "shows form again" do
expect(subject).to render_template(:new)
end
it "does not save the new submission" do
expect{subject}.not_to change(Submission, :count)
end
end
end
end
| require "rails_helper"
RSpec.describe SubmissionsController, type: :controller do
describe "POST #create" do
subject { post :create, submission: submission_attributes }
context "with vaild submission parameters" do
let(:submission_attributes) do
FactoryGirl.attributes_for(:submission)
end
it "redirects to thank you page" do
expect(subject).to redirect_to("/submissions/thank_you")
end
it "saves the new submission" do
expect{subject}.to change(Submission, :count).by(1)
end
end
context "with invaild submission parameters" do
let(:submission_attributes) do
{ full_name: "NN", email: "nn", age: 200 }
end
it "shows form again" do
expect(subject).to render_template(:new)
end
it "does not save the new submission" do
expect{subject}.not_to change(Submission, :count)
end
end
end
end
|
Update max links per file to be 50000 |
require 'simple_sitemap/generators/base'
require 'simple_sitemap/generators/index'
require 'simple_sitemap/generators/sitemap'
require 'simple_sitemap/writers/gzip_writer'
require 'simple_sitemap/writers/plain_writer'
require 'simple_sitemap/version'
module SimpleSitemap
MAX_LINKS_PER_FILE = 10000
MAX_FILE_SIZE = 10*1024*1024 # 10 megabytes
class << self
attr_accessor :config, :hooks
def configure(&block)
@config = OpenStruct.new
@config.gzip = true
@config.verbose = false
yield @config
end
def build(opts={}, &block)
start_time = Time.now
generator = Generators::Sitemap.new @config, @hooks
generator.instance_eval &block
generator.write!
puts "Time taken: #{Time.now - start_time}" if @config.verbose
end
def after_write(&block)
@hooks ||= {}
@hooks[:after_write] = block
end
end
end
|
require 'simple_sitemap/generators/base'
require 'simple_sitemap/generators/index'
require 'simple_sitemap/generators/sitemap'
require 'simple_sitemap/writers/gzip_writer'
require 'simple_sitemap/writers/plain_writer'
require 'simple_sitemap/version'
module SimpleSitemap
MAX_LINKS_PER_FILE = 50000
MAX_FILE_SIZE = 10*1024*1024 # 10 megabytes
class << self
attr_accessor :config, :hooks
def configure(&block)
@config = OpenStruct.new
@config.gzip = true
@config.verbose = false
yield @config
end
def build(opts={}, &block)
start_time = Time.now
generator = Generators::Sitemap.new @config, @hooks
generator.instance_eval &block
generator.write!
puts "Time taken: #{Time.now - start_time}" if @config.verbose
end
def after_write(&block)
@hooks ||= {}
@hooks[:after_write] = block
end
end
end
|
Update dependency to most recent gerrit cookbook | name "site-reviewtypo3org"
maintainer "Steffen Gebert / TYPO3 Association"
maintainer_email "steffen.gebert@typo3.org"
license "Apache 2.0"
description "Installs/configures something"
version "0.1.30"
depends "ssh", "= 0.6.6"
depends "ssl_certificates", "= 1.1.3"
depends "t3-gerrit", "= 0.4.26"
depends "t3-chef-vault", "= 1.0.1"
depends "apt", "= 2.7.0"
depends "runit"
| name "site-reviewtypo3org"
maintainer "Steffen Gebert / TYPO3 Association"
maintainer_email "steffen.gebert@typo3.org"
license "Apache 2.0"
description "Installs/configures something"
version "0.1.30"
depends "ssh", "= 0.6.6"
depends "ssl_certificates", "= 1.1.3"
depends "t3-gerrit", "= 0.4.27"
depends "t3-chef-vault", "= 1.0.1"
depends "apt", "= 2.7.0"
depends "runit"
|
Add Swift Versions to podspec file | Pod::Spec.new do |s|
s.name = "RxAppState"
s.version = "1.5.1"
s.summary = "Handy RxSwift extensions to observe your app's state and view controllers' view-related notifications"
s.description = <<-DESC
Transform the state of your App and UIViewController's view-related notifications into RxSwift Observables. Including convenience Observables for common scenarios.
DESC
s.homepage = "https://github.com/pixeldock/RxAppState"
s.license = 'MIT'
s.author = { "Jörn Schoppe" => "joern@pixeldock.com" }
s.source = { :git => "https://github.com/pixeldock/RxAppState.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/pixeldock'
s.ios.deployment_target = '8.0'
s.requires_arc = true
s.source_files = 'Pod/Classes/**/*'
s.frameworks = 'Foundation'
s.dependency 'RxSwift', '~> 5.0'
s.dependency 'RxCocoa', '~> 5.0'
end
| Pod::Spec.new do |s|
s.name = "RxAppState"
s.version = "1.5.1"
s.swift_versions = ['5.0']
s.summary = "Handy RxSwift extensions to observe your app's state and view controllers' view-related notifications"
s.description = <<-DESC
Transform the state of your App and UIViewController's view-related notifications into RxSwift Observables. Including convenience Observables for common scenarios.
DESC
s.homepage = "https://github.com/pixeldock/RxAppState"
s.license = 'MIT'
s.author = { "Jörn Schoppe" => "joern@pixeldock.com" }
s.source = { :git => "https://github.com/pixeldock/RxAppState.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/pixeldock'
s.ios.deployment_target = '8.0'
s.requires_arc = true
s.source_files = 'Pod/Classes/**/*'
s.frameworks = 'Foundation'
s.dependency 'RxSwift', '~> 5.0'
s.dependency 'RxCocoa', '~> 5.0'
end
|
Handle ':memory:' database name -- JDBC just wants an empty string | # Don't need to load native sqlite3 adapter
$LOADED_FEATURES << "active_record/connection_adapters/sqlite_adapter.rb"
$LOADED_FEATURES << "active_record/connection_adapters/sqlite3_adapter.rb"
class ActiveRecord::Base
class << self
def sqlite3_connection(config)
require "arjdbc/sqlite3"
parse_sqlite3_config!(config)
config[:url] ||= "jdbc:sqlite:#{config[:database]}"
config[:driver] ||= "org.sqlite.JDBC"
config[:adapter_class] = ActiveRecord::ConnectionAdapters::SQLite3Adapter
jdbc_connection(config)
end
def parse_sqlite3_config!(config)
config[:database] ||= config[:dbfile]
# Allow database path relative to RAILS_ROOT, but only if
# the database path is not the special path that tells
# Sqlite to build a database only in memory.
rails_root_defined = defined?(Rails.root) || Object.const_defined?(:RAILS_ROOT)
if rails_root_defined && ':memory:' != config[:database]
rails_root = defined?(Rails.root) ? Rails.root : RAILS_ROOT
config[:database] = File.expand_path(config[:database], rails_root)
end
end
alias_method :jdbcsqlite3_connection, :sqlite3_connection
end
end
| # Don't need to load native sqlite3 adapter
$LOADED_FEATURES << "active_record/connection_adapters/sqlite_adapter.rb"
$LOADED_FEATURES << "active_record/connection_adapters/sqlite3_adapter.rb"
class ActiveRecord::Base
class << self
def sqlite3_connection(config)
require "arjdbc/sqlite3"
parse_sqlite3_config!(config)
database = config[:database]
database = '' if database == ':memory:'
config[:url] ||= "jdbc:sqlite:#{database}"
config[:driver] ||= "org.sqlite.JDBC"
config[:adapter_class] = ActiveRecord::ConnectionAdapters::SQLite3Adapter
jdbc_connection(config)
end
def parse_sqlite3_config!(config)
config[:database] ||= config[:dbfile]
# Allow database path relative to RAILS_ROOT, but only if
# the database path is not the special path that tells
# Sqlite to build a database only in memory.
rails_root_defined = defined?(Rails.root) || Object.const_defined?(:RAILS_ROOT)
if rails_root_defined && ':memory:' != config[:database]
rails_root = defined?(Rails.root) ? Rails.root : RAILS_ROOT
config[:database] = File.expand_path(config[:database], rails_root)
end
end
alias_method :jdbcsqlite3_connection, :sqlite3_connection
end
end
|
Send create and update date on API response. | # == Schema Information
#
# Table name: change_payloads
#
# id :integer not null, primary key
# payload :json
# changeset_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_change_payloads_on_changeset_id (changeset_id)
#
class ChangePayloadSerializer < ApplicationSerializer
attributes :id, :changeset_id, :payload
end
| # == Schema Information
#
# Table name: change_payloads
#
# id :integer not null, primary key
# payload :json
# changeset_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_change_payloads_on_changeset_id (changeset_id)
#
class ChangePayloadSerializer < ApplicationSerializer
attributes :id,
:created_at,
:updated_at,
:changeset_id,
:payload
end
|
Make node types not sortable for category names. | ActiveAdmin.register NodeType do
filter :category, :as => :select, :collection => proc { Category.all.inject([]){|memo,r| memo << [r.name, r.id]; memo} }
filter :identifier
filter :osm_key
filter :osm_value
filter :alt_osm_key
filter :alt_osm_value
filter :created_at
filter :updated_at
controller do
def update
region = resource
region.update_attributes(params[:node_type])
super
end
end
index do
column :id
column :icon do |node_type|
image_tag("/icons/#{node_type.icon}")
end
column :name
column :category
column :osm_key do |node_type|
link_to node_type.osm_key, "http://wiki.openstreetmap.org/wiki/Key:#{node_type.osm_key}", :target => '_blank'
end
column :osm_value do |node_type|
link_to node_type.osm_value, "http://wiki.openstreetmap.org/wiki/Tag:#{node_type.osm_key}%3D#{node_type.osm_value}", :target => '_blank'
end
default_actions
end
end | ActiveAdmin.register NodeType do
filter :category, :as => :select, :collection => proc { Category.all.inject([]){|memo,r| memo << [r.name, r.id]; memo} }
filter :identifier
filter :osm_key
filter :osm_value
filter :alt_osm_key
filter :alt_osm_value
filter :created_at
filter :updated_at
controller do
def update
region = resource
region.update_attributes(params[:node_type])
super
end
end
index do
column :id
column :icon do |node_type|
image_tag("/icons/#{node_type.icon}")
end
column :name, :sortable => false
column :category, :sortable => false
column :osm_key, :sortable => :osm_key do |node_type|
link_to node_type.osm_key, "http://wiki.openstreetmap.org/wiki/Key:#{node_type.osm_key}", :target => '_blank'
end
column :osm_value, :sortable => :osm_value do |node_type|
link_to node_type.osm_value, "http://wiki.openstreetmap.org/wiki/Tag:#{node_type.osm_key}%3D#{node_type.osm_value}", :target => '_blank'
end
default_actions
end
end |
Use `.build` instead of `.new` on promotion_codes | # frozen_string_literal: true
require 'csv'
module Spree
module Admin
class PromotionCodesController < Spree::Admin::ResourceController
def index
@promotion = Spree::Promotion.accessible_by(current_ability, :read).find(params[:promotion_id])
@promotion_codes = @promotion.promotion_codes.order(:value)
respond_to do |format|
format.html do
@promotion_codes = @promotion_codes.page(params[:page]).per(50)
end
format.csv do
filename = "promotion-code-list-#{@promotion.id}.csv"
headers["Content-Type"] = "text/csv"
headers["Content-disposition"] = "attachment; filename=\"#{filename}\""
end
end
end
def new
@promotion = Spree::Promotion.accessible_by(current_ability, :read).find(params[:promotion_id])
@promotion_code = @promotion.promotion_codes.new
end
def create
@promotion = Spree::Promotion.accessible_by(current_ability, :read).find(params[:promotion_id])
@promotion_code = @promotion.promotion_codes.new(value: params[:promotion_code][:value])
if @promotion_code.save
flash[:success] = flash_message_for(@promotion_code, :successfully_created)
redirect_to admin_promotion_promotion_codes_url(@promotion)
else
flash.now[:error] = @promotion_code.errors.full_messages.to_sentence
render_after_create_error
end
end
end
end
end
| # frozen_string_literal: true
require 'csv'
module Spree
module Admin
class PromotionCodesController < Spree::Admin::ResourceController
def index
@promotion = Spree::Promotion.accessible_by(current_ability, :read).find(params[:promotion_id])
@promotion_codes = @promotion.promotion_codes.order(:value)
respond_to do |format|
format.html do
@promotion_codes = @promotion_codes.page(params[:page]).per(50)
end
format.csv do
filename = "promotion-code-list-#{@promotion.id}.csv"
headers["Content-Type"] = "text/csv"
headers["Content-disposition"] = "attachment; filename=\"#{filename}\""
end
end
end
def new
@promotion = Spree::Promotion.accessible_by(current_ability, :read).find(params[:promotion_id])
@promotion_code = @promotion.promotion_codes.build
end
def create
@promotion = Spree::Promotion.accessible_by(current_ability, :read).find(params[:promotion_id])
@promotion_code = @promotion.promotion_codes.build(value: params[:promotion_code][:value])
if @promotion_code.save
flash[:success] = flash_message_for(@promotion_code, :successfully_created)
redirect_to admin_promotion_promotion_codes_url(@promotion)
else
flash.now[:error] = @promotion_code.errors.full_messages.to_sentence
render_after_create_error
end
end
end
end
end
|
Fix after_sign_in action to work with locale params | class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :set_locale
helper_method :current_user, :destroy_user
def after_sign_in_path_for(resource)
sign_in_url = if resource.is_a?(Epix::User)
new_epix_user_session_url
else
new_sapi_user_session_url
end
referer_index = if request.referer.index('?')
request.referer.index('?') - 1
else
request.referer.size
end
if request.referer.slice(0..(referer_index)) == sign_in_url
annual_report_uploads_path
else
stored_location_for(resource) || request.referer || root_path
end
end
def current_user
current_epix_user || current_sapi_user
end
def destroy_user
if current_epix_user
destroy_epix_user_session_path
elsif current_sapi_user
destroy_sapi_user_session_path
end
end
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def default_url_options
{ locale: I18n.locale }
end
end
| class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :set_locale
helper_method :current_user, :destroy_user
def after_sign_in_path_for(resource)
sign_in_url = if resource.is_a?(Epix::User)
new_epix_user_session_url
else
new_sapi_user_session_url
end.split('?').first
referer_index = if request.referer.index('?')
request.referer.index('?') - 1
else
request.referer.size
end
if request.referer.slice(0..(referer_index)) == sign_in_url
annual_report_uploads_path
else
stored_location_for(resource) || request.referer || root_path
end
end
def current_user
current_epix_user || current_sapi_user
end
def destroy_user
if current_epix_user
destroy_epix_user_session_path
elsif current_sapi_user
destroy_sapi_user_session_path
end
end
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def default_url_options
{ locale: I18n.locale }
end
end
|
Rename leader to replica in MigrationPlan | # encoding: utf-8
module Ktl
class MigrationPlan
def initialize(zk_client, old_leader, new_leader, options = {})
@zk_client = zk_client
@old_leader = old_leader.to_java
@new_leader = new_leader.to_java
@options = options
@logger = options[:logger] || NullLogger.new
@log_plan = !!options[:log_plan]
end
def generate
plan = Scala::Collection::Map.empty
topics = @zk_client.all_topics
assignments = ScalaEnumerable.new(@zk_client.replica_assignment_for_topics(topics))
assignments.each do |item|
topic_partition = item.first
replicas = item.last
if replicas.contains?(@old_leader)
index = replicas.index_of(@old_leader)
new_replicas = replicas.updated(index, @new_leader, CanBuildFrom)
@logger.info "Moving #{topic_partition.topic},#{topic_partition.partition} from #{replicas} to #{new_replicas}" if @log_plan
plan += Scala::Tuple.new(topic_partition, new_replicas)
end
end
plan
end
end
end
| # encoding: utf-8
module Ktl
class MigrationPlan
def initialize(zk_client, old_replica, new_replica, options = {})
@zk_client = zk_client
@old_replica = old_replica.to_java
@new_replica = new_replica.to_java
@options = options
@logger = options[:logger] || NullLogger.new
@log_plan = !!options[:log_plan]
end
def generate
plan = Scala::Collection::Map.empty
topics = @zk_client.all_topics
assignments = ScalaEnumerable.new(@zk_client.replica_assignment_for_topics(topics))
assignments.each do |item|
topic_partition = item.first
replicas = item.last
if replicas.contains?(@old_replica)
index = replicas.index_of(@old_replica)
new_replicas = replicas.updated(index, @new_replica, CanBuildFrom)
@logger.info "Moving #{topic_partition.topic},#{topic_partition.partition} from #{replicas} to #{new_replicas}" if @log_plan
plan += Scala::Tuple.new(topic_partition, new_replicas)
end
end
plan
end
end
end
|
Make it work with ActiveRecord Array proxies when using association with collections. | module ShowFor
module Content
def content(value, options={}, apply_options=true, &block)
if value.blank? && value != false
value = options.delete(:if_blank) || I18n.t(:'show_for.blank', :default => "Not specified")
options[:class] = [options[:class], ShowFor.blank_content_class].join(' ')
end
content = case value
when Date, Time, DateTime
I18n.l value, :format => options.delete(:format) || ShowFor.i18n_format
when TrueClass
I18n.t :"show_for.yes", :default => "Yes"
when FalseClass
I18n.t :"show_for.no", :default => "No"
when Array, Hash
collection_handler(value, options, &block)
when Proc
@template.capture(&value)
when NilClass
""
else
value
end
options[:content_html] = options.dup if apply_options
wrap_with(:content, content, options)
end
protected
def collection_handler(value, options, &block) #:nodoc:
iterator = collection_block?(block) ? block : ShowFor.default_collection_proc
response = ""
value.each do |item|
response << template.capture(item, &iterator)
end
wrap_with(:collection, response.html_safe, options)
end
end
end | module ShowFor
module Content
def content(value, options={}, apply_options=true, &block)
if value.blank? && value != false
value = options.delete(:if_blank) || I18n.t(:'show_for.blank', :default => "Not specified")
options[:class] = [options[:class], ShowFor.blank_content_class].join(' ')
end
# We need to convert value to_a because when dealing with ActiveRecord
# Array proxies, the follow statement Array# === value return false
value = value.to_a if value.is_a?(Array)
content = case value
when Date, Time, DateTime
I18n.l value, :format => options.delete(:format) || ShowFor.i18n_format
when TrueClass
I18n.t :"show_for.yes", :default => "Yes"
when FalseClass
I18n.t :"show_for.no", :default => "No"
when Array, Hash
collection_handler(value, options, &block)
when Proc
@template.capture(&value)
when NilClass
""
else
value
end
options[:content_html] = options.dup if apply_options
wrap_with(:content, content, options)
end
protected
def collection_handler(value, options, &block) #:nodoc:
iterator = collection_block?(block) ? block : ShowFor.default_collection_proc
response = ""
value.each do |item|
response << template.capture(item, &iterator)
end
wrap_with(:collection, response.html_safe, options)
end
end
end |
Declare required Ruby 2.3+ in gemspec | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "gir_ffi-pango"
s.version = "0.0.10"
s.summary = "GirFFI-based bindings for Pango"
s.description = "Bindings for Pango generated by GirFFI, with an eclectic set of overrides."
s.required_ruby_version = %q{>= 2.1.0}
s.license = 'LGPL-2.1'
s.authors = ["Matijs van Zuijlen"]
s.email = ["matijs@matijs.net"]
s.homepage = "http://www.github.com/mvz/gir_ffi-pango"
s.files = Dir['{lib,test}/**/*.rb', "README.md", "Rakefile", "COPYING.LIB"]
s.test_files = Dir['test/**/*.rb']
s.add_runtime_dependency('gir_ffi', ["~> 0.12.0"])
s.add_development_dependency('minitest', ["~> 5.0"])
s.add_development_dependency('rake', ["~> 12.0"])
s.require_paths = ["lib"]
end
| # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "gir_ffi-pango"
s.version = "0.0.10"
s.summary = "GirFFI-based bindings for Pango"
s.description = "Bindings for Pango generated by GirFFI, with an eclectic set of overrides."
s.required_ruby_version = %q{>= 2.3.0}
s.license = 'LGPL-2.1'
s.authors = ["Matijs van Zuijlen"]
s.email = ["matijs@matijs.net"]
s.homepage = "http://www.github.com/mvz/gir_ffi-pango"
s.files = Dir['{lib,test}/**/*.rb', "README.md", "Rakefile", "COPYING.LIB"]
s.test_files = Dir['test/**/*.rb']
s.add_runtime_dependency('gir_ffi', ["~> 0.12.0"])
s.add_development_dependency('minitest', ["~> 5.0"])
s.add_development_dependency('rake', ["~> 12.0"])
s.require_paths = ["lib"]
end
|
Add require statement for set. Extract function for fixnum conversion. | # This is a hack that I don't want to ever use anywhere else or repeat EVER, but we need enums to be
# an Array to pass schema validation. But we also want fast lookup!
class ArraySet < Array
def include?(obj)
if !defined? @values
@values = Set.new
self.each { |x| @values << (x.is_a?(Fixnum) ? x.to_f : x) }
end
obj = obj.to_f if obj.is_a?(Fixnum)
@values.include?(obj)
end
end
| require 'set'
# This is a hack that I don't want to ever use anywhere else or repeat EVER, but we need enums to be
# an Array to pass schema validation. But we also want fast lookup!
class ArraySet < Array
def include?(obj)
if !defined? @values
@values = Set.new
self.each { |x| @values << convert_to_float_if_fixnum(x) }
end
@values.include?(convert_to_float_if_fixnum(obj))
end
private
def convert_to_float_if_fixnum(value)
value.is_a?(Fixnum) ? value.to_f : value
end
end
|
Update rubocop requirement from ~> 1.14.0 to ~> 1.15.0 | # coding: utf-8
# frozen_string_literal: true
lib = File.expand_path("lib", __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "business/version"
Gem::Specification.new do |spec|
spec.name = "business"
spec.version = Business::VERSION
spec.authors = ["Harry Marr"]
spec.email = ["developers@gocardless.com"]
spec.summary = "Date calculations based on business calendars"
spec.description = "Date calculations based on business calendars"
spec.homepage = "https://github.com/gocardless/business"
spec.licenses = ["MIT"]
spec.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "gc_ruboconfig", "~> 2.25.0"
spec.add_development_dependency "rspec", "~> 3.1"
spec.add_development_dependency "rspec_junit_formatter", "~> 0.4.1"
spec.add_development_dependency "rubocop", "~> 1.14.0"
end
| # coding: utf-8
# frozen_string_literal: true
lib = File.expand_path("lib", __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "business/version"
Gem::Specification.new do |spec|
spec.name = "business"
spec.version = Business::VERSION
spec.authors = ["Harry Marr"]
spec.email = ["developers@gocardless.com"]
spec.summary = "Date calculations based on business calendars"
spec.description = "Date calculations based on business calendars"
spec.homepage = "https://github.com/gocardless/business"
spec.licenses = ["MIT"]
spec.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "gc_ruboconfig", "~> 2.25.0"
spec.add_development_dependency "rspec", "~> 3.1"
spec.add_development_dependency "rspec_junit_formatter", "~> 0.4.1"
spec.add_development_dependency "rubocop", "~> 1.15.0"
end
|
Rename permission key to mailer instead of inbox | require "georgia/mailer/engine"
module Georgia
module Mailer
# Helper to turn off email notifications
mattr_accessor :turn_on_email_notifications
@@turn_on_email_notifications = true
# Add to Georgia by default
Georgia.navigation += %w(messages)
Georgia.permissions.merge!(inbox: {
read_messages: { communications: true, admin: true, },
print_messages: { communications: true, admin: true, },
mark_messages_as_spam: { communications: true, admin: true, },
mark_messages_as_ham: { communications: true, admin: true, },
delete_messages: { communications: true, admin: true, },
empty_trash: { communications: false, admin: true, },
})
Georgia.roles += %w(communications)
end
end
| require "georgia/mailer/engine"
module Georgia
module Mailer
# Helper to turn off email notifications
mattr_accessor :turn_on_email_notifications
@@turn_on_email_notifications = true
# Add to Georgia by default
Georgia.navigation += %w(messages)
Georgia.permissions.merge!(mailer: {
read_messages: { communications: true, admin: true, },
print_messages: { communications: true, admin: true, },
mark_messages_as_spam: { communications: true, admin: true, },
mark_messages_as_ham: { communications: true, admin: true, },
delete_messages: { communications: true, admin: true, },
empty_trash: { communications: false, admin: true, },
})
Georgia.roles += %w(communications)
end
end
|
Move Moretext API URL to constant. | require "chh_moretext/version"
require "json"
require "open-uri"
module ChhMoretext
class Base
class << self
def fetch_moretext(number, limit)
number = "n=#{number}"
limit = parse(limit)
condition = limit.nil? ? "?#{number}" : "?#{number}&#{limit}"
return JSON(open("http://more.handlino.com/sentences.json#{condition}").read)["sentences"]
end
end
private
def self.parse(type)
case type
when Range then "limit=#{type.min},#{type.max}"
when Integer then "limit=#{type}"
else nil
end
end
end
end
require "chh_moretext/moretext"
| require "chh_moretext/version"
require "json"
require "open-uri"
module ChhMoretext
class Base
MORETEXT_API_URL = "http://more.handlino.com/sentences.json"
class << self
def fetch_moretext(number, limit)
number = "n=#{number}"
limit = parse(limit)
condition = limit.nil? ? "?#{number}" : "?#{number}&#{limit}"
return JSON(open("#{MORETEXT_API_URL}#{condition}").read)["sentences"]
end
end
private
def self.parse(type)
case type
when Range then "limit=#{type.min},#{type.max}"
when Integer then "limit=#{type}"
else nil
end
end
end
end
require "chh_moretext/moretext"
|
Stop the zxcvbn.js file being left open | module Zxcvbn
require "execjs"
class Tester
DATA_PATH = Pathname(File.expand_path('../../../data/zxcvbn.js', __FILE__))
def initialize
src = File.open(DATA_PATH, 'r').read
@context = ExecJS.compile(src)
end
def test(password, user_inputs = [])
result = @context.eval("zxcvbn(#{password.to_json}, #{user_inputs.to_json})")
OpenStruct.new(result)
end
end
end
| module Zxcvbn
require "execjs"
class Tester
DATA_PATH = Pathname(File.expand_path('../../../data/zxcvbn.js', __FILE__))
def initialize
src = File.read(DATA_PATH)
@context = ExecJS.compile(src)
end
def test(password, user_inputs = [])
result = @context.eval("zxcvbn(#{password.to_json}, #{user_inputs.to_json})")
OpenStruct.new(result)
end
end
end
|
Make Trawler play nice with Kaminari | require 'mongoid'
require 'trawler/stores/visible'
Dir["#{File.dirname(__FILE__)}/trawler/**/*.rb"].each { |rb| require rb }
| require 'mongoid'
require 'trawler/stores/visible'
# Ensure Kaminari is initialized (if it is present) before our models are loaded
begin; require 'kaminari'; rescue LoadError; end
if defined? ::Kaminari
puts "Kicking off Kaminari init"
::Kaminari::Hooks.init
end
Dir["#{File.dirname(__FILE__)}/trawler/**/*.rb"].each { |rb| require rb }
|
Add example of importing to cloud | # Usage (from the repo root):
# env FLIPPER_CLOUD_TOKEN=<token> bundle exec ruby examples/cloud/basic.rb
require 'pathname'
require 'logger'
root_path = Pathname(__FILE__).dirname.join('..').expand_path
lib_path = root_path.join('lib')
$:.unshift(lib_path)
require 'flipper'
require 'flipper/cloud'
memory_adapter = Flipper::Adapters::Memory.new
existing_flipper = Flipper.new(memory_adapter)
existing_flipper.enable(:test)
existing_flipper.enable(:search)
existing_flipper.enable_actor(:stats, Flipper::Actor.new("jnunemaker"))
existing_flipper.enable_percentage_of_time(:logging, 5)
# Don't provide a local adapter when doing an import from a local flipper
# instance. If you use the same local adapter as what you want to import from,
# you'll end up wiping out your local adapter.
cloud_flipper = Flipper::Cloud.new
pp memory_adapter.get_all
cloud_flipper.import(existing_flipper)
pp memory_adapter.get_all
| |
Add BenVista PhotoZoom Pro v6.0.4 | cask :v1 => 'photozoom-pro' do
version :latest
sha256 :no_check
url 'https://www.benvista.com/photozoompro/download/mac'
name 'PhotoZoom Pro'
homepage 'http://www.benvista.com/photozoompro'
license :freemium
app 'PhotoZoom Pro 6.app'
end
| |
Fix Rspec test user controler | require 'rails_helper'
RSpec.describe UsersController, type: :controller do
render_views
describe "GET #show" do
before(:each) do
@user = Factory(:user)
end
it "devrait réussir" do
get :show, :id => @user
response.should be_success
end
it "devrait trouver le bon utilisateur" do
get :show, :id => @user
assigns(:user).should == @user
end
it "devrait avoir le bon titre" do
get :show, :id => @user
response.should have_selector("title", :content => @user.nom)
end
it "devrait inclure le nom de l'utilisateur" do
get :show, :id => @user
response.should have_selector("h1", :content => @user.nom)
end
it "devrait avoir une image de profil" do
get :show, :id => @user
response.should have_selector("h1>img", :class => "gravatar")
end
end
end
describe "GET #new" do
it "devrait réussir" do
get :new
expect(response).to have_http_status(:success)
end
it "devrait avoir le titre adéquat" do
get :new
expect(response).should have_selector("head title", :content => "Sign up")
end
end
end | require 'rails_helper'
RSpec.describe UsersController, type: :controller do
render_views
describe "GET #show" do
before(:each) do
@user = Factory(:user)
end
it "devrait réussir" do
get :show, :id => @user
response.should be_success
end
it "devrait trouver le bon utilisateur" do
get :show, :id => @user
assigns(:user).should == @user
end
it "devrait avoir le bon titre" do
get :show, :id => @user
response.should have_selector("title", :content => @user.nom)
end
it "devrait inclure le nom de l'utilisateur" do
get :show, :id => @user
response.should have_selector("h1", :content => @user.nom)
end
it "devrait avoir une image de profil" do
get :show, :id => @user
response.should have_selector("h1>img", :class => "gravatar")
end
end
describe "GET #new" do
it "devrait réussir" do
get :new
expect(response).to have_http_status(:success)
end
it "devrait avoir le titre adéquat" do
get :new
expect(response).should have_selector("head title", :content => "Sign up")
end
end
end |
Add rspec-rails to development dependencies. | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/acts_as_purchasable/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Damien Wilson"]
gem.email = ["damien@mindglob.com"]
gem.description = %q{Everything has it's price, and now your ActiveRecord models can too!}
gem.summary = %q{`acts_as_purchasable` extends ActiveRecord models with methods that allow you to perform simple payment transactions on your models.}
gem.homepage = "https://github.com/damien/acts_as_purchasable"
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 = "acts_as_purchasable"
gem.require_paths = ["lib"]
gem.version = ActsAsPurchasable::VERSION
gem.add_dependency "rails", "~> 3.2"
gem.add_development_dependency "rspec"
gem.add_development_dependency "growl"
gem.add_development_dependency "guard"
gem.add_development_dependency "guard-rspec"
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/acts_as_purchasable/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Damien Wilson"]
gem.email = ["damien@mindglob.com"]
gem.description = %q{Everything has it's price, and now your ActiveRecord models can too!}
gem.summary = %q{`acts_as_purchasable` extends ActiveRecord models with methods that allow you to perform simple payment transactions on your models.}
gem.homepage = "https://github.com/damien/acts_as_purchasable"
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 = "acts_as_purchasable"
gem.require_paths = ["lib"]
gem.version = ActsAsPurchasable::VERSION
gem.add_dependency "rails", "~> 3.2"
gem.add_development_dependency "rspec"
gem.add_development_dependency "rspec-rails"
gem.add_development_dependency "growl"
gem.add_development_dependency "guard"
gem.add_development_dependency "guard-rspec"
end
|
Use updated versioncake configuration options. | require 'rails/engine'
module Spree
module Api
class Engine < Rails::Engine
isolate_namespace Spree
engine_name 'spree_api'
Rabl.configure do |config|
config.include_json_root = false
config.include_child_root = false
# Motivation here it make it call as_json when rendering timestamps
# and therefore display miliseconds. Otherwise it would fall to
# JSON.dump which doesn't display the miliseconds
config.json_engine = ActiveSupport::JSON
end
config.view_versions = [1]
config.view_version_extraction_strategy = :http_header
initializer "spree.api.environment", :before => :load_config_initializers do |app|
Spree::Api::Config = Spree::ApiConfiguration.new
end
def self.activate
Dir.glob(File.join(File.dirname(__FILE__), "../../../app/**/*_decorator*.rb")) do |c|
Rails.configuration.cache_classes ? require(c) : load(c)
end
end
config.to_prepare &method(:activate).to_proc
def self.root
@root ||= Pathname.new(File.expand_path('../../../../', __FILE__))
end
end
end
end
| require 'rails/engine'
require 'versioncake'
module Spree
module Api
class Engine < Rails::Engine
isolate_namespace Spree
engine_name 'spree_api'
Rabl.configure do |config|
config.include_json_root = false
config.include_child_root = false
# Motivation here it make it call as_json when rendering timestamps
# and therefore display miliseconds. Otherwise it would fall to
# JSON.dump which doesn't display the miliseconds
config.json_engine = ActiveSupport::JSON
end
config.versioncake.supported_version_numbers = [1]
config.versioncake.extraction_strategy = :http_header
initializer "spree.api.environment", :before => :load_config_initializers do |app|
Spree::Api::Config = Spree::ApiConfiguration.new
end
def self.activate
Dir.glob(File.join(File.dirname(__FILE__), "../../../app/**/*_decorator*.rb")) do |c|
Rails.configuration.cache_classes ? require(c) : load(c)
end
end
config.to_prepare &method(:activate).to_proc
def self.root
@root ||= Pathname.new(File.expand_path('../../../../', __FILE__))
end
end
end
end
|
Move setting of `feed_url` into `get_feed_for_url` | require "feedbag"
require "feedzirra"
class FeedDiscovery
def discover(url, finder = Feedbag, parser = Feedzirra::Feed)
feed = get_feed_for_url(url, finder, parser) do
urls = finder.find(url)
return false if urls.empty?
get_feed_for_url(urls.first, finder, parser) do
return false
end
end
feed.feed_url ||= url
feed
end
def get_feed_for_url(url, finder, parser)
feed = parser.fetch_and_parse(url)
rescue Exception
yield if block_given?
end
end
| require "feedbag"
require "feedzirra"
class FeedDiscovery
def discover(url, finder = Feedbag, parser = Feedzirra::Feed)
feed = get_feed_for_url(url, finder, parser) do
urls = finder.find(url)
return false if urls.empty?
get_feed_for_url(urls.first, finder, parser) do
return false
end
end
feed
end
def get_feed_for_url(url, finder, parser)
feed = parser.fetch_and_parse(url)
feed.feed_url ||= url
feed
rescue Exception
yield if block_given?
end
end
|
Fix Gem summary and description | # encoding: utf-8
$:.unshift(File.expand_path('../lib', __FILE__))
require 'api-pagination/version'
Gem::Specification.new do |s|
s.name = 'api-pagination'
s.version = ApiPagination::VERSION
s.authors = ['David Celis']
s.email = ['me@davidcel.is']
s.description = 'Link header pagination for Rails APIs'
s.summary = "Link header pagination for Rails APIs. Don't use the request body."
s.homepage = 'https://github.com/davidcelis/api-pagination'
s.license = 'MIT'
s.files = Dir['lib/**/*']
s.test_files = Dir['spec/**/*']
s.require_paths = ['lib']
s.add_development_dependency 'rspec'
s.add_development_dependency 'grape'
s.add_development_dependency 'actionpack', '>= 3.0.0'
end
| # encoding: utf-8
$:.unshift(File.expand_path('../lib', __FILE__))
require 'api-pagination/version'
Gem::Specification.new do |s|
s.name = 'api-pagination'
s.version = ApiPagination::VERSION
s.authors = ['David Celis']
s.email = ['me@davidcel.is']
s.description = 'Link header pagination for Rails and Grape APIs'
s.summary = "Link header pagination for Rails and Grape APIs. Don't use the request body."
s.homepage = 'https://github.com/davidcelis/api-pagination'
s.license = 'MIT'
s.files = Dir['lib/**/*']
s.test_files = Dir['spec/**/*']
s.require_paths = ['lib']
s.add_development_dependency 'rspec'
s.add_development_dependency 'grape'
s.add_development_dependency 'actionpack', '>= 3.0.0'
end
|
Use 100MB as a chunk_size | require "fog/aws"
require "open-uri"
class PgbackupsArchive::Storage
def initialize(key, file)
@key = key
@file = file
end
def connection
Fog::Storage.new({
:provider => "AWS",
:aws_access_key_id => ENV["PGBACKUPS_AWS_ACCESS_KEY_ID"],
:aws_secret_access_key => ENV["PGBACKUPS_AWS_SECRET_ACCESS_KEY"],
:region => ENV["PGBACKUPS_REGION"],
:persistent => false
})
end
def bucket
connection.directories.get ENV["PGBACKUPS_BUCKET"]
end
def store
bucket.files.create :key => @key, :body => @file, :public => false, :encryption => "AES256", :multipart_chunk_size => 5242880
end
end
| require "fog/aws"
require "open-uri"
class PgbackupsArchive::Storage
def initialize(key, file)
@key = key
@file = file
end
def connection
Fog::Storage.new({
:provider => "AWS",
:aws_access_key_id => ENV["PGBACKUPS_AWS_ACCESS_KEY_ID"],
:aws_secret_access_key => ENV["PGBACKUPS_AWS_SECRET_ACCESS_KEY"],
:region => ENV["PGBACKUPS_REGION"],
:persistent => false
})
end
def bucket
connection.directories.get ENV["PGBACKUPS_BUCKET"]
end
def store
bucket.files.create :key => @key, :body => @file, :public => false, :encryption => "AES256", :multipart_chunk_size => 104857600
end
end
|
Change fa-cog to pficon-settings in VmdbDatabaseSettingDecorator | class VmdbDatabaseSettingDecorator < MiqDecorator
def self.fonticon
'fa fa-cog'
end
end
| class VmdbDatabaseSettingDecorator < MiqDecorator
def self.fonticon
'pficon pficon-settings'
end
end
|
Allow up to Sprockets 2.12.x | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/compass-rails/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Scott Davis", "Chris Eppstein", "Craig McNamara"]
gem.email = ["jetviper21@gmail.com", "chris@eppsteins.net", "craig.mcnamara@gmail.com"]
gem.description = %q{Integrate Compass into Rails 3.0 and up.}
gem.summary = %q{Integrate Compass into Rails 3.0 and up.}
gem.homepage = "https://github.com/Compass/compass-rails"
gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
gem.files = `git ls-files`.split("\n")
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.name = "compass-rails"
gem.require_paths = ["lib"]
gem.version = CompassRails::VERSION
gem.license = "MIT"
gem.add_dependency 'compass', '~> 1.0.0'
gem.add_dependency 'sprockets', '<= 2.11.0'
gem.add_dependency 'sass-rails', '<= 5.0.1'
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/compass-rails/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Scott Davis", "Chris Eppstein", "Craig McNamara"]
gem.email = ["jetviper21@gmail.com", "chris@eppsteins.net", "craig.mcnamara@gmail.com"]
gem.description = %q{Integrate Compass into Rails 3.0 and up.}
gem.summary = %q{Integrate Compass into Rails 3.0 and up.}
gem.homepage = "https://github.com/Compass/compass-rails"
gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
gem.files = `git ls-files`.split("\n")
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.name = "compass-rails"
gem.require_paths = ["lib"]
gem.version = CompassRails::VERSION
gem.license = "MIT"
gem.add_dependency 'compass', '~> 1.0.0'
gem.add_dependency 'sprockets', '< 2.13'
gem.add_dependency 'sass-rails', '<= 5.0.1'
end
|
Add missing `optional: true` in NotificationsForFollowedTopics | # frozen_string_literal: true
module Thredded
class NotificationsForFollowedTopics < ActiveRecord::Base
belongs_to :user,
class_name: Thredded.user_class_name,
inverse_of: :thredded_notifications_for_followed_topics
belongs_to :messageboard # or is global
belongs_to :user_preference,
primary_key: :user_id,
foreign_key: :user_id,
inverse_of: :notifications_for_followed_topics
validates :user_id, presence: true
include Thredded::NotifierPreference
def self.default(_notifier)
# could be moved to `notifier.defaults(:notifications_for_followed_topics)`
Thredded::BaseNotifier::NotificationsDefault.new(true)
end
end
end
| # frozen_string_literal: true
module Thredded
class NotificationsForFollowedTopics < ActiveRecord::Base
belongs_to :user,
class_name: Thredded.user_class_name,
inverse_of: :thredded_notifications_for_followed_topics
belongs_to :messageboard,
# If messageboard is `nil`, these are the global preferences.
**(Thredded.rails_gte_51? ? { optional: true } : {})
belongs_to :user_preference,
primary_key: :user_id,
foreign_key: :user_id,
inverse_of: :notifications_for_followed_topics
validates :user_id, presence: true
include Thredded::NotifierPreference
def self.default(_notifier)
# could be moved to `notifier.defaults(:notifications_for_followed_topics)`
Thredded::BaseNotifier::NotificationsDefault.new(true)
end
end
end
|
Support ISO 639-2 3-letter language codes | class CheckCldr
def self.load
data = {}
Dir.foreach(File.join(Rails.root, 'data')) do |file|
if file =~ /^[a-z]{2}$/
yaml = File.join(Rails.root, 'data', file, 'languages.yml')
data[file] = YAML.load(File.read(yaml))[file]['languages'] if File.exist?(yaml)
end
end
data
end
def self.language_code_to_name(code, locale = I18n.locale)
locale ||= :en
name = CLDR_LANGUAGES[locale.to_s][code.to_s]
name.blank? ? code.to_s : name.mb_chars.capitalize
end
def self.localized_languages(locale = I18n.locale)
locale ||= :en
data = {}
CLDR_LANGUAGES[locale.to_s].each do |code, name|
data[code] = name.mb_chars.capitalize
end
data
end
end
| class CheckCldr
def self.load
data = {}
Dir.foreach(File.join(Rails.root, 'data')) do |file|
if /^[a-z]{2,3}$/ === file
yaml = File.join(Rails.root, 'data', file, 'languages.yml')
data[file] = YAML.load(File.read(yaml))[file]['languages'] if File.exist?(yaml)
end
end
data
end
def self.language_code_to_name(code, locale = I18n.locale)
locale ||= :en
name = CLDR_LANGUAGES[locale.to_s][code.to_s]
name.blank? ? code.to_s : name.mb_chars.capitalize
end
def self.localized_languages(locale = I18n.locale)
locale ||= :en
data = {}
CLDR_LANGUAGES[locale.to_s].each do |code, name|
data[code] = name.mb_chars.capitalize
end
data
end
end
|
Fix salesmachine syncing rake task | desc "Sync teacher and school attributes with salesmachine"
task :sync_salesmachine => :environment do
puts "Queueing sync workers:"
SchoolUser.joins(:users).where('users.role = ?', 'teacher').find_each do |school|
SyncSalesmachineAccountWorker.perform_async(school.id)
puts "school_id: #{school.id}"
school.users.where('users.role = ?', 'teacher').each do |teacher|
SyncSalesmachineContactWorker.perform_async(teacher.id)
puts " -- teacher_id: #{teacher.id}"
end
end
puts "Done"
end
| desc "Sync teacher and school attributes with salesmachine"
task :sync_salesmachine => :environment do
puts "Queueing sync workers:"
School.distinct
.joins(:users)
.where('users.role = ?', 'teacher')
.find_each do |school|
SyncSalesmachineAccountWorker.perform_async(school.id)
puts "school_id: #{school.id}"
school.users.teacher.each do |teacher|
SyncSalesmachineContactWorker.perform_async(teacher.id)
puts " -- teacher_id: #{teacher.id}"
end
end
puts "Done"
end
|
Add test to check if dispatcher calls route action with request and response objects | require_relative "helper"
class DispatcherTest < MiniTest::Unit::TestCase
class TestRouter
attr_reader :match_argument
def initialize(route)
@route = route
end
def match(verb, path)
@match_argument = path
@route
end
end
def setup
@route = Harbor::Router::Route.new(Proc.new{}, [])
@router = TestRouter.new(@route)
@dispatcher = Harbor::Dispatcher.new(@router)
@request = Harbor::Test::Request.new
@response = Harbor::Test::Response.new
@request.path_info = 'parts/1234/4321/'
@route.tokens << 'parts' << ':id' << ':order_id'
end
def test_extracts_wildcard_params_from_request_path
@dispatcher.dispatch!(@request, @response)
assert_equal '1234', @request.params['id']
assert_equal '4321', @request.params['order_id']
end
end
| require_relative "helper"
class DispatcherTest < MiniTest::Unit::TestCase
class TestRouter
def initialize(route)
@route = route
end
def match(verb, path)
@route
end
end
def setup
@action_called = false
@action = Proc.new { |request, response| @action_called = (response == @response && request == @request) }
@route = Harbor::Router::Route.new(@action, ['parts', ':id', ':order_id'])
@router = TestRouter.new(@route)
@dispatcher = Harbor::Dispatcher.new(@router)
@request = Harbor::Test::Request.new
@response = Harbor::Test::Response.new
@request.path_info = 'parts/1234/4321/'
end
def test_extracts_wildcard_params_from_request_path
@dispatcher.dispatch!(@request, @response)
assert_equal '1234', @request.params['id']
assert_equal '4321', @request.params['order_id']
end
def test_calls_route_action_with_request_and_response
@dispatcher.dispatch!(@request, @response)
assert @action_called
end
end
|
Add is_benign?, is_suspicious? and include_benign? methods + tests |
require_relative 'siphash'
module OpenDNS
class DNSDB
module Label
CACHE_KEY = 'Umbrella/OpenDNS'
def distinct_labels(labels)
return labels unless labels.kind_of?(Hash)
labels.values.flatten.uniq
end
def label_by_name(names)
names_is_array = names.kind_of?(Enumerable)
names = [ names ] unless names_is_array
multi = Ethon::Multi.new
names_json = MultiJson.dump(names)
cacheid = SipHash::digest(CACHE_KEY, names_json).to_s(16)
url = "/infected/names/#{cacheid}.json"
query = query_handler(url, :get, { body: names_json })
multi.add(query)
multi.perform
responses = MultiJson.load(query.response_body)
responses = responses['scores']
responses.each_pair do |name, label|
responses[name] = [:suspicious, :unknown, :benign][label + 1]
end
responses = responses.values.first unless names_is_array
responses
end
def distinct_labels_by_name(names)
distinct_labels(label_by_name(names))
end
def include_suspicious?(names)
distinct_labels_by_name(names).include?(:suspicious)
end
end
end
end |
require_relative 'siphash'
module OpenDNS
class DNSDB
module Label
CACHE_KEY = 'Umbrella/OpenDNS'
def distinct_labels(labels)
return [ labels ] unless labels.kind_of?(Hash)
labels.values.flatten.uniq
end
def label_by_name(names)
names_is_array = names.kind_of?(Enumerable)
names = [ names ] unless names_is_array
multi = Ethon::Multi.new
names_json = MultiJson.dump(names)
cacheid = SipHash::digest(CACHE_KEY, names_json).to_s(16)
url = "/infected/names/#{cacheid}.json"
query = query_handler(url, :get, { body: names_json })
multi.add(query)
multi.perform
responses = MultiJson.load(query.response_body)
responses = responses['scores']
responses.each_pair do |name, label|
responses[name] = [:suspicious, :unknown, :benign][label + 1]
end
responses = responses.values.first unless names_is_array
responses
end
def distinct_labels_by_name(names)
distinct_labels(label_by_name(names))
end
def include_suspicious?(names)
distinct_labels_by_name(names).include?(:suspicious)
end
def is_suspicious?(name)
include_suspicious?(name)
end
def include_benign?(names)
distinct_labels_by_name(names).include?(:benign)
end
def is_benign?(name)
include_benign?(name)
end
end
end
end |
Change dependency version syntax for Rails gem. This will enable update to newer Rails 4 versions. Still requires version 4.1.6 as minimum version. | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "unlock_paypal/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "unlock_paypal"
s.version = UnlockPaypal::VERSION
s.authors = ["Daniel Weinmann"]
s.email = ["danielweinmann@gmail.com"]
s.homepage = "https://github.com/danielweinmann/unlock_paypal"
s.summary = "paypal-recurrring integration with Unlock"
s.description = "paypal-recurrring integration with Unlock"
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.add_dependency "rails", "~> 4.1.6"
s.add_dependency "unlock_gateway", "0.2.1"
s.add_dependency "paypal-recurring"
s.add_development_dependency "sqlite3"
end
| $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "unlock_paypal/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "unlock_paypal"
s.version = UnlockPaypal::VERSION
s.authors = ["Daniel Weinmann"]
s.email = ["danielweinmann@gmail.com"]
s.homepage = "https://github.com/danielweinmann/unlock_paypal"
s.summary = "paypal-recurrring integration with Unlock"
s.description = "paypal-recurrring integration with Unlock"
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.add_dependency "rails", "~> 4", ">= 4.1.6"
s.add_dependency "unlock_gateway", "0.2.1"
s.add_dependency "paypal-recurring"
s.add_development_dependency "sqlite3"
end
|
Make sure vim is installed | require 'spec_helper'
describe package('bash') do
it { should be_installed }
end
describe package('curl') do
it { should be_installed }
end
describe package('openssh') do
it { should be_installed }
end
describe package('wget') do
it { should be_installed }
end
| require 'spec_helper'
describe package('bash') do
it { should be_installed }
end
describe package('curl') do
it { should be_installed }
end
describe package('openssh') do
it { should be_installed }
end
describe package('vim') do
it { should be_installed }
end
describe package('wget') do
it { should be_installed }
end
|
Extend self on XPath module | module XPath
autoload :Expression, 'xpath/expression'
autoload :Collection, 'xpath/collection'
def self.generate
yield(Expression::Self.new)
end
def current
Expression::Self.new
end
def descendant(expression)
Expression::Descendant.new(current, expression)
end
def child(expression)
Expression::Child.new(current, expression)
end
def anywhere(expression)
Expression::Anywhere.new(expression)
end
def attr(expression)
Expression::Attribute.new(current, expression)
end
def string
Expression::StringFunction.new(current)
end
def contains(expression)
Expression::Contains.new(current, expression)
end
def text
Expression::Text.new(current)
end
def var(name)
Expression::Variable.new(name)
end
def varstring(name)
var(name).string_literal
end
end
| module XPath
autoload :Expression, 'xpath/expression'
autoload :Collection, 'xpath/collection'
extend self
def self.generate
yield(Expression::Self.new)
end
def current
Expression::Self.new
end
def descendant(expression)
Expression::Descendant.new(current, expression)
end
def child(expression)
Expression::Child.new(current, expression)
end
def anywhere(expression)
Expression::Anywhere.new(expression)
end
def attr(expression)
Expression::Attribute.new(current, expression)
end
def string
Expression::StringFunction.new(current)
end
def contains(expression)
Expression::Contains.new(current, expression)
end
def text
Expression::Text.new(current)
end
def var(name)
Expression::Variable.new(name)
end
def varstring(name)
var(name).string_literal
end
end
|
Make changes so test environment runs. | require "formtastic"
require "formtastic-bootstrap/engine"
require "formtastic-bootstrap/helpers"
require "formtastic-bootstrap/inputs"
require "formtastic-bootstrap/form_builder"
require "action_view/helpers/text_field_date_helper"
| require "formtastic"
require "formtastic-bootstrap/engine" if defined?(::Rails) # For tests
require "formtastic-bootstrap/helpers"
require "formtastic-bootstrap/inputs"
require "formtastic-bootstrap/form_builder"
require "action_view/helpers/text_field_date_helper"
|
Substitute the call through the method within the test by the static call to FizzBuzz.say(n) | require "test/unit"
require "shoulda"
class FizzBuzz
def self.say(n)
"1"
end
end
class TestFizzbuzz < Test::Unit::TestCase
def say(n)
FizzBuzz.say(n)
end
should "say 1 for 1" do
assert_equal "1", say(1)
end
end
| require "test/unit"
require "shoulda"
class FizzBuzz
def self.say(n)
"1"
end
end
class TestFizzbuzz < Test::Unit::TestCase
def say(n)
FizzBuzz.say(n)
end
should "say 1 for 1" do
assert_equal "1", FizzBuzz.say(1)
end
end
|
Add search method to tag controller. | class TagsController < ApplicationController
def index
@tags = ActsAsTaggableOn::Tag.all
end
def show
@tag_name = params[:tag_name]
@lists = List.tagged_with(@tag_name)
end
end
| class TagsController < ApplicationController
def index
@tags = ActsAsTaggableOn::Tag.all
end
def search
@tags = ActsAsTaggableOn::Tag.where("name like ?", "%#{params[:tag_query]}%")
respond_to do |format|
format.html
format.json {
render json: @tags, root: false
}
end
def show
@tag_name = params[:tag_name]
@lists = List.tagged_with(@tag_name)
end
end
end
|
Add inline documentation to Service Version states | class ServiceVersion < ApplicationRecord
belongs_to :service
belongs_to :user
validates :spec, swagger_spec: true
before_create :set_version_number
after_save :update_search_metadata
after_create :retract_proposed
# proposed: 0, current: 1, rejected: 2, retracted:3 , outdated:4 , retired:5
# Always add new states at the end.
enum status: [:proposed, :current, :rejected, :retracted, :outdated, :retired]
def spec_file
@spec_file
end
def spec_file=(spec_file)
@spec_file = spec_file
self.spec = JSON.parse(self.spec_file.read)
end
def to_param
version_number.to_s
end
def set_version_number
self.version_number = service.last_version_number + 1
end
def update_search_metadata
service.update_search_metadata if status == "current"
end
def retract_proposed
service.service_versions.proposed.each do |version|
version.retracted! unless version.version_number == self.version_number
end
end
end
| class ServiceVersion < ApplicationRecord
belongs_to :service
belongs_to :user
validates :spec, swagger_spec: true
before_create :set_version_number
after_save :update_search_metadata
after_create :retract_proposed
# proposed: 0, current: 1, rejected: 2, retracted:3 , outdated:4 , retired:5
#
# The lifecycle is a follows:
#
# A new service version is born "proposed".
# Until it is approved by GobiernoDigital, where it becomes "current".
# Unless it is NOT approved, and it turns "rejected".
# Or, the author decides to upload a new version before the approval or
# rejection, in which case it becomes "retracted"
# Also, once a subsequent version is accepted and becomes "current", the
# previously current version becomes "outdated" if the change is backwards
# compatible. If the change is NOT backwards compatible, it becomes "retired"
#
# ALWAYS add new states at the end.
enum status: [:proposed, :current, :rejected, :retracted, :outdated, :retired]
def spec_file
@spec_file
end
def spec_file=(spec_file)
@spec_file = spec_file
self.spec = JSON.parse(self.spec_file.read)
end
def to_param
version_number.to_s
end
def set_version_number
self.version_number = service.last_version_number + 1
end
def update_search_metadata
service.update_search_metadata if status == "current"
end
def retract_proposed
service.service_versions.proposed.each do |version|
version.retracted! unless version.version_number == self.version_number
end
end
end
|
Add a group_id attribute to Requests. Like a User, a Request also belongs to a group. | class CreateRequests < ActiveRecord::Migration
def change
create_table :requests do |t|
t.string :content, null: false
t.integer :requester_id, null: false
t.integer :responder_id
t.boolean :is_fulfilled, default: false
t.timestamps null: false
end
end
end
| class CreateRequests < ActiveRecord::Migration
def change
create_table :requests do |t|
t.string :content, null: false
t.integer :requester_id, null: false
t.integer :responder_id
t.integer :group_id, null: false
t.boolean :is_fulfilled, default: false
t.timestamps null: false
end
end
end
|
Add = and IN SQL operators | module Riews
class FilterCriteria < ApplicationRecord
self.table_name = 'riews_filter_criterias'
def self.operators
{
1 => 'NULL',
2 => 'NOT NULL',
3 => '='
}
end
belongs_to :riews_view, class_name: 'Riews::View'
has_many :arguments, foreign_key: 'riews_filter_criteria_id', dependent: :delete_all, inverse_of: :riews_filter_criteria
accepts_nested_attributes_for :arguments, reject_if: :all_blank, allow_destroy: true
alias_method :view, :riews_view
validates :operator, inclusion: { in: operators.keys }
validates_presence_of :view, :field_name, :operator
def available_filter_criterias
(view.model.constantize).attribute_names
end
def apply_to(query)
case operator
when 1
query.where(field_name => nil)
when 2
query.where.not(field_name => nil)
else
query
end
end
end
end
| module Riews
class FilterCriteria < ApplicationRecord
self.table_name = 'riews_filter_criterias'
def self.operators
{
1 => 'NULL',
2 => 'NOT NULL',
3 => '=',
4 => 'IN'
}
end
belongs_to :riews_view, class_name: 'Riews::View'
has_many :arguments, foreign_key: 'riews_filter_criteria_id', dependent: :delete_all, inverse_of: :riews_filter_criteria
accepts_nested_attributes_for :arguments, reject_if: :all_blank, allow_destroy: true
alias_method :view, :riews_view
validates :operator, inclusion: { in: operators.keys }
validates_presence_of :view, :field_name, :operator
def available_filter_criterias
(view.model.constantize).attribute_names
end
def apply_to(query)
case operator
when 1
query.where(field_name => nil)
when 2
query.where.not(field_name => nil)
when 3, 4
query.where(field_name => arguments.pluck(:value))
else
query
end
end
end
end
|
Fix for MRI 2.0, JRuby | require 'spec_helper'
require 'vxod/db/mongoid'
module Vxod::Db::Mongoid
describe User do
let(:user_class) { Class.new { include Vxod::Db::Mongoid::User } }
let(:user){ user_class.new }
describe '#password_valid?' do
it 'require not empty password' do
expect(user.password_valid?('')).to be_false
expect(user.password_valid?(nil)).to be_false
expect(user.errors[:password]).to_not be_nil
end
it 'checks min lenght' do
expect(user.password_valid?('1234567')).to be_true
expect(user.password_valid?('123456')).to be_false
expect(user.errors[:password]).to_not be_nil
end
end
end
end | require 'spec_helper'
require 'vxod/db/mongoid'
module Vxod::Db::Mongoid
describe User do
let(:user_class) { Class.new { send(:include, Vxod::Db::Mongoid::User) } }
let(:user){ user_class.new }
describe '#password_valid?' do
it 'require not empty password' do
expect(user.password_valid?('')).to be_false
expect(user.password_valid?(nil)).to be_false
expect(user.errors[:password]).to_not be_nil
end
it 'checks min lenght' do
expect(user.password_valid?('1234567')).to be_true
expect(user.password_valid?('123456')).to be_false
expect(user.errors[:password]).to_not be_nil
end
end
end
end |
Change stop signal. INT for QUIT | class Asynchronic::Worker
attr_reader :queue
attr_reader :queue_name
attr_reader :env
attr_reader :listener
def initialize(queue_name, env)
@queue_name = queue_name
@queue = env.queue_engine[queue_name]
@env = env
@listener = env.queue_engine.listener
end
def start
Asynchronic.logger.info('Asynchronic') { "Starting worker of #{queue_name} (#{Process.pid})" }
Signal.trap('INT') { stop }
listener.listen(queue) do |pid|
env.load_process(pid).execute
end
end
def stop
Asynchronic.logger.info('Asynchronic') { "Stopping worker of #{@queue_name} (#{Process.pid})" }
listener.stop
end
def self.start(queue_name, &block)
worker = new queue_name, Asynchronic.environment
Thread.new { block.call(worker) } if block_given?
worker.start
end
end | class Asynchronic::Worker
attr_reader :queue
attr_reader :queue_name
attr_reader :env
attr_reader :listener
def initialize(queue_name, env)
@queue_name = queue_name
@queue = env.queue_engine[queue_name]
@env = env
@listener = env.queue_engine.listener
end
def start
Asynchronic.logger.info('Asynchronic') { "Starting worker of #{queue_name} (#{Process.pid})" }
Signal.trap('QUIT') { stop }
listener.listen(queue) do |pid|
env.load_process(pid).execute
end
end
def stop
Asynchronic.logger.info('Asynchronic') { "Stopping worker of #{@queue_name} (#{Process.pid})" }
listener.stop
end
def self.start(queue_name, &block)
worker = new queue_name, Asynchronic.environment
Thread.new { block.call(worker) } if block_given?
worker.start
end
end |
Update gem to version 1.0.1 | # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'capistrano-getservers/get_servers'
Gem::Specification.new do |gem|
gem.name = "capistrano-getservers"
gem.version = '1.0.0'
gem.authors = ["Alfred Moreno"]
gem.email = ["alfred.moreno@zumba.com"]
gem.description = %q{A capistrano plugin for simplifying EC2 deployment processes}
gem.summary = %q{A capistrano plugin for simplifying EC@ deployment processes}
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 'capistrano', '>=2.1.0'
gem.add_dependency 'fog', '>=1.5.0'
end
| # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'capistrano-getservers/get_servers'
Gem::Specification.new do |gem|
gem.name = "capistrano-getservers"
gem.version = '1.0.1'
gem.authors = ["Alfred Moreno"]
gem.email = ["alfred.moreno@zumba.com"]
gem.description = %q{A capistrano plugin for simplifying EC2 deployment processes}
gem.summary = %q{A capistrano plugin for simplifying EC@ deployment processes}
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 'capistrano', '>=2.1.0'
gem.add_dependency 'fog', '>=1.5.0'
end
|
Add details to heart rate list | class HeartRate < ActiveRecord::Base
belongs_to :identity
# beats:integer measurement_date:date measurement_source:string
validates :beats, presence: true
validates :measurement_date, presence: true
def display
beats.to_s + " " + I18n.t("myplaceonline.heart_rates.beats")
end
before_create :do_before_save
before_update :do_before_save
def do_before_save
Myp.set_common_model_properties(self)
end
end
| class HeartRate < ActiveRecord::Base
belongs_to :identity
# beats:integer measurement_date:date measurement_source:string
validates :beats, presence: true
validates :measurement_date, presence: true
def display
beats.to_s + " " + I18n.t("myplaceonline.heart_rates.beats") + " (" + Myp.display_date(measurement_date, User.current_user) + ")"
end
before_create :do_before_save
before_update :do_before_save
def do_before_save
Myp.set_common_model_properties(self)
end
end
|
Add a bunch of test TODOs | require File.expand_path("../../base", __FILE__)
class BasicUpTest < AcceptanceTest
should "bring up a running virtual machine" do
assert_execute("vagrant", "box", "add", "base", config.boxes["default"])
assert_execute("vagrant", "init")
assert_execute("vagrant", "up")
result = assert_execute("vagrant", "status")
assert(output(result.stdout).status("default", "running"),
"Virtual machine should be running")
end
=begin
This shows how we can test that SSH is working. We'll use
this code later, but for now have no test that exercises it.
outputted = false
result = assert_execute("vagrant", "ssh") do |io_type, data|
if io_type == :stdin and !outputted
data.puts("echo hello")
data.puts("exit")
outputted = true
end
end
assert_equal("hello", result.stdout.chomp,
"Vagrant should bring up a virtual machine and be able to SSH in."
=end
end
| require File.expand_path("../../base", __FILE__)
class BasicUpTest < AcceptanceTest
should "bring up a running virtual machine" do
assert_execute("vagrant", "box", "add", "base", config.boxes["default"])
assert_execute("vagrant", "init")
assert_execute("vagrant", "up")
result = assert_execute("vagrant", "status")
assert(output(result.stdout).status("default", "running"),
"Virtual machine should be running")
end
=begin
TODO:
should "fail if no `Vagrantfile` is found"
should "be able to run if `Vagrantfile` is in parent directory"
should "bring up a running virtual machine and be able to SSH into it"
should "bring up a running virtual machine and have a `/vagrant' shared folder by default"
should "destroy a running virtual machine"
should "save then restore a virtual machine using `vagrant up`"
should "halt then start a virtual machine using `vagrant up`"
This shows how we can test that SSH is working. We'll use
this code later, but for now have no test that exercises it.
outputted = false
result = assert_execute("vagrant", "ssh") do |io_type, data|
if io_type == :stdin and !outputted
data.puts("echo hello")
data.puts("exit")
outputted = true
end
end
assert_equal("hello", result.stdout.chomp,
"Vagrant should bring up a virtual machine and be able to SSH in."
=end
end
|
Refactor RuntimeLoader spec to use example Class | require 'spec_helper'
require 'rohbau/runtime_loader'
describe Rohbau::RuntimeLoader do
let(:my_runtime_loader) do
Class.new(Rohbau::RuntimeLoader)
end
let(:example_class) do
Class.new
end
before do
my_runtime_loader.new(example_class)
end
it 'starts up a given class' do
assert_kind_of example_class, my_runtime_loader.instance
end
it 'fails if it was already instanciated' do
raised = assert_raises RuntimeError do
my_runtime_loader.new(example_class)
end
assert_match(/already/, raised.message)
end
end
| require 'spec_helper'
require 'rohbau/runtime_loader'
describe Rohbau::RuntimeLoader do
ExampleClass = Class.new
let(:my_runtime_loader) do
Class.new(Rohbau::RuntimeLoader)
end
before do
my_runtime_loader.new(ExampleClass)
end
it 'starts up a given class' do
assert_kind_of ExampleClass, my_runtime_loader.instance
end
it 'fails if it was already instanciated' do
raised = assert_raises RuntimeError do
my_runtime_loader.new(ExampleClass)
end
assert_match(/already/, raised.message)
end
end
|
Add spec for compact help formatter | require 'spec_helper'
describe Commander::HelpFormatter::TerminalCompact do
include Commander::Methods
before :each do
mock_terminal
end
describe 'global help' do
before :each do
new_command_runner 'help' do
program :help_formatter, :compact
command :'install gem' do |c|
c.syntax = 'foo install gem [options]'
c.summary = 'Install some gem'
end
end.run!
@global_help = @output.string
end
describe 'should display' do
it 'the command name' do
expect(@global_help).to include('install gem')
end
it 'the summary' do
expect(@global_help).to include('Install some gem')
end
end
end
describe 'command help' do
before :each do
new_command_runner 'help', 'install', 'gem' do
program :help_formatter, :compact
command :'install gem' do |c|
c.syntax = 'foo install gem [options]'
c.summary = 'Install some gem'
c.description = 'Install some gem, blah blah blah'
c.example 'one', 'two'
c.example 'three', 'four'
end
end.run!
@command_help = @output.string
end
describe 'should display' do
it 'the command name' do
expect(@command_help).to include('install gem')
end
it 'the description' do
expect(@command_help).to include('Install some gem, blah blah blah')
end
it 'all examples' do
expect(@command_help).to include('# one')
expect(@command_help).to include('two')
expect(@command_help).to include('# three')
expect(@command_help).to include('four')
end
it 'the syntax' do
expect(@command_help).to include('foo install gem [options]')
end
end
end
end
| |
Remove ruby from body column | #!/usr/bin/env ruby
require "nkf"
require "groonga"
require "nokogiri"
Groonga::Database.open("db/db") do |database|
authors = File.read("authors.txt")
authors.each_line do |line|
puts line
author_id = line.split(",")[0]
Dir.glob("aozorabunko/cards/#{author_id}/files/*.html") do |path|
html = File.read(path)
encoding = NKF.guess(html).to_s
doc = Nokogiri::HTML.parse(html, nil, encoding)
books = Groonga["Books"]
basename = File.basename(path)
if /\A\d+_/ =~ basename
book_id = basename.split("_")[0]
else
book_id = basename.split(".")[0]
end
title = doc.css(".title").text
subtitle = doc.css(".subtitle").text
if subtitle
title = [title, subtitle].join(" ")
end
books.add(
basename,
title: title,
author: doc.css(".author").text,
author_id: author_id,
book_id: book_id,
body: html.encode("utf-8", encoding)
)
end
end
end
| #!/usr/bin/env ruby
require "nkf"
require "groonga"
require "nokogiri"
Groonga::Database.open("db/db") do |database|
authors = File.read("authors.txt")
authors.each_line do |line|
puts line
author_id = line.split(",")[0]
Dir.glob("aozorabunko/cards/#{author_id}/files/*.html") do |path|
html = File.read(path)
encoding = NKF.guess(html).to_s
doc = Nokogiri::HTML.parse(html, nil, encoding)
books = Groonga["Books"]
basename = File.basename(path)
if /\A\d+_/ =~ basename
book_id = basename.split("_")[0]
else
book_id = basename.split(".")[0]
end
title = doc.css(".title").text
subtitle = doc.css(".subtitle").text
if subtitle
title = [title, subtitle].join(" ")
end
content = ""
doc.search("body .main_text").children.each do |node|
case node.node_name
when "text"
content += node.text
end
end
books.add(
basename,
title: title,
author: doc.css(".author").text,
author_id: author_id,
book_id: book_id,
body: content
)
end
end
end
|
Improve error messages on run failure in UAT | def scube_run options: nil, command: nil, check: false
cmd = %w[scube]
cmd << options if options
cmd << command if command
run_simple cmd.join(' '), false
expect(last_command_started).to have_exit_status 0 if check
end
When /^I( successfully)? run scube with options? (-.+)$/ do |check, options|
scube_run options: options, check: !!check
end
When /^I( successfully)? run scube with command `([^']*)'$/ do |check, command|
scube_run command: command, check: !!check
end
Then /^the exit status must be (\d+)$/ do |exit_status|
expect(last_command_started).to have_exit_status exit_status.to_i
end
| def scube_run options: nil, command: nil, check: false
cmd = %w[scube]
cmd << options if options
cmd << command if command
run_simple cmd.join(' '), false
return unless check
expect(last_command_started).to have_exit_status 0
rescue RSpec::Expectations::ExpectationNotMetError => e
if ENV.key? 'SCUBE_CLI_TEST_DEBUG'
fail RSpec::Expectations::ExpectationNotMetError, <<-eoh
#{e.message} Output was:
```\n#{last_command_started.output.lines.map { |l| " #{l}" }.join} ```
eoh
else
raise
end
end
When /^I( successfully)? run scube with options? (-.+)$/ do |check, options|
scube_run options: options, check: !!check
end
When /^I( successfully)? run scube with command `([^']*)'$/ do |check, command|
scube_run command: command, check: !!check
end
Then /^the exit status must be (\d+)$/ do |exit_status|
expect(last_command_started).to have_exit_status exit_status.to_i
end
|
Remove explicit class names from nested resources | module Bcx
module Resources
# Bcx::Resources::Project
# Provides access to projects resoource and other nested resources
#
# Fetch all projects
# GET /projects.json
#
# client.projects!
#
# Fetch archived projects
# GET /projects/archived.json
#
# clients.projects.archived!
#
# Fetch single project with ID of 123
# GET /projects/123.json
#
# client.projects!(123)
#
# Create a project
# POST /projects.json
#
# client.projects.create!(name: 'Acme project', description: 'This is a new project')
#
# Update an existing project
# PUT /projects/123.json
#
# client.projects(123).update!(description: 'A new description')
#
# Delete a project
# DELETE /projects/123.json
#
# client.projects(123).delete!
#
class Project < Rapidash::Base
root :project
resource :todolists, class_name: 'Bcx::Resources::Todolist'
resource :todos, class_name: 'Bcx::Resources::Todo'
def archived!
@url += '/archived'
call!
end
end
end
end
| module Bcx
module Resources
# Bcx::Resources::Project
# Provides access to projects resoource and other nested resources
#
# Fetch all projects
# GET /projects.json
#
# client.projects!
#
# Fetch archived projects
# GET /projects/archived.json
#
# clients.projects.archived!
#
# Fetch single project with ID of 123
# GET /projects/123.json
#
# client.projects!(123)
#
# Create a project
# POST /projects.json
#
# client.projects.create!(name: 'Acme project', description: 'This is a new project')
#
# Update an existing project
# PUT /projects/123.json
#
# client.projects(123).update!(description: 'A new description')
#
# Delete a project
# DELETE /projects/123.json
#
# client.projects(123).delete!
#
class Project < Rapidash::Base
root :project
resource :todolists
resource :todos
def archived!
@url += '/archived'
call!
end
end
end
end
|
Use active scope in orgs rake task | namespace :organisations do
desc 'Update organisations contribution_count'
task update_contribution_count: :environment do
next unless Contribution.in_date_range?
Organisation.all.find_each(&:update_contribution_count)
end
desc 'Reset organisations contribution_count'
task reset_contribution_count: :environment do
Organisation.all.update_all(contribution_count: 0)
end
desc 'Download user organisations'
task download_user_organisations: :environment do
next unless Contribution.in_date_range?
User.all.find_each do |user|
puts "Importing organisations for #{user.nickname}"
user.download_user_organisations(User.load_user.token) rescue nil
end
end
end
| namespace :organisations do
desc 'Update organisations contribution_count'
task update_contribution_count: :environment do
next unless Contribution.in_date_range?
Organisation.all.find_each(&:update_contribution_count)
end
desc 'Reset organisations contribution_count'
task reset_contribution_count: :environment do
Organisation.all.update_all(contribution_count: 0)
end
desc 'Download user organisations'
task download_user_organisations: :environment do
next unless Contribution.in_date_range?
User.active.find_each do |user|
puts "Importing organisations for #{user.nickname}"
user.download_user_organisations(User.load_user.token) rescue nil
end
end
end
|
Remove method that does not belong in sequent | ##
# Multi-tenant event store that replays events grouped by a specific tenant.
#
module Sequent
module Core
class TenantEventStore < EventStore
## TODO remove this method since created_organizations is Freemle specific
def self.all_organization_ids(record_class = Sequent::Core::EventRecord)
record_class.created_organizations.pluck(:aggregate_id)
end
def replay_events_for(organization_id)
replay_events do
aggregate_ids = @record_class.connection.select_all("select distinct aggregate_id from #{@record_class.table_name} where organization_id = '#{organization_id}'").map { |hash| hash["aggregate_id"] }
@record_class.connection.select_all("select id, event_type, event_json from #{@record_class.table_name} where aggregate_id in (#{aggregate_ids.map { |id| %Q{'#{id}'} }.join(",")}) order by id")
end
end
end
end
end
| ##
# Multi-tenant event store that replays events grouped by a specific tenant.
#
module Sequent
module Core
class TenantEventStore < EventStore
def replay_events_for(organization_id)
replay_events do
aggregate_ids = @record_class.connection.select_all("select distinct aggregate_id from #{@record_class.table_name} where organization_id = '#{organization_id}'").map { |hash| hash["aggregate_id"] }
@record_class.connection.select_all("select id, event_type, event_json from #{@record_class.table_name} where aggregate_id in (#{aggregate_ids.map { |id| %Q{'#{id}'} }.join(",")}) order by id")
end
end
end
end
end
|
Fix the syntax for including a recipe | #
# Cookbook Name:: apache_zookeeper
# Recipe:: default
#
include_recipe['install']
include_recipe['configure']
include_recipe['service']
| #
# Cookbook Name:: apache_zookeeper
# Recipe:: default
#
include_recipe 'apache_zookeeper::install'
include_recipe 'apache_zookeeper::configure'
include_recipe 'apache_zookeeper::service'
|
Include GitHub repo as homepage. | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'grape/jbuilder/version'
Gem::Specification.new do |spec|
spec.name = "grape-jbuilder"
spec.version = Grape::Jbuilder::VERSION
spec.authors = ["Shu Masuda"]
spec.email = ["masushu@gmail.com"]
spec.description = %q{Use Jbuilder in Grape}
spec.summary = %q{Use Jbuilder in Grape}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "grape", ">= 0.3"
spec.add_dependency "jbuilder"
spec.add_dependency "tilt"
spec.add_dependency "tilt-jbuilder", ">= 0.4.0"
spec.add_dependency "i18n"
spec.add_development_dependency "bundler"
spec.add_development_dependency "json_expressions"
spec.add_development_dependency "rack-test"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'grape/jbuilder/version'
Gem::Specification.new do |spec|
spec.name = "grape-jbuilder"
spec.version = Grape::Jbuilder::VERSION
spec.authors = ["Shu Masuda"]
spec.email = ["masushu@gmail.com"]
spec.description = %q{Use Jbuilder in Grape}
spec.summary = %q{Use Jbuilder in Grape}
spec.homepage = "https://github.com/milkcocoa/grape-jbuilder"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "grape", ">= 0.3"
spec.add_dependency "jbuilder"
spec.add_dependency "tilt"
spec.add_dependency "tilt-jbuilder", ">= 0.4.0"
spec.add_dependency "i18n"
spec.add_development_dependency "bundler"
spec.add_development_dependency "json_expressions"
spec.add_development_dependency "rack-test"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
end
|
Remove rubygems usage from libraries | require 'pathname'
require 'rubygems'
gem 'dm-core', '0.10.0'
require 'dm-core'
spec_dir_path = Pathname(__FILE__).dirname.expand_path
$LOAD_PATH.unshift(spec_dir_path.parent + 'lib/')
require 'dm-serializer'
def load_driver(name, default_uri)
return false if ENV['ADAPTER'] != name.to_s
begin
DataMapper.setup(name, ENV["#{name.to_s.upcase}_SPEC_URI"] || default_uri)
DataMapper::Repository.adapters[:default] = DataMapper::Repository.adapters[name]
DataMapper::Repository.adapters[:alternate] = DataMapper::Repository.adapters[name]
true
rescue LoadError => e
warn "Could not load do_#{name}: #{e}"
false
end
end
ENV['ADAPTER'] ||= 'sqlite3'
HAS_SQLITE3 = load_driver(:sqlite3, 'sqlite3::memory:')
HAS_MYSQL = load_driver(:mysql, 'mysql://localhost/dm_core_test')
HAS_POSTGRES = load_driver(:postgres, 'postgres://postgres@localhost/dm_core_test')
class SerializerTestHarness
def test(object, *args)
deserialize(object.send(method_name, *args))
end
end
require spec_dir_path + 'lib/serialization_method_shared_spec'
# require fixture resources
Dir[(spec_dir_path + "fixtures/*.rb").to_s].each do |fixture_file|
require fixture_file
end
| require 'pathname'
require 'rubygems'
gem 'dm-core', '0.10.0'
require 'dm-core'
ROOT = Pathname(__FILE__).dirname.parent
require ROOT / 'lib' / 'dm-serializer'
def load_driver(name, default_uri)
return false if ENV['ADAPTER'] != name.to_s
begin
DataMapper.setup(name, ENV["#{name.to_s.upcase}_SPEC_URI"] || default_uri)
DataMapper::Repository.adapters[:default] = DataMapper::Repository.adapters[name]
DataMapper::Repository.adapters[:alternate] = DataMapper::Repository.adapters[name]
true
rescue LoadError => e
warn "Could not load do_#{name}: #{e}"
false
end
end
ENV['ADAPTER'] ||= 'sqlite3'
HAS_SQLITE3 = load_driver(:sqlite3, 'sqlite3::memory:')
HAS_MYSQL = load_driver(:mysql, 'mysql://localhost/dm_core_test')
HAS_POSTGRES = load_driver(:postgres, 'postgres://postgres@localhost/dm_core_test')
class SerializerTestHarness
def test(object, *args)
deserialize(object.send(method_name, *args))
end
end
require ROOT / 'spec' / 'lib' / 'serialization_method_shared_spec'
# require fixture resources
Dir[(ROOT / 'spec' / 'fixtures' / '*.rb').to_s].each do |fixture_file|
require fixture_file
end
|
Add some environment variable toggles for VCR | require 'vcr'
require 'yoga_pants'
VCR.configure do |c|
c.cassette_library_dir = 'fixtures/vcr_cassettes'
c.hook_into :webmock
end
| require 'vcr'
require 'yoga_pants'
VCR.configure do |c|
c.cassette_library_dir = 'fixtures/vcr_cassettes'
c.hook_into :webmock
c.allow_http_connections_when_no_cassette = true if ENV['ALLOW_NO_CASSETTE']
c.ignore_localhost = true if ENV['INTEGRATION']
end
|
Tweak library requires for specs. | require 'doc_repo'
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.disable_monkey_patching!
config.warnings = true
if config.files_to_run.one?
config.default_formatter = 'doc'
end
Kernel.srand config.seed
end
| # This is a very warning riddled gem, load it before we enable warnings
require 'rouge'
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.disable_monkey_patching!
config.warnings = true
if config.files_to_run.one?
config.default_formatter = 'doc'
end
Kernel.srand config.seed
end
# Load our lib after warnings are enabled so we can fix them
require 'doc_repo'
|
Package version is incremented from 0.1.0 to 0.1.1 | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'set_attributes'
s.summary = "Set an object's attributes"
s.version = '0.1.0'
s.authors = ['']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.add_runtime_dependency 'dependency'
s.add_runtime_dependency 'telemetry-logger'
s.add_development_dependency 'minitest'
s.add_development_dependency 'minitest-spec-context', '~> 0'
s.add_development_dependency 'pry', '~> 0'
s.add_development_dependency 'runner', '~> 0'
end
| # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'set_attributes'
s.summary = "Set an object's attributes"
s.version = '0.1.1'
s.authors = ['']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.add_runtime_dependency 'dependency'
s.add_runtime_dependency 'telemetry-logger'
s.add_development_dependency 'minitest'
s.add_development_dependency 'minitest-spec-context', '~> 0'
s.add_development_dependency 'pry', '~> 0'
s.add_development_dependency 'runner', '~> 0'
end
|
Rename virtual_service => rabbitmq_cluster. * Remove un-used attr_reader | require 'stackbuilder/stacks/namespace'
class Stacks::Services::RabbitMQServer < Stacks::MachineDef
attr_reader :virtual_service
def initialize(virtual_service, index, networks = [:mgmt, :prod], location = :primary_site)
super(virtual_service.name + "-" + index, networks, location)
@virtual_service = virtual_service
end
def to_enc
enc = super()
enc.merge!('role::rabbitmq_server' => {
'cluster_nodes' => @virtual_service.cluster_nodes(location),
'vip_fqdn' => @virtual_service.vip_fqdn(:prod, fabric)
},
'server::default_new_mgmt_net_local' => nil)
dependant_instances = @virtual_service.dependant_instance_fqdns(location)
if dependant_instances && !dependant_instances.nil? && dependant_instances != []
enc['role::rabbitmq_server'].merge!('dependant_instances' => dependant_instances,
'dependencies' => @virtual_service.dependency_config(fabric))
end
enc
end
end
| require 'stackbuilder/stacks/namespace'
class Stacks::Services::RabbitMQServer < Stacks::MachineDef
def initialize(rabbitmq_cluster, index, networks = [:mgmt, :prod], location = :primary_site)
super(rabbitmq_cluster.name + "-" + index, networks, location)
@rabbitmq_cluster = rabbitmq_cluster
end
def to_enc
enc = super()
enc.merge!('role::rabbitmq_server' => {
'cluster_nodes' => @rabbitmq_cluster.cluster_nodes(location),
'vip_fqdn' => @rabbitmq_cluster.vip_fqdn(:prod, fabric)
},
'server::default_new_mgmt_net_local' => nil)
dependant_instances = @rabbitmq_cluster.dependant_instance_fqdns(location)
if dependant_instances && !dependant_instances.nil? && dependant_instances != []
enc['role::rabbitmq_server'].merge!('dependant_instances' => dependant_instances,
'dependencies' => @rabbitmq_cluster.dependency_config(fabric))
end
enc
end
end
|
Add spec for publish! method | require 'spec_helper'
describe Publisher do
end | require 'spec_helper'
describe Publisher do
before do
@root = File.expand_path('../', __FILE__)
FileUtils.rm(Publisher::LAST_PUBLISHED_FILE) if File.exist?(Publisher::LAST_PUBLISHED_FILE)
end
context "on publish!" do
it "publish all files" do
AWS::S3::Client.any_instance.expects(:put_object).times(4)
path = File.join(@root, 'sample')
Publisher.publish!('s3.amazonaws.com', 'abc', '123', 'mybucket.amazonaws.com', path, {})
end
end
end |
Remove pin on rake version | # -*- encoding: utf-8 -*-
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "fluent-plugin-systemd"
spec.version = "0.0.5"
spec.authors = ["Ed Robinson"]
spec.email = ["ed@reevoo.com"]
spec.summary = "Input plugin to read from systemd journal."
spec.description = "This is a fluentd input plugin. It reads logs from the systemd journal."
spec.homepage = "https://github.com/reevoo/fluent-plugin-systemd"
spec.license = "MIT"
spec.files = Dir["**/**"].reject { |f| f.match(/^(test|spec|features)\//) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.10"
spec.add_development_dependency "rake", "~> 10.4"
spec.add_development_dependency "test-unit", "~> 2.5"
spec.add_development_dependency "reevoocop"
spec.add_runtime_dependency "fluentd", "~> 0.12"
spec.add_runtime_dependency "systemd-journal", "~> 1.2"
end
| # -*- encoding: utf-8 -*-
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "fluent-plugin-systemd"
spec.version = "0.0.5"
spec.authors = ["Ed Robinson"]
spec.email = ["ed@reevoo.com"]
spec.summary = "Input plugin to read from systemd journal."
spec.description = "This is a fluentd input plugin. It reads logs from the systemd journal."
spec.homepage = "https://github.com/reevoo/fluent-plugin-systemd"
spec.license = "MIT"
spec.files = Dir["**/**"].reject { |f| f.match(/^(test|spec|features)\//) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.10"
spec.add_development_dependency "rake"
spec.add_development_dependency "test-unit", "~> 2.5"
spec.add_development_dependency "reevoocop"
spec.add_runtime_dependency "fluentd", "~> 0.12"
spec.add_runtime_dependency "systemd-journal", "~> 1.2"
end
|
Update gir_ffi to version 0.14.0 | # frozen_string_literal: true
Gem::Specification.new do |s|
s.name = 'gir_ffi-gnome_keyring'
s.version = '0.0.10'
s.summary = 'GirFFI-based binding to GnomeKeyring'
s.description = 'Bindings for GnomeKeyring generated by GirFFI, with overrides.'
s.required_ruby_version = '>= 2.2.0'
s.license = 'LGPL-2.1+'
s.authors = ['Matijs van Zuijlen']
s.email = ['matijs@matijs.net']
s.homepage = 'http://www.github.com/mvz/gir_ffi-gnome_keyring'
s.rdoc_options = ['--main', 'README.md']
s.files = Dir['{lib,test,tasks,examples}/**/*',
'*.md',
'Rakefile',
'COPYING.lIB'] & `git ls-files -z`.split("\0")
s.extra_rdoc_files = ['README.md', 'Changelog.md']
s.test_files = `git ls-files -z -- test`.split("\0")
s.add_runtime_dependency('gir_ffi', ['~> 0.13.0'])
s.add_development_dependency('minitest', ['~> 5.0'])
s.add_development_dependency('rake', ['~> 12.0'])
s.require_paths = ['lib']
end
| # frozen_string_literal: true
Gem::Specification.new do |s|
s.name = 'gir_ffi-gnome_keyring'
s.version = '0.0.10'
s.summary = 'GirFFI-based binding to GnomeKeyring'
s.description = 'Bindings for GnomeKeyring generated by GirFFI, with overrides.'
s.required_ruby_version = '>= 2.2.0'
s.license = 'LGPL-2.1+'
s.authors = ['Matijs van Zuijlen']
s.email = ['matijs@matijs.net']
s.homepage = 'http://www.github.com/mvz/gir_ffi-gnome_keyring'
s.rdoc_options = ['--main', 'README.md']
s.files = Dir['{lib,test,tasks,examples}/**/*',
'*.md',
'Rakefile',
'COPYING.lIB'] & `git ls-files -z`.split("\0")
s.extra_rdoc_files = ['README.md', 'Changelog.md']
s.test_files = `git ls-files -z -- test`.split("\0")
s.add_runtime_dependency('gir_ffi', ['~> 0.14.0'])
s.add_development_dependency('minitest', ['~> 5.0'])
s.add_development_dependency('rake', ['~> 12.0'])
s.require_paths = ['lib']
end
|
Update lita gem version requirement to support version 3, bump version. | Gem::Specification.new do |spec|
spec.name = "lita-likeaboss"
spec.version = "1.0.1"
spec.authors = ["Henrik Sjökvist"]
spec.email = ["henrik.sjokvist@gmail.com"]
spec.description = %q{A Lita handler for outputting random 'like a boss' images.}
spec.summary = %q{A Lita handler for outputting random 'like a boss' images.}
spec.homepage = "https://github.com/henrrrik/lita-likeaboss"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "lita", "~> 2.0"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec", "~> 2.14"
spec.add_development_dependency "simplecov"
spec.add_development_dependency "coveralls"
end
| Gem::Specification.new do |spec|
spec.name = "lita-likeaboss"
spec.version = "1.0.2"
spec.authors = ["Henrik Sjökvist"]
spec.email = ["henrik.sjokvist@gmail.com"]
spec.description = %q{A Lita handler for outputting random 'like a boss' images.}
spec.summary = %q{A Lita handler for outputting random 'like a boss' images.}
spec.homepage = "https://github.com/henrrrik/lita-likeaboss"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "lita", "~> 3.0"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec", "~> 2.14"
spec.add_development_dependency "simplecov"
spec.add_development_dependency "coveralls"
end
|
Drop wiki_type_id from assignment and wiki_types table. | class RemoveWikiTypeFromAssignment < ActiveRecord::Migration
def self.up
execute "alter table assignments drop foreign key `fk_assignments_wiki_types`;"
remove_column :assignments,:wiki_type_id
drop_table "wiki_types"
end
end
| |
Improve spec coverage for Mash. | require File.expand_path(File.join(File.dirname(__FILE__), 'spec_helper'))
describe Mash do
before(:each) do
@hash = { "mash" => "indifferent", :hash => "different" }
end
describe "#initialize" do
it 'converts all keys into strings when param is a Hash' do
mash = Mash.new(@hash)
mash.keys.any? { |key| key.is_a?(Symbol) }.should be(false)
end
it 'converts all Hash values into Mashes if param is a Hash' do
mash = Mash.new :hash => @hash
mash.should be_an_instance_of(Mash)
# sanity check
mash["hash"]["hash"].should == "different"
end
it 'delegates to superclass constructor if param is not a Hash' do
mash = Mash.new("dash berlin")
mash["unexisting key"].should == "dash berlin"
end
end # describe "#initialize"
describe "#key?" do
before(:each) do
@mash = Mash.new(@hash)
end
it 'converts key before lookup' do
@mash.key?("mash").should be(true)
@mash.key?(:mash).should be(true)
@mash.key?("hash").should be(true)
@mash.key?(:hash).should be(true)
@mash.key?(:rainclouds).should be(false)
@mash.key?("rainclouds").should be(false)
end
it 'is aliased as include?' do
@mash.include?("mash").should be(true)
@mash.include?(:mash).should be(true)
@mash.include?("hash").should be(true)
@mash.include?(:hash).should be(true)
@mash.include?(:rainclouds).should be(false)
@mash.include?("rainclouds").should be(false)
end
it 'is aliased as member?' do
@mash.member?("mash").should be(true)
@mash.member?(:mash).should be(true)
@mash.member?("hash").should be(true)
@mash.member?(:hash).should be(true)
@mash.member?(:rainclouds).should be(false)
@mash.member?("rainclouds").should be(false)
end
end # describe "#key?"
end
| |
Update podspec with new version. New version allows for tinting input text and prompt. | Pod::Spec.new do |s|
git_tag = "0.1.6"
s.name = "MBContactPicker"
s.version = git_tag
s.summary = "A contact picker that looks like the one in Apple mail for iOS7. This implementation uses a UICollectionView."
s.description = <<-DESC
MBContactPicker is a library that uses the latest styling and technologies
available on iOS.
I wrote this library to provide an update to the awesome THContactPicker that
our company used in the past. My main goal when I created this library was to build
something that behaved and felt like the native mail app's contact selector.
My secondary goal was to make using it extremely simple while still providing
a high level of flexibility for projects that need it.
DESC
s.homepage = "http://github.com/Citrrus/MBContactPicker"
s.license = 'MIT'
s.author = {
"Matt Bowman" => "mbowman@citrrus.com",
"Matt Hupman" => "mhupman@citrrus.com"
}
s.platform = :ios, '7.0'
s.source = { :git => "https://github.com/Citrrus/MBContactPicker.git", :tag => git_tag }
s.source_files = 'MBContactPicker'
s.requires_arc = true
s.frameworks = 'UIKit'
end
| Pod::Spec.new do |s|
git_tag = "0.2.0"
s.name = "MBContactPicker"
s.version = git_tag
s.summary = "A contact picker that looks like the one in Apple mail for iOS7. This implementation uses a UICollectionView."
s.description = <<-DESC
MBContactPicker is a library that uses the latest styling and technologies
available on iOS.
I wrote this library to provide an update to the awesome THContactPicker that
our company used in the past. My main goal when I created this library was to build
something that behaved and felt like the native mail app's contact selector.
My secondary goal was to make using it extremely simple while still providing
a high level of flexibility for projects that need it.
DESC
s.homepage = "http://github.com/Citrrus/MBContactPicker"
s.license = 'MIT'
s.author = {
"Matt Bowman" => "mbowman@citrrus.com",
"Matt Hupman" => "mhupman@citrrus.com"
}
s.platform = :ios, '7.0'
s.source = { :git => "https://github.com/Citrrus/MBContactPicker.git", :tag => git_tag }
s.source_files = 'MBContactPicker'
s.requires_arc = true
s.frameworks = 'UIKit'
end
|
Add !ghpull as an alias to !ghissue | class GitHub
include Cinch::Plugin
match /ghissue (.+) (.+)/, method: :ghissue
def ghissue(m, repo, issuenum)
issuenum = issuenum.to_i
issueurl = "https://api.github.com/repos/#{repo}/issues/#{issuenum}"
parsed = JSON.parse(RestClient.get(issueurl))
issueorpull = parsed['html_url'].split('/')[5]
issueorpull = 'Issue' if issueorpull == 'issues'
issueorpull = 'Pull' if issueorpull == 'pull'
status = parsed['state']
if status == 'closed'
statusformatted = Format(:bold, Format(:red, 'Closed'))
statusformatted += " by #{parsed['closed_by']['login']}"
end
statusformatted = Format(:bold, Format(:green, 'Open')) if status == 'open'
m.reply "#{issueorpull} ##{issuenum} (#{statusformatted}): #{parsed['html_url']} | #{parsed['title']}"
end
end
| class GitHub
include Cinch::Plugin
match /ghissue (.+) (.+)/, method: :ghissue
match /ghpull (.+) (.+)/, method: :ghissue
def ghissue(m, repo, issuenum)
issuenum = issuenum.to_i
issueurl = "https://api.github.com/repos/#{repo}/issues/#{issuenum}"
parsed = JSON.parse(RestClient.get(issueurl))
issueorpull = parsed['html_url'].split('/')[5]
issueorpull = 'Issue' if issueorpull == 'issues'
issueorpull = 'Pull' if issueorpull == 'pull'
status = parsed['state']
if status == 'closed'
statusformatted = Format(:bold, Format(:red, 'Closed'))
statusformatted += " by #{parsed['closed_by']['login']}"
end
statusformatted = Format(:bold, Format(:green, 'Open')) if status == 'open'
m.reply "#{issueorpull} ##{issuenum} (#{statusformatted}): #{parsed['html_url']} | #{parsed['title']}"
end
end
|
Fix warning: `&' interpreted as argument prefix | module Specinfra
module Backend
module PowerShell
class Command
attr_reader :import_functions, :script
def initialize &block
@import_functions = []
@script = ""
instance_eval &block if block_given?
end
def using *functions
functions.each { |f| import_functions << f }
end
def exec code
@script = code
end
def convert_regexp(target)
case target
when Regexp
target.source
else
target.to_s.gsub '(^\/|\/$)', ''
end
end
def get_identity id
raise "You must provide a specific Windows user/group" if id =~ /(owner|group|others)/
identity = id || 'Everyone'
end
def to_s
@script
end
end
end
end
end
| module Specinfra
module Backend
module PowerShell
class Command
attr_reader :import_functions, :script
def initialize &block
@import_functions = []
@script = ""
instance_eval(&block) if block_given?
end
def using *functions
functions.each { |f| import_functions << f }
end
def exec code
@script = code
end
def convert_regexp(target)
case target
when Regexp
target.source
else
target.to_s.gsub '(^\/|\/$)', ''
end
end
def get_identity id
raise "You must provide a specific Windows user/group" if id =~ /(owner|group|others)/
identity = id || 'Everyone'
end
def to_s
@script
end
end
end
end
end
|
Make ask.wikiedu.org query into a tag | # frozen_string_literal: true
require 'uri'
# Controller for ask.wikiedu.org search form
class AskController < ApplicationController
ASK_ROOT = 'http://ask.wikiedu.org/questions/scope:all/sort:activity-desc/'
def search
if params[:q].blank?
# Default to the 'student' tag
redirect_to "#{ASK_ROOT}tags:student/page:1/"
else
log_to_sentry
query = URI.encode(params[:q])
redirect_to "#{ASK_ROOT}page:1/query:#{query}/"
end
end
private
def log_to_sentry
# Logging to see how this feature gets used
Raven.capture_message 'ask.wikiedu.org query',
level: 'info',
tags: { 'source' => params[:source] },
extra: { query: params[:q], username: current_user&.username }
end
end
| # frozen_string_literal: true
require 'uri'
# Controller for ask.wikiedu.org search form
class AskController < ApplicationController
ASK_ROOT = 'http://ask.wikiedu.org/questions/scope:all/sort:activity-desc/'
def search
if params[:q].blank?
# Default to the 'student' tag
redirect_to "#{ASK_ROOT}tags:student/page:1/"
else
log_to_sentry
query = URI.encode(params[:q])
redirect_to "#{ASK_ROOT}page:1/query:#{query}/"
end
end
private
def log_to_sentry
# Logging to see how this feature gets used
Raven.capture_message 'ask.wikiedu.org query',
level: 'info',
tags: { 'source' => params[:source], 'query' => params[:q] },
extra: { query: params[:q], username: current_user&.username }
end
end
|
Set max age of the cookies to 3 hours | SERVICE_DOMAIN = (url = ENV['ACTION_MAILER_DEFAULT_URL']) ? URI.parse(url).host : nil
{key: '_moj_peoplefinder_session', expire_after: 1.day, httponly: true, max_age: 1.day.to_s, domain: SERVICE_DOMAIN}.tap do |configuration|
configuration[:secure] = (ENV['SSL_ON'] != 'false' ? true : false)
Peoplefinder::Application.config.session_store :cookie_store, configuration
end
| SERVICE_DOMAIN = (url = ENV['ACTION_MAILER_DEFAULT_URL']) ? URI.parse(url).host : nil
{key: '_moj_peoplefinder_session', expire_after: 3.hours, httponly: true, max_age: 3.hours.to_s, domain: SERVICE_DOMAIN}.tap do |configuration|
configuration[:secure] = (ENV['SSL_ON'] != 'false' ? true : false)
Peoplefinder::Application.config.session_store :cookie_store, configuration
end
|
Upgrade Mapbox Studio.app to v0.3.1 | cask :v1 => 'mapbox-studio' do
version '0.2.7'
sha256 '4804b1304e08c31717ede103b13d5d84fecd3d3879b9413e0e73e193f4bdd3fd'
# amazonaws.com is the official download host per the vendor homepage
url "https://mapbox.s3.amazonaws.com/mapbox-studio/mapbox-studio-darwin-x64-v#{version}.zip"
name 'Mapbox Studio'
homepage 'https://www.mapbox.com/mapbox-studio/'
license :bsd
app "mapbox-studio-darwin-x64-v#{version}/Mapbox Studio.app"
end
| cask :v1 => 'mapbox-studio' do
version '0.3.1'
sha256 'ed5cb9ca0db8135caf2b82c30e3b58c4ad1689f7a3b6d05d7ecf82642c95e812'
# amazonaws.com is the official download host per the vendor homepage
url "https://mapbox.s3.amazonaws.com/mapbox-studio/mapbox-studio-darwin-x64-v#{version}.zip"
name 'Mapbox Studio'
homepage 'https://www.mapbox.com/mapbox-studio/'
license :bsd
app "mapbox-studio-darwin-x64-v#{version}/Mapbox Studio.app"
end
|
Add definition for redis gem | #
# Copyright 2014 Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
name "redis-gem"
default_version "3.1.0"
dependency "ruby"
dependency "rubygems"
build do
env = with_standard_compiler_flags(with_embedded_path)
gem "install redis" \
" --version '#{version}'" \
" --bindir '#{install_dir}/embedded/bin'" \
" --no-ri --no-rdoc", env: env
end
| |
Install chef-handler-sns gem version 1.2.0 | # encoding: UTF-8
#
# Cookbook Name:: chef_handler_sns
# Author:: Xabier de Zuazo (<xabier@zuazo.org>)
# Attributes:: default
# Copyright:: Copyright (c) 2014 Onddo Labs, SL.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
default['chef_handler_sns']['topic_arn'] = nil
default['chef_handler_sns']['access_key'] = nil
default['chef_handler_sns']['secret_key'] = nil
default['chef_handler_sns']['token'] = nil
default['chef_handler_sns']['region'] = nil
default['chef_handler_sns']['subject'] = nil
default['chef_handler_sns']['body_template'] = nil
default['chef_handler_sns']['supports'] = {
'exception' => true,
'report' => false
}
default['chef_handler_sns']['version'] = nil
default['chef_handler_sns']['mirror_url'] = nil
| # encoding: UTF-8
#
# Cookbook Name:: chef_handler_sns
# Author:: Xabier de Zuazo (<xabier@zuazo.org>)
# Attributes:: default
# Copyright:: Copyright (c) 2014 Onddo Labs, SL.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
default['chef_handler_sns']['topic_arn'] = nil
default['chef_handler_sns']['access_key'] = nil
default['chef_handler_sns']['secret_key'] = nil
default['chef_handler_sns']['token'] = nil
default['chef_handler_sns']['region'] = nil
default['chef_handler_sns']['subject'] = nil
default['chef_handler_sns']['body_template'] = nil
default['chef_handler_sns']['supports'] = {
'exception' => true,
'report' => false
}
default['chef_handler_sns']['version'] = '1.2.0'
default['chef_handler_sns']['mirror_url'] = nil
|
Remove extraneous space before EOH (causing error) | powershell_script 'Install IIS' do
code <<- EOH
Add-WindowsFeature Web-Server, Web-WebServer, Web-Common-Http, Web-Default-Doc, Web-Dir-Browsing, Web-Http-Errors, Web-Static-Content, Web-Http-Redirect, Web-Health, Web-Http-Logging, Web-Log-Libraries, Web-Request-Monitor, Web-Http-Tracing, Web-Performance, Web-Stat-Compression, Web-Security, Web-Filtering, Web-Basic-Auth, Web-Windows-Auth, Web-App-Dev, Web-Net-Ext, Web-Net-Ext45, Web-Asp-Net, Web-Asp-Net45, Web-ISAPI-Ext, Web-ISAPI-Filter, Web-WebSockets, Web-Mgmt-Tools, Web-Mgmt-Console, Web-Mgmt-Compat, Web-Mgmt-Service
EOH
action :run
not_if "(Get-WindowsFeature -Name Web-Server).Installed"
end
windows_service 'w3svc' do
action [:start, :enable]
end | powershell_script 'Install IIS' do
code <<-EOH
Add-WindowsFeature Web-Server, Web-WebServer, Web-Common-Http, Web-Default-Doc, Web-Dir-Browsing, Web-Http-Errors, Web-Static-Content, Web-Http-Redirect, Web-Health, Web-Http-Logging, Web-Log-Libraries, Web-Request-Monitor, Web-Http-Tracing, Web-Performance, Web-Stat-Compression, Web-Security, Web-Filtering, Web-Basic-Auth, Web-Windows-Auth, Web-App-Dev, Web-Net-Ext, Web-Net-Ext45, Web-Asp-Net, Web-Asp-Net45, Web-ISAPI-Ext, Web-ISAPI-Filter, Web-WebSockets, Web-Mgmt-Tools, Web-Mgmt-Console, Web-Mgmt-Compat, Web-Mgmt-Service
EOH
action :run
not_if "(Get-WindowsFeature -Name Web-Server).Installed"
end
windows_service 'w3svc' do
action [:start, :enable]
end |
Rename charge to position in person serializer | class GobiertoPeople::PersonSerializer < ActiveModel::Serializer
attributes :id, :name, :email, :charge, :bio, :bio_url, :avatar_url, :category, :political_group, :party, :created_at, :updated_at
has_many :content_block_records
def political_group
object.political_group.try(:name)
end
end
| class GobiertoPeople::PersonSerializer < ActiveModel::Serializer
attributes :id, :name, :email, :position, :bio, :bio_url, :avatar_url, :category, :political_group, :party, :created_at, :updated_at
has_many :content_block_records
def political_group
object.political_group.try(:name)
end
def position
object.charge
end
end
|
Update rubocop requirement from ~> 0.78.0 to ~> 0.79.0 | Gem::Specification.new do |spec|
spec.name = 'puppet-lint-no_cron_resources-check'
spec.version = '1.0.1'
spec.homepage = 'https://github.com/deanwilson/no_cron_resources-check'
spec.license = 'MIT'
spec.author = 'Dean Wilson'
spec.email = 'dean.wilson@gmail.com'
spec.files = Dir[
'README.md',
'LICENSE',
'lib/**/*',
'spec/**/*',
]
spec.test_files = Dir['spec/**/*']
spec.summary = 'puppet-lint no_cron_resources check'
spec.description = <<-EOF
Extends puppet-lint to ensure no cron resources are contained in the catalog.
EOF
spec.add_dependency 'puppet-lint', '>= 1.1', '< 3.0'
spec.add_development_dependency 'rspec', '~> 3.9.0'
spec.add_development_dependency 'rspec-its', '~> 1.0'
spec.add_development_dependency 'rspec-collection_matchers', '~> 1.0'
spec.add_development_dependency 'rubocop', '~> 0.78.0'
spec.add_development_dependency 'rake', '~> 13.0.0'
spec.add_development_dependency 'rspec-json_expectations', '~> 2.2'
spec.add_development_dependency 'simplecov', '~> 0.17.1'
end
| Gem::Specification.new do |spec|
spec.name = 'puppet-lint-no_cron_resources-check'
spec.version = '1.0.1'
spec.homepage = 'https://github.com/deanwilson/no_cron_resources-check'
spec.license = 'MIT'
spec.author = 'Dean Wilson'
spec.email = 'dean.wilson@gmail.com'
spec.files = Dir[
'README.md',
'LICENSE',
'lib/**/*',
'spec/**/*',
]
spec.test_files = Dir['spec/**/*']
spec.summary = 'puppet-lint no_cron_resources check'
spec.description = <<-EOF
Extends puppet-lint to ensure no cron resources are contained in the catalog.
EOF
spec.add_dependency 'puppet-lint', '>= 1.1', '< 3.0'
spec.add_development_dependency 'rspec', '~> 3.9.0'
spec.add_development_dependency 'rspec-its', '~> 1.0'
spec.add_development_dependency 'rspec-collection_matchers', '~> 1.0'
spec.add_development_dependency 'rubocop', '~> 0.79.0'
spec.add_development_dependency 'rake', '~> 13.0.0'
spec.add_development_dependency 'rspec-json_expectations', '~> 2.2'
spec.add_development_dependency 'simplecov', '~> 0.17.1'
end
|
Add Quartz as framework dependency | Pod::Spec.new do |s|
s.name = "UIKitExtensions"
s.version = "0.0.13"
s.summary = "A collection of extensions for UIKit framework."
# s.description = <<-DESC
# An optional longer description of UIKitExtensions
#
# * Markdown format.
# * Don't worry about the indent, we strip it!
# DESC
s.homepage = "https://github.com/stanislaw/UIKitExtensions"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "Stanislaw Pankevich" => "s.pankevich@gmail.com" }
s.source = { :git => "https://github.com/stanislaw/UIKitExtensions.git", :tag => s.version.to_s }
s.platform = :ios, '5.0'
s.source_files = 'UIKitExtensions/**/*.{h,m}'
s.header_mappings_dir = 'UIKitExtensions'
s.framework = 'UIKit'
s.weak_frameworks = 'CoreGraphics'
s.requires_arc = true
end
| Pod::Spec.new do |s|
s.name = "UIKitExtensions"
s.version = "0.0.14"
s.summary = "A collection of extensions for UIKit framework."
# s.description = <<-DESC
# An optional longer description of UIKitExtensions
#
# * Markdown format.
# * Don't worry about the indent, we strip it!
# DESC
s.homepage = "https://github.com/stanislaw/UIKitExtensions"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "Stanislaw Pankevich" => "s.pankevich@gmail.com" }
s.source = { :git => "https://github.com/stanislaw/UIKitExtensions.git", :tag => s.version.to_s }
s.platform = :ios, '5.0'
s.source_files = 'UIKitExtensions/**/*.{h,m}'
s.header_mappings_dir = 'UIKitExtensions'
s.frameworks = 'UIKit', 'QuartzCore'
s.weak_frameworks = 'CoreGraphics'
s.requires_arc = true
end
|
Use Faker job titles instead of creating them by hand | namespace :db do
desc "Fill database with sample data"
task :populate => :environment do
make_users
make_jobs
end
end
def make_users
20.times do |n|
provider = "Github"
uid = "1234abd"
name = Faker::Name.name
email = "test-#{n}@test.com"
nickname = "test#{n}"
user = User.new(
:provider => provider,
:uid => uid,
:name => name,
:email => email,
:nickname => nickname
)
user.save
end
end
def make_jobs
positions = [
"Senior Developer",
"Junior Developer",
"Code Ninja",
"Code Surfer",
"Pro Hacker",
"Programmer"
]
20.times do |n|
job = Job.new(
title: positions.sample,
description: "#{Faker::Lorem.paragraph}",
company_name: Faker::Company.name,
company_website: Faker::Internet.domain_name,
how_to_apply: "Send an email to #{Faker::Internet.email}",
approved: true
).save
end
end | namespace :db do
desc "Fill database with sample data"
task :populate => :environment do
make_users
make_jobs
end
end
def make_users
20.times do |n|
provider = "Github"
uid = "1234abd"
name = Faker::Name.name
email = "test-#{n}@test.com"
nickname = "test#{n}"
user = User.new(
:provider => provider,
:uid => uid,
:name => name,
:email => email,
:nickname => nickname
)
user.save
end
end
def make_jobs
20.times do |n|
job = Job.new(
title: Faker::Name.title,
description: "#{Faker::Lorem.paragraph}",
company_name: Faker::Company.name,
company_website: Faker::Internet.domain_name,
how_to_apply: "Send an email to #{Faker::Internet.email}",
approved: true
).save
end
end |
Add specs for new User model validations | require 'rails_helper'
describe User do
context "validations" do
it { is_expected.to validate_presence_of :name }
end
context "associations" do
it { is_expected.to have_many :timeslots}
it { is_expected.to have_many :bookings}
end
end
| require 'rails_helper'
describe User do
context "validations" do
it { is_expected.to validate_presence_of :name }
it { is_expected.to validate_presence_of :email_notify }
it { is_expected.to validate_presence_of :text_notify }
end
context "when not requesting text notifications without a cellphone" do
subject { User.new(text_notify: false) }
it { is_expected.not_to validate_presence_of :cellphone }
end
context "when requesting text notifications without a cellphone" do
subject { User.new(text_notify: true) }
it {
is_expected.to validate_presence_of(:cellphone)
.with_message 'must be present for text notifications'
}
end
context "associations" do
it { is_expected.to have_many :timeslots}
it { is_expected.to have_many :bookings}
end
end
|
Switch password strategy to BCryptMigrationFromSHA1. | unless Rails.env.maintenance?
Clearance.configure do |config|
config.mailer_sender = "donotreply@rubygems.org"
config.secure_cookie = true
config.password_strategy = Clearance::PasswordStrategies::SHA1
end
end
| unless Rails.env.maintenance?
Clearance.configure do |config|
config.mailer_sender = "donotreply@rubygems.org"
config.secure_cookie = true
config.password_strategy = Clearance::PasswordStrategies::BCryptMigrationFromSHA1
end
end
|
Add rspec test for munin.conf template | require 'spec_helper'
describe 'munin::master', :type => 'class' do
it {
should contain_package('munin')
}
end
| require 'spec_helper'
describe 'munin::master', :type => 'class' do
it {
should contain_package('munin')
}
it do
should contain_file('/etc/munin/munin.conf')\
.with_content(/^graph_strategy cgi$/)
end
context 'with graph_strategy => cron' do
let(:params) { {:graph_strategy => 'cron'} }
it do
should contain_file('/etc/munin/munin.conf')\
.with_content(/^graph_strategy cron$/)
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.