Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Change syntax on incoming references to follow style | module Contentful
# Method to retrieve references (incoming links) for a given entry or asset
module ResourceReferences
# Gets a collection of entries which links to current entry
#
# @param [Contentful::Client] client
# @param [Hash] query
#
# @return [Contentful::Array<Contentful::Entry>, false]
def incoming_references(client = nil, query = {})
return false unless client
query = is_a?(Contentful::Entry) ? query.merge(links_to_entry: id) : query.merge(links_to_asset: id)
client.entries query
end
end
end
| module Contentful
# Method to retrieve references (incoming links) for a given entry or asset
module ResourceReferences
# Gets a collection of entries which links to current entry
#
# @param [Contentful::Client] client
# @param [Hash] query
#
# @return [Contentful::Array<Contentful::Entry>, false]
def incoming_references(client = nil, query = {})
return false unless client
query = is_a?(Contentful::Entry) ? query.merge(links_to_entry: id) : query.merge(links_to_asset: id)
client.entries(query)
end
end
end
|
Add Sass to dependent gem list | $:.push File.expand_path("../lib", __FILE__)
require "css_inliner/version"
Gem::Specification.new do |s|
s.name = "css_inliner"
s.version = CSSInliner::VERSION
s.authors = ["KITAITI Makoto"]
s.email = ["KitaitiMakoto@gmail.com"]
s.homepage = "http://gitorious.org/css_inliner"
s.summary = %q{inline CSS into HTML attribute of elements}
s.description = %q{
inline CSS from external file(s) and/or style elment(s) in head element
into style attibute of HTML elements
}
# s.rubyforge_project = "css_inliner"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.has_rdoc = false
s.add_runtime_dependency "nokogiri", '~> 1'
s.add_runtime_dependency "css_parser", '~> 1'
s.add_development_dependency "test-unit", '~> 2'
s.add_development_dependency "cover_me", '~> 1'
s.add_development_dependency "yard"
end
| $:.push File.expand_path("../lib", __FILE__)
require "css_inliner/version"
Gem::Specification.new do |s|
s.name = "css_inliner"
s.version = CSSInliner::VERSION
s.authors = ["KITAITI Makoto"]
s.email = ["KitaitiMakoto@gmail.com"]
s.homepage = "http://gitorious.org/css_inliner"
s.summary = %q{inline CSS into HTML attribute of elements}
s.description = %q{
inline CSS from external file(s) and/or style elment(s) in head element
into style attibute of HTML elements
}
# s.rubyforge_project = "css_inliner"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.has_rdoc = false
s.add_runtime_dependency "nokogiri", '~> 1'
s.add_runtime_dependency "css_parser", '~> 1'
s.add_runtime_dependency "sass", '~> 3'
s.add_development_dependency "test-unit", '~> 2'
s.add_development_dependency "cover_me", '~> 1'
s.add_development_dependency "yard"
end
|
Fix more rspec syntax deprecation errors. | require 'spec_helper'
describe 'Mina' do
it '#invoke should work' do
rake {
task :clone do
queue 'git clone'
end
}
2.times {
rake { invoke :clone }
}
rake.commands.should == ['git clone']
end
it '#invoke should work with :reenable option' do
rake {
task :pull do
queue 'git pull'
end
}
2.times {
rake { invoke :pull, :reenable => true }
}
rake.commands.should == ['git pull', 'git pull']
end
it '#invoke with task arguments should work with :reenable option' do
rake {
task :hello, [:world] do |t, args|
queue "echo Hello #{args[:world]}"
end
}
%w(World Pirate).each { |name|
rake { invoke :"hello[#{name}]", :reenable => true }
}
rake.commands.should == ['echo Hello World', 'echo Hello Pirate']
end
end
| require 'spec_helper'
describe 'Mina' do
it '#invoke should work' do
rake {
task :clone do
queue 'git clone'
end
}
2.times {
rake { invoke :clone }
}
expect(rake.commands).to eql ['git clone']
end
it '#invoke should work with :reenable option' do
rake {
task :pull do
queue 'git pull'
end
}
2.times {
rake { invoke :pull, :reenable => true }
}
expect(rake.commands).to eql['git pull', 'git pull']
end
it '#invoke with task arguments should work with :reenable option' do
rake {
task :hello, [:world] do |t, args|
queue "echo Hello #{args[:world]}"
end
}
%w(World Pirate).each { |name|
rake { invoke :"hello[#{name}]", :reenable => true }
}
expect(rake.commands).to eql ['echo Hello World', 'echo Hello Pirate']
end
end
|
Add the license to the gemspec | # encoding: utf-8
require File.expand_path('../lib/google-civic/version', __FILE__)
Gem::Specification.new do |gem|
gem.add_dependency 'addressable', '~> 2.2'
gem.add_dependency 'faraday', '~> 0.8'
gem.add_dependency 'faraday_middleware', '~> 0.8'
gem.add_dependency 'hashie', '~> 2.0'
gem.add_dependency 'multi_json', '~> 1.8'
gem.add_development_dependency 'rake'
gem.add_development_dependency 'rdiscount'
gem.add_development_dependency 'rspec'
gem.add_development_dependency 'simplecov'
gem.add_development_dependency 'webmock'
gem.add_development_dependency 'yard'
gem.author = "Ryan Resella"
gem.description = %q{A Ruby wrapper for the Google Civic API}
gem.email = 'ryan@codeforamerica.org'
gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)}
gem.files = `git ls-files`.split("\n")
gem.homepage = ''
gem.name = 'google-civic'
gem.require_paths = ['lib']
gem.summary = gem.description
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.version = GoogleCivic::VERSION
end
| # encoding: utf-8
require File.expand_path('../lib/google-civic/version', __FILE__)
Gem::Specification.new do |gem|
gem.add_dependency 'addressable', '~> 2.2'
gem.add_dependency 'faraday', '~> 0.8'
gem.add_dependency 'faraday_middleware', '~> 0.8'
gem.add_dependency 'hashie', '~> 2.0'
gem.add_dependency 'multi_json', '~> 1.8'
gem.add_development_dependency 'rake'
gem.add_development_dependency 'rdiscount'
gem.add_development_dependency 'rspec'
gem.add_development_dependency 'simplecov'
gem.add_development_dependency 'webmock'
gem.add_development_dependency 'yard'
gem.author = "Ryan Resella"
gem.description = %q{A Ruby wrapper for the Google Civic API}
gem.email = 'ryan@codeforamerica.org'
gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)}
gem.files = `git ls-files`.split("\n")
gem.homepage = ''
gem.license = 'MIT'
gem.name = 'google-civic'
gem.require_paths = ['lib']
gem.summary = gem.description
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.version = GoogleCivic::VERSION
end
|
Add spec for validity check of dice roll | require 'rails_helper'
RSpec.describe DiceRoll, type: :event do
pending "Test expecting dice roll passes"
pending "Test opposite"
pending "Test not started"
pending "Test current turn and not"
end
| require 'rails_helper'
RSpec.describe DiceRoll, type: :event do
pending "Test expecting dice roll passes"
pending "Test opposite"
pending "Test not started"
pending "Test current turn and not"
let(:game_state) do
instance_double("GameState").tap do |game_state|
end
end
subject(:event) { DiceRoll.new(amount: amount) }
let(:amount) { nil }
describe "checking validity" do
before do
expect(game_state).to receive(:started?).and_return(started)
end
context "when the game is not started yet" do
let(:started) { false }
describe "#can_apply?" do
subject { event.can_apply?(game_state) }
it { is_expected.to be_falsey }
end
end
context "when the game is started" do
let(:started) { true }
before do
expect(game_state).to receive(:expecting_rolls).and_return(expecting_rolls)
end
context "when I can't roll the dice" do
let(:expecting_rolls) { 0 }
describe "#can_apply?" do
subject { event.can_apply?(game_state) }
it { is_expected.to be_falsey }
end
end
context "when I can roll the dice" do
let(:expecting_rolls) { 1 }
describe "#can_apply?" do
subject { event.can_apply?(game_state) }
it { is_expected.to be_truthy }
end
end
end
end
describe "applying the event" do
end
end
|
Allow to define a search column/value. | # This provides convenience-methods to directly operate on the database, without
# relying on the existence of model methods (except for `id`).
# It allows to perform data migrations which won't fail because of renamed
# or removed model-methods.
class MigrationWithData < ActiveRecord::Migration
def select_attributes(record, *keys)
attributes = keys.map do |key|
record.class.where(id: record.id).pluck(key).first
end
Hash[keys.zip(attributes)]
end
def update_attributes!(record, **attributes)
record.update_attributes!(attributes, without_protection: true)
end
end
| # This provides convenience-methods to directly operate on the database, without
# relying on the existence of model methods (except for `id`).
# It allows to perform data migrations which won't fail because of renamed
# or removed model-methods.
class MigrationWithData < ActiveRecord::Migration
def select_attributes(record, *keys,
search_column: :id, search_value: record.id)
attributes = keys.map do |key|
record.class.where(search_column => search_value).pluck(key).first
end
Hash[keys.zip(attributes)]
end
def update_attributes!(record, **attributes)
record.update_attributes!(attributes, without_protection: true)
end
end
|
Remove ruby 2.7 deprecation warning | # encoding: utf-8
module Formtastic
# @private
module I18n
DEFAULT_SCOPE = [:formtastic].freeze
DEFAULT_VALUES = YAML.load_file(File.expand_path("../../locale/en.yml", __FILE__))["en"]["formtastic"].freeze
SCOPES = [
'%{model}.%{nested_model}.%{action}.%{attribute}',
'%{model}.%{nested_model}.%{attribute}',
'%{nested_model}.%{action}.%{attribute}',
'%{nested_model}.%{attribute}',
'%{model}.%{action}.%{attribute}',
'%{model}.%{attribute}',
'%{attribute}'
]
class << self
def translate(*args)
key = args.shift.to_sym
options = args.extract_options!
options.reverse_merge!(:default => DEFAULT_VALUES[key])
options[:scope] = [DEFAULT_SCOPE, options[:scope]].flatten.compact
::I18n.translate(key, *(args << options))
end
alias :t :translate
end
end
end
| # encoding: utf-8
module Formtastic
# @private
module I18n
DEFAULT_SCOPE = [:formtastic].freeze
DEFAULT_VALUES = YAML.load_file(File.expand_path("../../locale/en.yml", __FILE__))["en"]["formtastic"].freeze
SCOPES = [
'%{model}.%{nested_model}.%{action}.%{attribute}',
'%{model}.%{nested_model}.%{attribute}',
'%{nested_model}.%{action}.%{attribute}',
'%{nested_model}.%{attribute}',
'%{model}.%{action}.%{attribute}',
'%{model}.%{attribute}',
'%{attribute}'
]
class << self
def translate(*args)
key = args.shift.to_sym
options = args.extract_options!
options.reverse_merge!(:default => DEFAULT_VALUES[key])
options[:scope] = [DEFAULT_SCOPE, options[:scope]].flatten.compact
::I18n.translate(key, *args, **options)
end
alias :t :translate
end
end
end
|
Mark minitest specific gems as development dependency | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "facebook_canvas/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "facebook_canvas"
s.version = FacebookCanvas::VERSION
s.authors = ["André Stuhrmann"]
s.email = ["as@neopoly.de"]
s.summary = "Rails engine for Facebook's canvas integration."
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["test/**/*"]
s.add_dependency "rails"
s.add_dependency "minitest-rails"
s.add_dependency "minitest-focus"
end
| $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "facebook_canvas/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "facebook_canvas"
s.version = FacebookCanvas::VERSION
s.authors = ["André Stuhrmann"]
s.email = ["as@neopoly.de"]
s.summary = "Rails engine for Facebook's canvas integration."
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["test/**/*"]
s.add_dependency "rails"
s.add_development_dependency "minitest-rails"
s.add_development_dependency "minitest-focus"
end
|
Remove entrust certificates and update Partner API endpoint | module XeroGateway
class PartnerApp < Gateway
class CertificateRequired < StandardError; end
NO_SSL_CLIENT_CERT_MESSAGE = "You need to provide a client ssl certificate and key pair (these are the ones you got from Entrust and should not be password protected) as :ssl_client_cert and :ssl_client_key (should be .crt or .pem files)"
NO_PRIVATE_KEY_ERROR_MESSAGE = "You need to provide your private key (corresponds to the public key you uploaded at api.xero.com) as :private_key_file (should be .crt or .pem files)"
def_delegators :client, :session_handle, :renew_access_token, :authorization_expires_at
def initialize(consumer_key, consumer_secret, options = {})
raise CertificateRequired.new(NO_SSL_CLIENT_CERT_MESSAGE) unless options[:ssl_client_cert]
raise CertificateRequired.new(NO_SSL_CLIENT_CERT_MESSAGE) unless options[:ssl_client_key]
raise CertificateRequired.new(NO_PRIVATE_KEY_ERROR_MESSAGE) unless options[:private_key_file]
options.merge!(
:site => "https://api-partner.network.xero.com",
:authorize_url => 'https://api.xero.com/oauth/Authorize',
:signature_method => 'RSA-SHA1',
:ssl_client_cert => OpenSSL::X509::Certificate.new(File.read(options[:ssl_client_cert])),
:ssl_client_key => OpenSSL::PKey::RSA.new(File.read(options[:ssl_client_key])),
:private_key_file => options[:private_key_file]
)
@xero_url = options[:xero_url] || "https://api-partner.xero.com/api.xro/2.0"
@client = OAuth.new(consumer_key, consumer_secret, options)
end
def set_session_handle(handle)
client.session_handle = handle
end
end
end
| module XeroGateway
class PartnerApp < Gateway
class CertificateRequired < StandardError; end
NO_PRIVATE_KEY_ERROR_MESSAGE = "You need to provide your private key (corresponds to the public key you uploaded at api.xero.com) as :private_key_file (should be .crt or .pem files)"
def_delegators :client, :session_handle, :renew_access_token, :authorization_expires_at
def initialize(consumer_key, consumer_secret, options = {})
raise CertificateRequired.new(NO_PRIVATE_KEY_ERROR_MESSAGE) unless options[:private_key_file]
defaults = {
:site => "https://api.xero.com",
:authorize_url => 'https://api.xero.com/oauth/Authorize',
:signature_method => 'RSA-SHA1',
}
options = defaults.merge(options)
super(consumer_key, consumer_secret, options)
end
def set_session_handle(handle)
client.session_handle = handle
end
end
end
|
Delete commented out request stub | require 'test_helper'
class FeedEntryUpdateJobTest < ActiveJob::TestCase
let(:job) { FeedEntryUpdateJob.new }
describe "create" do
before {
stub_request(:get, "http://serialpodcast.org/sites/all/modules/custom/serial/img/serial-itunes-logo.png").
to_return(:status => 200, :body => test_file('/fixtures/transistor1400.jpg'), :headers => {})
#
# stub_request(:get, "http://cdn.transistor.prx.org/wp-content/uploads/powerpress/transistor300.png").
# to_return(:status => 200, :body => test_file('/fixtures/transistor300.png'), :headers => {})
}
it 'handles a feed entry update' do
data = json_file(:crier_entry)
Task.stub :new_fixer_sqs_client, SqsMock.new do
job.receive_feed_entry_update(data)
end
end
end
end
| require 'test_helper'
class FeedEntryUpdateJobTest < ActiveJob::TestCase
let(:job) { FeedEntryUpdateJob.new }
describe "create" do
before {
stub_request(:get, "http://serialpodcast.org/sites/all/modules/custom/serial/img/serial-itunes-logo.png").
to_return(:status => 200, :body => test_file('/fixtures/transistor1400.jpg'), :headers => {})
}
it 'handles a feed entry update' do
data = json_file(:crier_entry)
Task.stub :new_fixer_sqs_client, SqsMock.new do
job.receive_feed_entry_update(data)
end
end
end
end
|
Bump gem version to 0.4.0 | # frozen_string_literal: true
module Redress
# Gem identity information.
module Identity
def self.name
'redress'
end
def self.label
'Redress'
end
def self.version
'0.3.2'
end
def self.version_label
"#{label} #{version}"
end
end
end
| # frozen_string_literal: true
module Redress
# Gem identity information.
module Identity
def self.name
'redress'
end
def self.label
'Redress'
end
def self.version
'0.4.0'
end
def self.version_label
"#{label} #{version}"
end
end
end
|
Add command line argument for year | require './calendar'
Mortalical::Calendar.generate(1995, !ARGV.include?("--letter"), !ARGV.include?("--nofill")) | require './calendar'
Mortalical::Calendar.generate(ARGV[0].to_i, !ARGV.include?("--letter"), !ARGV.include?("--nofill")) |
Add rake task for adding admin to a user | namespace :roles do
desc 'Create Role::DEFAULTS roles'
task :create => :environment do
Role::DEFAULTS.each do |name, title|
role = Role.new
role.name = name
if role.valid?
role.save
puts '-'*10
puts "Role '#{name}' created."
else
puts '-'*10
puts "Role '#{name}' could not be created: "
role.errors.each do |field, message|
puts "#{field}: #{message}"
end
end
end
end
end
| namespace :roles do
desc 'Create Role::DEFAULTS roles'
task :create => :environment do
Role::DEFAULTS.each do |name, title|
role = Role.new
role.name = name
if role.valid?
role.save
puts '-'*10
puts "Role '#{name}' created."
else
puts '-'*10
puts "Role '#{name}' could not be created: "
role.errors.each do |field, message|
puts "#{field}: #{message}"
end
end
end
end
desc 'Grant admin role to user_id'
task :grant_admin, [:email, :provider] => :environment do |t, args|
args.with_defaults(:provider => 'identity')
user = args.provider.classify.constantize.where(email: args.email).first.user
user.add_role('admin')
puts "User #{user.name} is now an admin!"
end
end
|
Add missing sanitise_boundaries method that the API controller was trying to call. | module MapBoundary
def check_boundaries(min_lon, min_lat, max_lon, max_lat)
# check the bbox is sane
unless min_lon <= max_lon
raise("The minimum longitude must be less than the maximum longitude, but it wasn't")
end
unless min_lat <= max_lat
raise("The minimum latitude must be less than the maximum latitude, but it wasn't")
end
unless min_lon >= -180 && min_lat >= -90 && max_lon <= 180 && max_lat <= 90
raise("The latitudes must be between -90 and 90, and longitudes between -180 and 180")
end
# check the bbox isn't too large
requested_area = (max_lat-min_lat)*(max_lon-min_lon)
if requested_area > APP_CONFIG['max_request_area']
raise("The maximum bbox size is " + APP_CONFIG['max_request_area'].to_s +
", and your request was too large. Either request a smaller area, or use planet.osm")
end
end
end
| module MapBoundary
def sanitise_boundaries(bbox)
min_lon = [bbox[0].to_f,-180].max
min_lat = [bbox[1].to_f,-90].max
max_lon = [bbox[2].to_f,+180].min
max_lat = [bbox[3].to_f,+90].min
return min_lon, min_lat, max_lon, max_lat
end
def check_boundaries(min_lon, min_lat, max_lon, max_lat)
# check the bbox is sane
unless min_lon <= max_lon
raise("The minimum longitude must be less than the maximum longitude, but it wasn't")
end
unless min_lat <= max_lat
raise("The minimum latitude must be less than the maximum latitude, but it wasn't")
end
unless min_lon >= -180 && min_lat >= -90 && max_lon <= 180 && max_lat <= 90
raise("The latitudes must be between -90 and 90, and longitudes between -180 and 180")
end
# check the bbox isn't too large
requested_area = (max_lat-min_lat)*(max_lon-min_lon)
if requested_area > APP_CONFIG['max_request_area']
raise("The maximum bbox size is " + APP_CONFIG['max_request_area'].to_s +
", and your request was too large. Either request a smaller area, or use planet.osm")
end
end
end
|
Add specs for day methods | require 'spec_helper'
describe Yr::Day do
let(:period0) { build :period, id: 0 }
let(:period1) { build :period, id: 1 }
let(:period2) { build :period, id: 2 }
let(:period3) { build :period, id: 3 }
let(:period4) { build :period, id: 4 }
let(:periods) { [period0, period1, period2, period3, period4] }
subject { build :day, periods: periods }
describe "#day_period" do
context "period 2 is there" do
it "returns period 2" do
expect(subject.day_period).to eq(period2)
end
end
context "period 2 has passed" do
let(:day) { build :day, periods: periods[3,5] }
it "returns period 3" do
expect(day.day_period).to eq(period3)
end
end
end
describe "#temperature" do
it "returns the temperature for day period"
end
describe "#symbol" do
it "returns the symbol for day period"
end
describe "#pressure" do
it "returns the pressure for day period"
end
describe "#precipitation" do
it "returns the precipitation for day period"
end
end
| require 'spec_helper'
describe Yr::Day do
let(:period0) { build :period, id: 0 }
let(:period1) { build :period, id: 1 }
let(:period2) { build :period, id: 2 }
let(:period3) { build :period, id: 3 }
let(:period4) { build :period, id: 4 }
let(:periods) { [period0, period1, period2, period3, period4] }
subject { build :day, periods: periods }
describe "#day_period" do
context "period 2 is there" do
it "returns period 2" do
expect(subject.day_period).to eq(period2)
end
end
context "period 2 has passed" do
let(:day) { build :day, periods: periods[3,5] }
it "returns period 3" do
expect(day.day_period).to eq(period3)
end
end
end
describe "#temperature" do
it "returns the temperature for day period" do
expect(subject.temperature).to eq(period2.temperature)
end
end
describe "#symbol" do
it "returns the symbol for day period" do
expect(subject.symbol).to eq(period2.symbol)
end
end
describe "#pressure" do
it "returns the pressure for day period" do
expect(subject.pressure).to eq(period2.pressure)
end
end
describe "#precipitation" do
it "returns the precipitation for day period" do
expect(subject.precipitation).to eq(period2.precipitation)
end
end
end
|
Add solution to problem 9. | def p9
(1..1000).each do |a|
(1..a).each do |b|
c = Math.sqrt((a**2 + b**2).to_f)
return [a, b, c.to_i].reduce(&:*) if c % 1 == 0 && (a+b+c.to_i == 1000)
end
end
end
puts p9 | |
Add gregbeech as an author (at mezis' request) | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'polint/version'
Gem::Specification.new do |spec|
spec.name = "polint"
spec.version = Polint::VERSION
spec.authors = ["Julien Letessier"]
spec.email = ["julien.letessier@gmail.com"]
spec.summary = %q{A linter for Uniforum PO files.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "pry-byebug"
spec.add_development_dependency "guard-rspec"
spec.add_dependency "term-ansicolor"
spec.add_dependency "parslet", "~> 1.7", ">= 1.7.1"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'polint/version'
Gem::Specification.new do |spec|
spec.name = "polint"
spec.version = Polint::VERSION
spec.authors = ["Julien Letessier", "Greg Beech"]
spec.email = ["julien.letessier@gmail.com", "greg@gregbeech.com"]
spec.summary = %q{A linter for Uniforum PO files.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "pry-byebug"
spec.add_development_dependency "guard-rspec"
spec.add_dependency "term-ansicolor"
spec.add_dependency "parslet", "~> 1.7", ">= 1.7.1"
end
|
Remove conditional by using a better default value | require 'pry'
class TwoFer
def self.two_fer(name=nil)
if name
"One for #{name}, one for me."
else
"One for you, one for me."
end
end
end
| require 'pry'
class TwoFer
def self.two_fer(person='you')
"One for #{person}, one for me."
end
end
|
Add new fields to users table | class UpdateUser < ActiveRecord::Migration
def change_table :users do |t|
t.boolean :email_notify, null: false, default: true
t.boolean :text_notify, null: false, default: false
t.string :cellphone, limit: 15,
end
end
| |
Add rspec and cucumber to project | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "feedback/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "feedback"
s.version = Feedback::VERSION
s.authors = ["Phil, Rachel, Ryan"]
s.email = ["development.team@moneyadviceservice.org.uk"]
s.homepage = "http://www.moneyadviceservice.org.uk"
s.summary = "Allow visitors to submit feedback"
s.description = ""
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.add_dependency "rails", "~> 4.1.8"
s.add_development_dependency 'mas-development_dependencies'
end
| $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "feedback/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "feedback"
s.version = Feedback::VERSION
s.authors = ["Phil, Rachel, Ryan"]
s.email = ["development.team@moneyadviceservice.org.uk"]
s.homepage = "http://www.moneyadviceservice.org.uk"
s.summary = "Allow visitors to submit feedback"
s.description = ""
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.add_dependency "rails", "~> 4.1.8"
s.add_development_dependency 'mas-development_dependencies'
s.add_development_dependency 'rspec'
s.add_development_dependency 'rspec-rails'
s.add_development_dependency 'cucumber'
s.add_development_dependency 'cucumber-rails'
end
|
Remove '<= 1.3.1' from AFNetworking dependency | Pod::Spec.new do |s|
s.name = 'AFNetworkingMeter'
s.version = '0.0.6'
# s.license = 'MIT'
# s.summary = ''
s.homepage = 'https://github.com/stanislaw/AFNetworkingMeter'
# s.authors = { 'Mattt Thompson' => 'm@mattt.me' }
s.source = { :git => 'https://github.com/stanislaw/AFNetworkingMeter.git', :tag => s.version.to_s }
s.source_files = 'AFNetworkingMeter/*.{h,m}'
s.private_header_files = 'AFNetworkingMeter/AFNetworkingMeterData.h, AFNetworkingMeter/AFHTTPRequestOperation+StartDate.h'
s.requires_arc = true
s.ios.deployment_target = '5.0'
s.osx.deployment_target = '10.7'
s.dependency 'AFNetworking', '<= 1.3.1'
end
| Pod::Spec.new do |s|
s.name = 'AFNetworkingMeter'
s.version = '0.0.7'
# s.license = 'MIT'
# s.summary = ''
s.homepage = 'https://github.com/stanislaw/AFNetworkingMeter'
# s.authors = { 'Mattt Thompson' => 'm@mattt.me' }
s.source = { :git => 'https://github.com/stanislaw/AFNetworkingMeter.git', :tag => s.version.to_s }
s.source_files = 'AFNetworkingMeter/*.{h,m}'
s.private_header_files = 'AFNetworkingMeter/AFNetworkingMeterData.h, AFNetworkingMeter/AFHTTPRequestOperation+StartDate.h'
s.requires_arc = true
s.ios.deployment_target = '5.0'
s.osx.deployment_target = '10.7'
s.dependency 'AFNetworking'
end
|
Raise unauthorized exception when 401 | require 'faraday'
module Gmail
class Client
def initialize(token, username: 'me')
@username = username
@connection = Faraday.new('https://www.googleapis.com/gmail/v1/users/me') do |conn|
conn.request :oauth2, token
conn.request :json
conn.response :json, :content_type => /\bjson$/
conn.use :instrumentation
conn.adapter Faraday.default_adapter
end
end
def messages(query: '')
return enum_for(__method__) unless block_given?
response = @connection.get('messages', q: query)
response.body.fetch('messages').lazy.each do |ref|
yield Message.new(@connection.get("messages/#{ref['id']}").body)
end
end
end
end
| require 'faraday'
module Gmail
class Client
def initialize(token, username: 'me')
@username = username
@connection = Faraday.new('https://www.googleapis.com/gmail/v1/users/me') do |conn|
conn.request :oauth2, token
conn.request :json
conn.response :json, :content_type => /\bjson$/
conn.use :instrumentation
conn.adapter Faraday.default_adapter
end
end
def messages(query: '')
return enum_for(__method__) unless block_given?
response = @connection.get('messages', q: query)
raise Unauthorized if response.status == 401
response.body.fetch('messages').lazy.each do |ref|
yield Message.new(@connection.get("messages/#{ref['id']}").body)
end
end
end
Unauthorized = Class.new(StandardError)
end
|
Add -s and minute to --say switch | require 'optparse'
require 'ostruct'
class TimerCLI
def self.parse(args)
options = OpenStruct.new
options.messages = []
opt_parser = OptionParser.new do |opts|
opts.banner = "Usage: subtime [options]"
opts.separator ""
opts.separator "Specific options:"
opts.on("-m", "--minutes MINUTES", Integer,
"Total number of minutes to run timer") do |mins|
options.minutes = mins
end
opts.on("--say [MESSAGE]", "Message to say") do |message|
options.messages << message
end
opts.separator ""
opts.separator "Common options:"
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end
opt_parser.parse!(args)
options
end
end
| require 'optparse'
require 'ostruct'
class TimerCLI
def self.parse(args)
options = OpenStruct.new
options.messages = {}
opt_parser = OptionParser.new do |opts|
opts.banner = "Usage: subtime [options]"
opts.separator ""
opts.separator "Specific options:"
opts.on("-m", "--minutes MINUTES", Integer,
"Total number of minutes to run timer") do |mins|
options.minutes = mins
end
opts.on("-s", "--say [MINUTE MESSAGE]", "Message to say") do |minute, message|
options.messages[minute] = message
end
opts.separator ""
opts.separator "Common options:"
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end
opt_parser.parse!(args)
options
end
end
|
Remove an obsolete reference to RubyForge. | require File.expand_path('../lib/yard/version', __FILE__)
Gem::Specification.new do |s|
s.name = "yard"
s.summary = "Documentation tool for consistent and usable documentation in Ruby."
s.description = <<-eof
YARD is a documentation generation tool for the Ruby programming language.
It enables the user to generate consistent, usable documentation that can be
exported to a number of formats very easily, and also supports extending for
custom Ruby constructs such as custom class level definitions.
eof
s.version = YARD::VERSION
s.date = Time.now.strftime('%Y-%m-%d')
s.author = "Loren Segal"
s.email = "lsegal@soen.ca"
s.homepage = "http://yardoc.org"
s.platform = Gem::Platform::RUBY
s.files = Dir.glob("{docs,bin,lib,spec,templates,benchmarks}/**/*") +
['CHANGELOG.md', 'LICENSE', 'LEGAL', 'README.md', 'Rakefile', '.yardopts', __FILE__]
s.require_paths = ['lib']
s.executables = ['yard', 'yardoc', 'yri']
s.has_rdoc = 'yard'
s.rubyforge_project = 'yard'
s.license = 'MIT' if s.respond_to?(:license=)
end | require File.expand_path('../lib/yard/version', __FILE__)
Gem::Specification.new do |s|
s.name = "yard"
s.summary = "Documentation tool for consistent and usable documentation in Ruby."
s.description = <<-eof
YARD is a documentation generation tool for the Ruby programming language.
It enables the user to generate consistent, usable documentation that can be
exported to a number of formats very easily, and also supports extending for
custom Ruby constructs such as custom class level definitions.
eof
s.version = YARD::VERSION
s.date = Time.now.strftime('%Y-%m-%d')
s.author = "Loren Segal"
s.email = "lsegal@soen.ca"
s.homepage = "http://yardoc.org"
s.platform = Gem::Platform::RUBY
s.files = Dir.glob("{docs,bin,lib,spec,templates,benchmarks}/**/*") +
['CHANGELOG.md', 'LICENSE', 'LEGAL', 'README.md', 'Rakefile', '.yardopts', __FILE__]
s.require_paths = ['lib']
s.executables = ['yard', 'yardoc', 'yri']
s.has_rdoc = 'yard'
s.license = 'MIT' if s.respond_to?(:license=)
end
|
Fix missing params to contribution observer on project notification | class ContributionObserver < ActiveRecord::Observer
observe :contribution
def after_create(contribution)
contribution.define_key
generate_matches(contribution)
end
def before_save(contribution)
notify_confirmation(contribution) if contribution.confirmed? && contribution.confirmed_at.nil?
end
def after_save(contribution)
if contribution.project.reached_goal?
contribution.project.notify_owner(:project_success)
end
end
def from_confirmed_to_canceled(resource)
notification_for_backoffice(resource, :contribution_canceled_after_confirmed)
end
def from_confirmed_to_requested_refund(resource)
notification_for_backoffice(resource, :refund_request)
end
private
def notify_confirmation(contribution)
contribution.update(confirmed_at: Time.now)
contribution.notify_owner(:confirm_contribution,
{ },
{ bcc: Configuration[:email_payments] })
if contribution.project.expires_at < 7.days.ago
notification_for_backoffice(contribution, :contribution_confirmed_after_project_was_closed)
end
end
def generate_matches(contribution)
unless contribution.payment_method.eql?(:matched)
MatchedContributionGenerator.new(contribution).create
end
end
def notification_for_backoffice(resource, template_name, options = {})
user = User.find_by(email: Configuration[:email_payments])
if user
Notification.notify_once(template_name,
user,
{ contribution_id: resource.id },
{ contribution: resource }.merge(options)
)
end
end
end
| class ContributionObserver < ActiveRecord::Observer
observe :contribution
def after_create(contribution)
contribution.define_key
generate_matches(contribution)
end
def before_save(contribution)
notify_confirmation(contribution) if contribution.confirmed? && contribution.confirmed_at.nil?
end
def after_save(contribution)
if contribution.project.reached_goal?
contribution.project.notify_owner(:project_success)
end
end
def from_confirmed_to_canceled(resource)
notification_for_backoffice(resource, :contribution_canceled_after_confirmed)
end
def from_confirmed_to_requested_refund(resource)
notification_for_backoffice(resource, :refund_request)
end
private
def notify_confirmation(contribution)
contribution.update(confirmed_at: Time.now)
contribution.notify_owner(:confirm_contribution,
{ },
{ project: contribution.project,
bcc: Configuration[:email_payments] })
if contribution.project.expires_at < 7.days.ago
notification_for_backoffice(contribution, :contribution_confirmed_after_project_was_closed)
end
end
def generate_matches(contribution)
unless contribution.payment_method.eql?(:matched)
MatchedContributionGenerator.new(contribution).create
end
end
def notification_for_backoffice(resource, template_name, options = {})
user = User.find_by(email: Configuration[:email_payments])
if user
Notification.notify_once(template_name,
user,
{ contribution_id: resource.id },
{ contribution: resource }.merge(options)
)
end
end
end
|
Implement fact value-quoting for error message | module Puppet::Parser::Functions
newfunction(:fail_unconfigured, :doc => "Fail with a canned 'not_configured' message."
) do |args|
if args.length == 0
args = ['operatingsystem', 'operatingsystemrelease', 'osfamily' ]
end
args = ['node'] + args
argpairs = [ "error=not_configured" ]
argpairs << "module=#{self.source.module_name}" if self.source.module_name
argpairs << "class=#{self.source.name}" if self.source.name
args.each do |arg|
val = lookupvar(arg) || :undefined
next if val == :undefined
val.downcase!
argpairs.push("#{arg}=#{val}")
end
raise Puppet::ParseError, argpairs.join(" ")
end
end
| module Puppet::Parser::Functions
newfunction(:fail_unconfigured, :doc => "Fail with a canned 'not_configured' message."
) do |args|
if args.length == 0
args = ['operatingsystem', 'operatingsystemrelease', 'osfamily' ]
end
args = ['node'] + args
argpairs = [ "error=not_configured" ]
argpairs << "module=#{self.source.module_name}" if self.source.module_name
argpairs << "class=#{self.source.name}" if self.source.name
args.each do |arg|
val = lookupvar(arg) || :undefined
next if val == :undefined
val.downcase!
val = %Q{"#{val}"} if val =~ /[^\w\.]/
argpairs.push("#{arg}=#{val}")
end
raise Puppet::ParseError, argpairs.join(" ")
end
end
|
Fix fog installation on rhel/variants | #
# Cookbook Name:: route53
# Recipe:: default
#
# Copyright 2010, Platform14.com.
#
# 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.
#
# Force immediate install of these packages
case node[:platform]
when 'centos'
package("libxml2-devel" ){ action :nothing }.run_action(:install)
else
package("libxml2-dev" ){ action :nothing }.run_action(:install)
package("libxslt1-dev" ){ action :nothing }.run_action(:install)
gem_package("fog") do
ignore_failure true
version '~> 1.5.0'
action :nothing
end.run_action(:install)
gem_package("net-ssh-multi"){ action :nothing }.run_action(:install)
gem_package("ghost" ){ action :nothing }.run_action(:install)
end
# Source the fog gem, forcing Gem to recognize new version if any
require 'rubygems' unless defined?(Gem)
Gem.clear_paths
require 'fog'
| #
# Cookbook Name:: route53
# Recipe:: default
#
# Copyright 2010, Platform14.com.
#
# 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.
#
# Force immediate install of these packages
case node[:platform_family]
when 'rhel'
package("libxml2-devel" ){ action :nothing }.run_action(:install)
when 'debian'
package("libxml2-dev" ){ action :nothing }.run_action(:install)
package("libxslt1-dev" ){ action :nothing }.run_action(:install)
else
raise 'Unable to install route53 dependencies'
end
chef_gem("fog") do
ignore_failure true
version '~> 1.5.0'
action :nothing
end.run_action(:install)
chef_gem("net-ssh-multi"){ action :nothing }.run_action(:install)
chef_gem("ghost" ){ action :nothing }.run_action(:install)
# Source the fog gem, forcing Gem to recognize new version if any
require 'rubygems' unless defined?(Gem)
Gem.clear_paths
require 'fog'
|
Add ruby version restriction to gemspec | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'butts/version'
Gem::Specification.new do |spec|
spec.name = 'butts'
spec.version = Butts::VERSION
spec.authors = ['William Mathewson']
spec.email = ['wncmathewson@me.com']
spec.summary = 'A gem to interact with butts.so for CLI fart noises'
spec.homepage = 'https://github.com/neanias/butts'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split('\x0')
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler', '~> 1.7'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_runtime_dependency 'httparty', '~> 0.13'
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'butts/version'
Gem::Specification.new do |spec|
spec.name = 'butts'
spec.version = Butts::VERSION
spec.authors = ['William Mathewson']
spec.email = ['wncmathewson@me.com']
spec.summary = 'A gem to interact with butts.so for CLI fart noises'
spec.homepage = 'https://github.com/neanias/butts'
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.required_ruby_version = '>= 1.9'
spec.add_development_dependency 'bundler', '~> 1.7'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_runtime_dependency 'httparty', '~> 0.13'
end
|
Remove unnecessary call to clear_all_jobba_data! | require 'spec_helper'
require 'status_shared_examples'
describe Jobba do
it_behaves_like 'status'
it 'computes `all.count` efficiently' do
2.times { make_status(state: :unqueued) }
1.times { make_status(state: :succeeded) }
3.times { make_status(state: :started) }
expect(Jobba.redis).to receive(:scard).exactly(Jobba::State::ALL.count).times.and_call_original
expect(Jobba.all.count).to eq 6
end
it 'can cleanup old statuses' do
Jobba.clear_all_jobba_data!
current_time = Jobba::Time.now
tested_months = 0.upto(59).to_a
tested_months.each do |nn|
job = Jobba::Status.create!
job.send :set, recorded_at: current_time - nn*60*60*24*30 # 1 month
end
expect { Jobba.cleanup }.to change { Jobba.all.count }.from(60).to(12)
expect(Jobba.all.map(&:recorded_at).min).to be > current_time - 60*60*24*30*12 # 1 year
end
end
| require 'spec_helper'
require 'status_shared_examples'
describe Jobba do
it_behaves_like 'status'
it 'computes `all.count` efficiently' do
2.times { make_status(state: :unqueued) }
1.times { make_status(state: :succeeded) }
3.times { make_status(state: :started) }
expect(Jobba.redis).to receive(:scard).exactly(Jobba::State::ALL.count).times.and_call_original
expect(Jobba.all.count).to eq 6
end
it 'can cleanup old statuses' do
current_time = Jobba::Time.now
tested_months = 0.upto(59).to_a
tested_months.each do |nn|
job = Jobba::Status.create!
job.send :set, recorded_at: current_time - nn*60*60*24*30 # 1 month
end
expect { Jobba.cleanup }.to change { Jobba.all.count }.from(60).to(12)
expect(Jobba.all.map(&:recorded_at).min).to be > current_time - 60*60*24*30*12 # 1 year
end
end
|
Rename from NessusDB to Risu | # encoding: utf-8
require 'spec_helper'
module NessusDB
module Models
describe Report do
before(:all) do
@report = Report.make
@report.hosts.make(:start => "Fri May 13 17:52:18 2011")
printf "%s\n\n", @report.inspect
end
it "should have a scan_date of Fri May 13 17:52:18 -0500 2011" do
date = Report.scan_date
#Ruby 1.8.7 and 1.9.2 return different date formats
if date == "Fri May 13 17:52:18 -0500 2011"
date.should == "Fri May 13 17:52:18 -0500 2011"
elsif date == "2011-05-13 17:52:18 -0500"
date.should == "2011-05-13 17:52:18 -0500"
end
end
end
end
end
| # encoding: utf-8
require 'spec_helper'
module Risu
module Models
describe Report do
before(:all) do
@report = Report.make
@report.hosts.make(:start => "Fri May 13 17:52:18 2011")
printf "%s\n\n", @report.inspect
end
it "should have a scan_date of Fri May 13 17:52:18 -0500 2011" do
date = Report.scan_date
#Ruby 1.8.7 and 1.9.2 return different date formats
if date == "Fri May 13 17:52:18 -0500 2011"
date.should == "Fri May 13 17:52:18 -0500 2011"
elsif date == "2011-05-13 17:52:18 -0500"
date.should == "2011-05-13 17:52:18 -0500"
end
end
end
end
end
|
Remove hack that is no longer needed | # encoding: utf-8
if ENV['COVERAGE'] == 'true'
require 'simplecov'
require 'coveralls'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
SimpleCov.start do
command_name 'spec:unit'
add_filter 'config'
add_filter 'lib/rom/support'
add_filter 'spec'
end
end
class BasicObject
def self.freeze
# FIXME: remove this when axiom no longer freezes classes
end
end
require 'devtools/spec_helper'
require 'rom'
require 'rom/support/axiom/adapter/memory'
require 'bogus/rspec'
include ROM
include SpecHelper
include Morpher::NodeHelpers
TEST_ENV = Environment.setup(test: 'memory://test') do
schema do
base_relation :users do
repository :test
attribute :id, Integer
attribute :name, String
key :id
end
end
mapping do
relation(:users) do
model mock_model(:id, :name)
map :id, :name
end
end
end
| # encoding: utf-8
if ENV['COVERAGE'] == 'true'
require 'simplecov'
require 'coveralls'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
SimpleCov.start do
command_name 'spec:unit'
add_filter 'config'
add_filter 'lib/rom/support'
add_filter 'spec'
end
end
require 'devtools/spec_helper'
require 'rom'
require 'rom/support/axiom/adapter/memory'
require 'bogus/rspec'
include ROM
include SpecHelper
include Morpher::NodeHelpers
TEST_ENV = Environment.setup(test: 'memory://test') do
schema do
base_relation :users do
repository :test
attribute :id, Integer
attribute :name, String
key :id
end
end
mapping do
relation(:users) do
model mock_model(:id, :name)
map :id, :name
end
end
end
|
Update Fauxhai debian platform version | # Cookbook:: beef
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'chefspec'
require 'chefspec/berkshelf'
RSpec.configure do |config|
config.log_level = :error
config.platform = 'debian'
config.version = '9.4'
end
| # Cookbook:: beef
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'chefspec'
require 'chefspec/berkshelf'
RSpec.configure do |config|
config.log_level = :error
config.platform = 'debian'
config.version = '9.11'
end
|
Add spec to test the resource | #
# Copyright:: Copyright 2018, Chef Software, Inc.
# 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.
#
require "spec_helper"
describe Chef::Resource::KernelModule do
let(:resource) { Chef::Resource::KernelModule.new("foo") }
it "sets resource name as :kernel_module" do
expect(resource.resource_name).to eql(:kernel_module)
end
it "sets the default action as :install" do
expect(resource.action).to eql([:install])
end
it "sets the modname property as its name property" do
expect(resource.modname).to eql("foo")
end
it "supports :create and :flush actions" do
expect { resource.action :install }.not_to raise_error
expect { resource.action :uninstall }.not_to raise_error
expect { resource.action :blacklist }.not_to raise_error
expect { resource.action :load }.not_to raise_error
expect { resource.action :unload }.not_to raise_error
expect { resource.action :delete }.to raise_error(ArgumentError)
end
end
| |
Add uploads directory to symlinks for deploy | Capistrano::Configuration.instance.load do
set :user, 'www-data'
set :scm, :git
set :deploy_via, :remote_cache
set :use_sudo, false
set :default_stage, 'integration'
set(:rails_env) { fetch(:stage) }
set(:repository) { "git@github.com:vigetlabs/#{application}.git" }
set(:deploy_to) { "/var/www/#{application}/#{rails_env}" }
set(:branch) do
(fetch(:rails_env).to_s == 'integration') ? :master : fetch(:rails_env)
end
set :keep_releases, 5
after "deploy:update_code", "deploy:cleanup"
namespace :setup do
task :default do
deploy.setup
strategy.deploy!
deploy.configuration.create
deploy.configuration.symlink
bundle.install
end
end
task :offline do
maintenance.on
end
task :online do
maintenance.off
end
namespace :deploy do
desc "Deploys code to target environment and runs all migrations"
task :default do
set :migrate_target, :latest
update_code
migrate
create_symlink
restart
end
desc "Restart passenger with restart.txt"
task :restart, :roles => :app, :except => { :no_release => true } do
run "touch #{current_path}/tmp/restart.txt"
end
end
end
| Capistrano::Configuration.instance.load do
set :user, 'www-data'
set :scm, :git
set :deploy_via, :remote_cache
set :use_sudo, false
set :default_stage, 'integration'
# Add the default uploads directory for CarrierWave, etc to the list of
# directories that will get symlinked on setup and deploy
set :shared_children, %w(public/system log tmp/pids public/uploads)
set(:rails_env) { fetch(:stage) }
set(:repository) { "git@github.com:vigetlabs/#{application}.git" }
set(:deploy_to) { "/var/www/#{application}/#{rails_env}" }
set(:branch) do
(fetch(:rails_env).to_s == 'integration') ? :master : fetch(:rails_env)
end
set :keep_releases, 5
after "deploy:update_code", "deploy:cleanup"
namespace :setup do
task :default do
deploy.setup
strategy.deploy!
deploy.configuration.create
deploy.configuration.symlink
bundle.install
end
end
task :offline do
maintenance.on
end
task :online do
maintenance.off
end
namespace :deploy do
desc "Deploys code to target environment and runs all migrations"
task :default do
set :migrate_target, :latest
update_code
migrate
create_symlink
restart
end
desc "Restart passenger with restart.txt"
task :restart, :roles => :app, :except => { :no_release => true } do
run "touch #{current_path}/tmp/restart.txt"
end
end
end
|
Set a default value for the UserClass | require "invitational/engine"
module Invitational
mattr_accessor :user_class
end
| require "invitational/engine"
module Invitational
mattr_accessor :user_class
@@user_class = "User"
end
|
Add get /new and post /create route handlers | require 'sinatra'
require 'slim'
require 'data_mapper'
require 'dm-postgres-adapter'
require 'pathname'
configure :development do
require 'dm-sqlite-adapter'
end
configure do
set :slim, pretty: true
APP_ROOT = Pathname.new(__FILE__).expand_path.dirname
DataMapper.setup(:default,
ENV['DATABASE_URL'] || "sqlite://#{APP_ROOT}/db/tdrb.db")
end
class Task
include DataMapper::Resource
property :id, Serial
property :body, Text, required: true
property :done, Boolean, default: false
end
configure :development do
DataMapper.auto_migrate!
end
get '/' do
slim :index
end
__END__
@@ layout
doctype 5
html
head
meta charset='utf-8'
title = @title
body
== yield
@@ index
p Hello.
| require 'sinatra'
require 'slim'
require 'data_mapper'
require 'dm-postgres-adapter'
require 'pathname'
configure :development do
require 'dm-sqlite-adapter'
end
configure do
set :slim, pretty: true
APP_ROOT = Pathname.new(__FILE__).expand_path.dirname
DataMapper.setup(:default,
ENV['DATABASE_URL'] || "sqlite://#{APP_ROOT}/db/tdrb.db")
end
class Task
include DataMapper::Resource
property :id, Serial
property :body, Text, required: true
property :done, Boolean, default: false
end
configure :development do
DataMapper.auto_migrate!
end
get '/' do
slim :index
end
get '/new' do
slim :new
end
post '/create' do
end
__END__
@@ layout
doctype 5
html
head
meta charset='utf-8'
title = @title
body
== yield
@@ index
p Hello.
|
Tag support warrants a version bump. | Gem::Specification.new do |s|
s.name = 'trello2kanboard'
s.version = '0.1.0'
s.licenses = ['MIT']
s.summary = "Converts CSV files exported from Trello into a format that can be imported to Kanboard"
s.description = "Export a CSV file from Trello, save it locally, create a config file that maps users and columns and run this script. The output should be a CSV file that can be imported into Kanboard."
s.authors = ["Ramón Cahenzli"]
s.email = 'rca@psy-q.ch'
s.files = Dir["{lib}/**/*.rb", "bin/*", "LICENSE", "*.md"]
s.executables = ['trello2kanboard']
s.require_path = 'lib'
s.homepage = 'https://github.com/psy-q/trello2kanboard'
s.add_dependency('ruby-trello', ["~> 2.0"])
s.add_dependency('table_print', ["~> 1.5"])
#s.add_dependency('jsonrpc-client', ["~> 0.1"])
s.add_dependency('faraday', ["~> 0.12"])
#s.add_dependency('saorin', ["~> 0.6"])
# s.add_dependency('jimson', ["~> 0.11"]) # pulls in rest-client < 2.0 which doesn't work on Ruby 2.4
end
| Gem::Specification.new do |s|
s.name = 'trello2kanboard'
s.version = '0.2.0'
s.licenses = ['MIT']
s.summary = "Converts CSV files exported from Trello into a format that can be imported to Kanboard"
s.description = "Export a CSV file from Trello, save it locally, create a config file that maps users and columns and run this script. The output should be a CSV file that can be imported into Kanboard."
s.authors = ["Ramón Cahenzli"]
s.email = 'rca@psy-q.ch'
s.files = Dir["{lib}/**/*.rb", "bin/*", "LICENSE", "*.md"]
s.executables = ['trello2kanboard']
s.require_path = 'lib'
s.homepage = 'https://github.com/psy-q/trello2kanboard'
s.add_dependency('ruby-trello', ["~> 2.0"])
s.add_dependency('table_print', ["~> 1.5"])
#s.add_dependency('jsonrpc-client', ["~> 0.1"])
s.add_dependency('faraday', ["~> 0.12"])
#s.add_dependency('saorin', ["~> 0.6"])
# s.add_dependency('jimson', ["~> 0.11"]) # pulls in rest-client < 2.0 which doesn't work on Ruby 2.4
end
|
Fix for changing file name | require 'minitest/unit'
require '../lib/Life.rb'
require '../lib/Nature.rb'
require '../Settings.rb'
MiniTest::Unit.autorun
DEAD = 0
ALIVE = 1
class TestNature < MiniTest::Unit::TestCase
def setup
@num = 10
@nature = Nature.new @num
end
def test_size
assert_equal(@num, @nature.size)
assert_equal(@num, @nature.length)
end
def test_state
assert_equal(false, @nature.state.include?('*'))
end
def test_first_born
@nature.set_first_alives(2,2)
assert_equal(true, @nature.state.include?('*'))
end
def test_step_generation
@nature.step_generation
assert_equal(false, @nature.state.include?('*'))
end
end
| require 'minitest/unit'
require '../lib/Life.rb'
require '../lib/Nature.rb'
require '../Settings.rb'
MiniTest::Unit.autorun
DEAD = 0
ALIVE = 1
class NatureTest < MiniTest::Unit::TestCase
def setup
@num = 10
@nature = Nature.new @num
end
def test_size
assert_equal(@num, @nature.size)
assert_equal(@num, @nature.length)
end
def test_state
assert_equal(false, @nature.state.include?('*'))
end
def test_first_born
@nature.set_first_alives(2,2)
assert_equal(true, @nature.state.include?('*'))
end
def test_step_generation
@nature.step_generation
assert_equal(false, @nature.state.include?('*'))
end
end
|
Fix line numbers for SCSS linter | module StyleGuide
class Scss < Base
DEFAULT_CONFIG_FILENAME = "scss.yml"
def violations_in_file(file)
require "scss_lint"
if config.excluded_file?(file.filename)
[]
else
runner.run([file.content])
runner.lints.map do |violation|
line = file.line_at(violation.location)
Violation.new(
filename: file.filename,
line: line,
line_number: violation.location,
messages: [violation.description],
patch_position: line.patch_position,
)
end
end
end
private
def runner
@runner ||= SCSSLint::Runner.new(config)
end
def config
SCSSLint::Config.new(custom_options || default_options)
end
def custom_options
if options = repo_config.for(name)
merge(default_options, options)
end
end
def merge(a, b)
SCSSLint::Config.send(:smart_merge, a, b)
end
def default_options
@default_options ||= SCSSLint::Config.send(
:load_options_hash_from_file,
default_config_file
)
end
def default_config_file
DefaultConfigFile.new(DEFAULT_CONFIG_FILENAME, repository_owner).path
end
end
end
| module StyleGuide
class Scss < Base
DEFAULT_CONFIG_FILENAME = "scss.yml"
def violations_in_file(file)
require "scss_lint"
if config.excluded_file?(file.filename)
[]
else
runner.run([file.content])
runner.lints.map do |violation|
line = file.line_at(violation.location.line)
Violation.new(
filename: file.filename,
line: line,
line_number: violation.location.line,
messages: [violation.description],
patch_position: line.patch_position,
)
end
end
end
private
def runner
@runner ||= SCSSLint::Runner.new(config)
end
def config
SCSSLint::Config.new(custom_options || default_options)
end
def custom_options
if options = repo_config.for(name)
merge(default_options, options)
end
end
def merge(a, b)
SCSSLint::Config.send(:smart_merge, a, b)
end
def default_options
@default_options ||= SCSSLint::Config.send(
:load_options_hash_from_file,
default_config_file
)
end
def default_config_file
DefaultConfigFile.new(DEFAULT_CONFIG_FILENAME, repository_owner).path
end
end
end
|
Remove call to File's private respond_to_missing? method | module ZendeskAppsSupport
class AppFile
attr_reader :relative_path
attr_reader :absolute_path
def initialize(package, relative_path)
@relative_path = relative_path
@file = File.new(package.root.join(relative_path))
@absolute_path = File.absolute_path @file.path
end
def read
File.read @file.path
end
def =~(regex)
@relative_path =~ regex
end
alias_method :to_s, :relative_path
def method_missing(sym, *args, &block)
if @file.respond_to?(sym)
@file.call(sym, *args, &block)
else
super
end
end
# Unless Ruby 1.9
def respond_to?(sym, include_private = false)
@file.respond_to?(sym, include_private) || super
end
# If Ruby 1.9
def respond_to_missing?(sym, include_private = false)
@file.respond_to_missing?(sym, include_private) || super
end
end
end
| module ZendeskAppsSupport
class AppFile
attr_reader :relative_path
attr_reader :absolute_path
def initialize(package, relative_path)
@relative_path = relative_path
@file = File.new(package.root.join(relative_path))
@absolute_path = File.absolute_path @file.path
end
def read
File.read @file.path
end
def =~(regex)
@relative_path =~ regex
end
alias_method :to_s, :relative_path
def method_missing(sym, *args, &block)
if @file.respond_to?(sym)
@file.call(sym, *args, &block)
else
super
end
end
# Unless Ruby 1.9
def respond_to?(sym, include_private = false)
@file.respond_to?(sym, include_private) || super
end
# If Ruby 1.9
def respond_to_missing?(sym, include_private = false)
@file.send(:respond_to_missing?, sym, include_private) || super
end
end
end
|
Add 'shell' trigger to Build JSONs | require 'inch_ci/worker/build_json/task'
module InchCI
module Worker
module BuildJSON
def self.json(filename)
JSONDump.new(filename)
end
class JSONDump
attr_reader :language, :branch_name, :revision, :nwo, :url
def initialize(filename)
contents = File.read(filename, :encoding => 'utf-8')
@json = JSON[contents]
@language = @json['language']
@branch_name = @json['branch_name'] || @json['travis_branch']
@revision = @json['revision'] || @json['travis_commit']
@nwo = @json['nwo'] || @json['travis_repo_slug']
@url = @json['git_repo_url']
end
def circleci?
!@json['circleci'].nil?
end
def travis?
!@json['travis'].nil?
end
def to_h(include_objects: true)
h = @json.dup
h.delete('objects') unless include_objects
h
end
end
end
end
end
| require 'inch_ci/worker/build_json/task'
module InchCI
module Worker
module BuildJSON
def self.json(filename)
JSONDump.new(filename)
end
class JSONDump
attr_reader :language, :branch_name, :revision, :nwo, :url
def initialize(filename)
contents = File.read(filename, :encoding => 'utf-8')
@json = JSON[contents]
@language = @json['language']
@branch_name = @json['branch_name'] || @json['travis_branch']
@revision = @json['revision'] || @json['travis_commit']
@nwo = @json['nwo'] || @json['travis_repo_slug']
@url = @json['git_repo_url']
end
def shell?
!@json['shell'].nil?
end
def circleci?
!@json['circleci'].nil?
end
def travis?
!@json['travis'].nil?
end
def to_h(include_objects: true)
h = @json.dup
h.delete('objects') unless include_objects
h
end
end
end
end
end
|
Add details to search by notification code | require_relative '../../boot'
# Find a Subscription by notification code
#
# You need to give AccountCredentials (EMAIL, TOKEN) and the notification code
#
# P.S: See the boot file example for more details.
credentials = PagSeguro::AccountCredentials.new('user@example.com', 'TOKEN')
subscription = PagSeguro::Subscription.find_by_notification_code('NOTIFICATION_CODE', credentials: credentials)
if subscription.errors.empty?
puts "Subscription:"
puts "\t#{subscription.inspect}"
else
puts "Errors:"
puts subscription.errors.join("\n")
end
| require_relative '../../boot'
# Find a Subscription by notification code
#
# You need to give AccountCredentials (EMAIL, TOKEN) and the notification code
#
# P.S: See the boot file example for more details.
email = 'user@example.com'
token = 'TOKEN'
code = 'NOTIFICATION_CODE'
credentials = PagSeguro::AccountCredentials.new(email, token)
subscription = PagSeguro::Subscription.find_by_notification_code(code, credentials: credentials)
if subscription.errors.empty?
puts "Subscription:"
puts " code: #{subscription.code}"
puts " name: #{subscription.name}"
puts " date: #{subscription.date}"
puts " tracker: #{subscription.tracker}"
puts " status: #{subscription.status}"
puts " reference: #{subscription.reference}"
puts " last event date: #{subscription.last_event_date}"
puts " charge: #{subscription.charge}"
if subscription.sender
puts " sender.name: #{subscription.sender.name}"
puts " sender.email: #{subscription.sender.email}"
if subscription.sender.phone
puts " sender.phone.area_code: #{subscription.sender.phone.area_code}"
puts " sender.phone.number: #{subscription.sender.phone.number}"
end
if subscription.sender.address
puts " sender.address.street: #{subscription.sender.address.street}"
puts " sender.address.number: #{subscription.sender.address.number}"
puts " sender.address.complement: #{subscription.sender.address.complement}"
puts " sender.address.district: #{subscription.sender.address.district}"
puts " sender.address.city: #{subscription.sender.address.city}"
puts " sender.address.state: #{subscription.sender.address.state}"
puts " sender.address.postal_code: #{subscription.sender.address.postal_code}"
puts " sender.address.country: #{subscription.sender.address.country}"
end
end
else
puts "Errors:"
puts subscription.errors.join("\n")
end
|
Use instance_exec instead of instance_eval | module ActiveRecord
module BelongsToIf
module PreloaderExtension
# @note Overriden to use :if condition.
def owners
super.select do |owner|
case if_condition
when Proc
owner.instance_eval(&if_condition)
when String, Symbol
owner.send(if_condition)
else
true
end
end
end
# @note Overridden to set loaded flag to all records.
def preload(*)
super.tap do
@owners.each do |owner|
owner.association(reflection.name).loaded!
end
end
end
private
# @return [Proc, String, Symbol, nil] The value :if option passed to belongs_to.
def if_condition
reflection.options[:if]
end
end
end
end
| module ActiveRecord
module BelongsToIf
module PreloaderExtension
# @note Overriden to use :if condition.
def owners
super.select do |owner|
case if_condition
when Proc
owner.instance_exec(&if_condition)
when String, Symbol
owner.send(if_condition)
else
true
end
end
end
# @note Overridden to set loaded flag to all records.
def preload(*)
super.tap do
@owners.each do |owner|
owner.association(reflection.name).loaded!
end
end
end
private
# @return [Proc, String, Symbol, nil] The value :if option passed to belongs_to.
def if_condition
reflection.options[:if]
end
end
end
end
|
Set timeout for newer ruby versions | class NameResolver < Scout::Plugin
needs 'resolv'
OPTIONS=<<-EOS
nameserver:
default: 8.8.8.8
resolve_address:
default: google.com
EOS
def build_report
resolver = Resolv::DNS.new(:nameserver => [option(:nameserver)])
begin
resolver.getaddress(option(:resolve_address))
rescue Resolv::ResolvError, Resolv::ResolvTimeout => err
report(:resolved? => 0, :result => err)
else
report(:resolved? => 1)
end
end
end
| class NameResolver < Scout::Plugin
needs 'resolv'
OPTIONS=<<-EOS
nameserver:
default: 8.8.8.8
resolve_address:
default: google.com
timeout:
default: 30
EOS
# Doesn't work :(
TIMEOUT=77
def build_report
resolver = Resolv::DNS.new(:nameserver => [option(:nameserver)])
# Only Ruby >= 2.0.0 supports setting a timeout.
# Without this DNS timeouts will raise a PluginTimeoutError
if resolver.respond_to? :timeouts=
resolver.timeouts = option(:timeout)
end
begin
resolver.getaddress(option(:resolve_address))
rescue Resolv::ResolvError, Resolv::ResolvTimeout => err
report(:resolved? => 0, :result => err)
else
report(:resolved? => 1)
end
end
end
|
Add FPM::Cookery::Package::Dir class that delegates to fpm's Dir class. | require 'fpm/package/dir'
require 'delegate'
module FPM
module Cookery
module Package
class Dir < SimpleDelegator
def initialize(recipe)
super(FPM::Package::Dir.new)
self.name = recipe.name
self.url = recipe.homepage || recipe.source
self.category = recipe.section || 'optional'
self.description = recipe.description.strip if recipe.description
self.architecture = recipe.arch.to_s if recipe.arch
self.dependencies += recipe.depends
self.conflicts += recipe.conflicts
self.provides += recipe.provides
self.replaces += recipe.replaces
self.config_files += recipe.config_files
attributes[:prefix] = '/'
attributes[:chdir] = recipe.destdir.to_s
attributes[:deb_compression] = 'gzip'
attributes[:rpm_compression] = 'gzip'
attributes[:rpm_digest] = 'md5'
attributes[:rpm_user] = 'root'
attributes[:rpm_group] = 'root'
# TODO replace remove_excluded_files() in packager with this.
attributes[:excludes] = []
input('.')
end
end
end
end
end
| |
Add initial waterings route tests | require 'rails_helper'
describe WateringsController do
it 'routes GET /plants/1/waterings/new' do
expect(get: '/plants/1/waterings/new').to route_to('waterings#new', plant_id: "1")
end
it 'routes POST /plants/1/waterings/' do
expect(post: '/plants/1/waterings').to route_to('waterings#create', plant_id: "1")
end
it 'does not route GET /plants/1/waterings/1' do
expect(get: '/plants/1/waterings/1').not_to route_to('waterings#show', plant_id: "1", id: "1")
end
end
| |
Use correct existence method for Pathname objects | # This script is run by ApplianceConsole::DatabaseConfiguration when joining a region.
$log.info("MIQ(#{$0}) Joining region...")
config = Rails.configuration.database_configuration[Rails.env]
raise "Failed to retrieve database configuration for Rails.env [#{Rails.env}]" if config.nil?
$log.info("MIQ(#{$0}) Establishing connection with #{config.except("password").inspect}")
class RemoteDatabase < ApplicationRecord
end
RemoteDatabase.establish_connection(config)
new_region = RemoteDatabase.region_number_from_sequence.to_i
region_file = Rails.root.join("REGION")
old_region = region_file.exists? ? region_file.read.to_i : 0
if new_region != old_region
$log.info("MIQ(#{$0}) Changing REGION file from [#{old_region}] to [#{new_region}]. Restart to use the new region.")
region_file.write(new_region)
end
$log.info("MIQ(#{$0}) Joining region...Complete")
| # This script is run by ApplianceConsole::DatabaseConfiguration when joining a region.
$log.info("MIQ(#{$0}) Joining region...")
config = Rails.configuration.database_configuration[Rails.env]
raise "Failed to retrieve database configuration for Rails.env [#{Rails.env}]" if config.nil?
$log.info("MIQ(#{$0}) Establishing connection with #{config.except("password").inspect}")
class RemoteDatabase < ApplicationRecord
end
RemoteDatabase.establish_connection(config)
new_region = RemoteDatabase.region_number_from_sequence.to_i
region_file = Rails.root.join("REGION")
old_region = region_file.exist? ? region_file.read.to_i : 0
if new_region != old_region
$log.info("MIQ(#{$0}) Changing REGION file from [#{old_region}] to [#{new_region}]. Restart to use the new region.")
region_file.write(new_region)
end
$log.info("MIQ(#{$0}) Joining region...Complete")
|
Add parent link to email alert signup presenter | class EmailAlertSignupContentItemPresenter
def initialize(policy, update_type="major")
@policy = policy
@update_type = update_type
end
def exportable_attributes
{
format: "email_alert_signup",
content_id: policy.email_alert_signup_content_id,
title: policy.name,
description: "",
public_updated_at: public_updated_at,
locale: "en",
update_type: update_type,
publishing_app: "policy-publisher",
rendering_app: "email-alert-frontend",
routes: routes,
details: details,
links: {},
}
end
def base_path
"#{policy.base_path}/email-signup"
end
private
attr_reader :policy, :update_type
def public_updated_at
policy.updated_at
end
def routes
[
{
path: base_path,
type: "exact",
},
]
end
def details
{
breadcrumbs: breadcrumbs,
summary: summary,
tags: {
policy: [policy.slug],
},
govdelivery_title: "#{policy.name} policy",
}
end
def summary
%q[
You'll get an email each time a document about
this policy is published or updated.
]
end
def breadcrumbs
[
{
title: policy.name,
link: policy.base_path,
}
]
end
end
| class EmailAlertSignupContentItemPresenter
def initialize(policy, update_type="major")
@policy = policy
@update_type = update_type
end
def exportable_attributes
{
format: "email_alert_signup",
content_id: policy.email_alert_signup_content_id,
title: policy.name,
description: "",
public_updated_at: public_updated_at,
locale: "en",
update_type: update_type,
publishing_app: "policy-publisher",
rendering_app: "email-alert-frontend",
routes: routes,
details: details,
links: { parent: [policy.content_id] },
}
end
def base_path
"#{policy.base_path}/email-signup"
end
private
attr_reader :policy, :update_type
def public_updated_at
policy.updated_at
end
def routes
[
{
path: base_path,
type: "exact",
},
]
end
def details
{
breadcrumbs: breadcrumbs,
summary: summary,
tags: {
policy: [policy.slug],
},
govdelivery_title: "#{policy.name} policy",
}
end
def summary
%q[
You'll get an email each time a document about
this policy is published or updated.
]
end
def breadcrumbs
[
{
title: policy.name,
link: policy.base_path,
}
]
end
end
|
Remove unnecessary requires from test helper | require "minitest/autorun"
require "minitest/pride"
require "shrine/storage/imgix"
require "forwardable"
require "stringio"
require "dotenv"
Dotenv.load!
class Minitest::Test
def image
File.open("test/fixtures/image.jpg")
end
end
| require "minitest/autorun"
require "minitest/pride"
require "shrine/storage/imgix"
require "dotenv"
Dotenv.load!
class Minitest::Test
def image
File.open("test/fixtures/image.jpg")
end
end
|
Update index route to redirect to users route if user is logged_in? | require './config/environment'
class ApplicationController < Sinatra::Base
configure do
set :public_folder, 'public'
set :views, 'app/views'
enable :sessions
set :session_secret, "secret_bookmark"
end
get '/' do
erb :index
end
helpers do
def logged_in?
!!session[:user_id]
end
def current_user
User.find_by_id(session[:user_id])
end
end
end
| require './config/environment'
class ApplicationController < Sinatra::Base
configure do
set :public_folder, 'public'
set :views, 'app/views'
enable :sessions
set :session_secret, "secret_bookmark"
end
get '/' do
if logged_in?
redirect '/users'
else
erb :index
end
end
helpers do
def logged_in?
!!session[:user_id]
end
def current_user
User.find_by_id(session[:user_id])
end
end
end
|
Use include? instad of has_key? for headers | class Sms::Adapters::TwilioAdapter < Sms::Adapters::Adapter
# checks if this adapter recognizes an incoming http receive request
def self.recognize_receive_request?(request)
request.headers.has_key?('X-Twilio-Signature')
end
def self.can_deliver?
true
end
def deliver(message)
raise NotImplementedError
end
def receive(params)
raise NotImplementedError
end
# Check_balance returns the balance string. Raises error if balance check failed.
def check_balance
raise NotImplementedError
end
# How replies should be sent.
def reply_style
:via_response
end
end
| class Sms::Adapters::TwilioAdapter < Sms::Adapters::Adapter
# checks if this adapter recognizes an incoming http receive request
def self.recognize_receive_request?(request)
request.headers.include?('X-Twilio-Signature')
end
def self.can_deliver?
true
end
def deliver(message)
raise NotImplementedError
end
def receive(params)
raise NotImplementedError
end
# Check_balance returns the balance string. Raises error if balance check failed.
def check_balance
raise NotImplementedError
end
# How replies should be sent.
def reply_style
:via_response
end
end
|
Allow updating admin user without changing his password | ActiveAdmin.register AdminUser do
permit_params :email, :password, :password_confirmation, :role
config.action_items[0] = ActiveAdmin::ActionItem.new only: :index do
link_to 'Add new Admin User', new_admin_admin_user_path if current_admin_user.superuser?
end
controller do
before_action :check_admin_role, only: [:new]
def check_admin_role
!current_admin_user.superuser? &&
redirect_to(admin_admin_users_path)
end
end
index download_links: false, new_link: false do
selectable_column
id_column
column :email
column :role
column :current_sign_in_at
column :sign_in_count
column :created_at
actions
end
filter :email
filter :role
filter :current_sign_in_at
filter :sign_in_count
filter :created_at
form do |f|
f.inputs do
f.input :email
f.input :role, as: :select, collection: %w(superuser admin),
selected: 'admin', include_blank: false
f.input :password
f.input :password_confirmation
end
f.actions
end
end
| ActiveAdmin.register AdminUser do
permit_params :email, :password, :password_confirmation, :role
config.action_items[0] = ActiveAdmin::ActionItem.new only: :index do
link_to 'Add new Admin User', new_admin_admin_user_path if current_admin_user.superuser?
end
controller do
before_action :check_admin_role, only: [:new]
def check_admin_role
!current_admin_user.superuser? &&
redirect_to(admin_admin_users_path)
end
def update_resource(object, attributes)
update_method =
if attributes.first[:password].present?
:update_attributes
else
:update_without_password
end
object.send(update_method, *attributes)
end
end
index download_links: false, new_link: false do
selectable_column
id_column
column :email
column :role
column :current_sign_in_at
column :sign_in_count
column :created_at
actions
end
filter :email
filter :role
filter :current_sign_in_at
filter :sign_in_count
filter :created_at
form do |f|
f.inputs do
f.input :email
f.input :role, as: :select, collection: %w(superuser admin),
selected: 'admin', include_blank: false
f.input :password
f.input :password_confirmation
end
f.actions
end
end
|
Remove require for the agent rb | require "snmpjr/version"
require "snmpjr/wrappers/agent"
require 'snmpjr/wrappers/smi'
require "snmpjr/getter"
require "snmpjr/walker"
require "snmpjr/target"
class Snmpjr
def initialize options = {}
@host = options.fetch(:host)
@port = options.fetch(:port) { 161 }
@community = options.fetch(:community)
@timeout = options.fetch(:timeout) { 5000 }
@retries = options.fetch(:retries) { 0 }
@target = Snmpjr::Target.new.create(host: @host,
port: @port,
community: @community,
timeout: @timeout,
retries: @retries
)
@max_oids_per_request = options.fetch(:max_oids_per_request) { 30 }
end
def get oids
getter = Snmpjr::Getter.new(target: @target, max_oids_per_request: @max_oids_per_request)
if oids.is_a?(String)
getter.get oids
elsif oids.is_a?(Array)
getter.get_multiple oids
else
raise ArgumentError.new 'You can request a single Oid using a String, or multiple using an Array'
end
end
def walk oid
if oid.is_a?(String)
Snmpjr::Walker.new(target: @target).walk Snmpjr::Wrappers::SMI::OID.new(oid)
else
raise ArgumentError.new 'The oid needs to be passed in as a String'
end
end
end
| require "snmpjr/version"
require 'snmpjr/wrappers/smi'
require "snmpjr/getter"
require "snmpjr/walker"
require "snmpjr/target"
class Snmpjr
def initialize options = {}
@host = options.fetch(:host)
@port = options.fetch(:port) { 161 }
@community = options.fetch(:community)
@timeout = options.fetch(:timeout) { 5000 }
@retries = options.fetch(:retries) { 0 }
@target = Snmpjr::Target.new.create(host: @host,
port: @port,
community: @community,
timeout: @timeout,
retries: @retries
)
@max_oids_per_request = options.fetch(:max_oids_per_request) { 30 }
end
def get oids
getter = Snmpjr::Getter.new(target: @target, max_oids_per_request: @max_oids_per_request)
if oids.is_a?(String)
getter.get oids
elsif oids.is_a?(Array)
getter.get_multiple oids
else
raise ArgumentError.new 'You can request a single Oid using a String, or multiple using an Array'
end
end
def walk oid
if oid.is_a?(String)
Snmpjr::Walker.new(target: @target).walk Snmpjr::Wrappers::SMI::OID.new(oid)
else
raise ArgumentError.new 'The oid needs to be passed in as a String'
end
end
end
|
Add working Cap prod DB copy task | namespace :db do
desc "Refreshes your local development environment to the current production database"
task :production_data_refresh do
db.database_dump
db.remote_db_download
db.production_data_load
db.remote_db_cleanup
end
desc "Dump the current database to a MySQL file"
task :database_dump, :roles => :db, :only => { :primary => true } do
load 'config/environment.rb'
abcs = ActiveRecord::Base.configurations
run("mysqldump -u #{abcs["production"]["username"]} -p#{abcs["production"]["password"]} --compress --ignore-table=#{abcs["production"]["database"]}.posts #{abcs["production"]["database"]} > db/production.sql")
end
desc 'Downloads db/production_data.sql from the remote production environment to your local machine'
task :remote_db_download, :roles => :db, :only => { :primary => true } do
get "db/production.sql", "db/production.sql"
end
desc "Loads the production data downloaded into db/production_data.sql into your local development database"
task :production_data_load, :roles => :db, :only => { :primary => true } do
load 'config/environment.rb'
abcs = ActiveRecord::Base.configurations
`mysql -u #{abcs[RAILS_ENV]["username"]} #{abcs[RAILS_ENV]["database"]} < db/production.sql`
exec("rm db/production.sql")
end
desc 'Cleans up data dump file'
task :remote_db_cleanup, :roles => :db, :only => { :primary => true } do
delete "db/production_data.sql"
end
end
| |
Add initial tests to sessions controller | require 'rails_helper'
describe SessionsController do
describe 'GET #new' do
it 'can render the login screen' do
get :new
expect(response).to render_template(:new)
end
it 'can redirect to user page if logged in' do
User.create(email: "test@test.com", password: "testPassword")
controller.session[:user_id] = User.first.id
end
end
end
| |
Truncate tables before test runs. | ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'json_expressions/rspec'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.infer_base_class_for_anonymous_controllers = false
config.filter_run focus: true
config.run_all_when_everything_filtered = true
config.treat_symbols_as_metadata_keys_with_true_values = true
config.include RSpec::Rails::RequestExampleGroup, type: :request,
example_group: { file_path: /spec\/api/ }
config.mock_with :mocha
config.include FactoryGirl::Syntax::Methods
config.around(:each) do |example|
Sequel::Model.db.transaction(rollback: :always){example.run}
end
end
| ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'json_expressions/rspec'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.infer_base_class_for_anonymous_controllers = false
config.filter_run focus: true
config.run_all_when_everything_filtered = true
config.treat_symbols_as_metadata_keys_with_true_values = true
config.include RSpec::Rails::RequestExampleGroup, type: :request,
example_group: { file_path: /spec\/api/ }
config.mock_with :mocha
config.include FactoryGirl::Syntax::Methods
config.before(:suite) do
Sequel::Model.db.tables.each{|table| Sequel::Model.db.from(table).truncate}
end
config.around(:each) do |example|
Sequel::Model.db.transaction(rollback: :always){example.run}
end
end
|
Return time in addition to response for logging and use localhost for testing | require 'net/http'
require 'json'
module Columbo
class APIClient
API_URI = "http://localhost:15080/hit".freeze
def initialize(api_key, api_uri)
@api_key = api_key
@api_uri = api_uri || API_URI
end
def post_data(hash)
zlib = Columbo::Compressor
headers = {
"Accept-Encoding" => "gzip, deflate",
"Content-Encoding" => "deflate",
"Content-Type" => "application/json; charset=utf-8"
}
json = hash.merge({api_key: @api_key}).to_json
payload = zlib.deflate(json)
uri = URI(@api_uri)
Net::HTTP.start(uri.host, uri.port) do |http|
response = http.post(@api_uri, payload, headers)
zlib.unzip(response.body, response['Content-Encoding'])
end
end
end
end
| require 'net/http'
require 'json'
module Columbo
class APIClient
API_URI = "http://localhost:15080/capture".freeze
#API_URI = "http://columbo.aws.af.cm/capture".freeze
def initialize(api_key, api_uri)
@api_key = api_key
@api_uri = api_uri || API_URI
end
def post_data(hash)
zlib = Columbo::Compressor
headers = {
"Accept-Encoding" => "gzip, deflate",
"Content-Encoding" => "deflate",
"Content-Type" => "application/json; charset=utf-8"
}
json = hash.merge({api_key: @api_key}).to_json
payload = zlib.deflate(json)
uri = URI(@api_uri)
start = Time.now
Net::HTTP.new(uri.host, uri.port).start do |http|
response = http.post(@api_uri, payload, headers)
stop = Time.now
duration = ((stop-start) * 1000).round(3)
zlib.unzip(response.body, response['Content-Encoding']) + ' - Time: ' + duration.to_s + 'ms'
end
end
end
end
|
Send accept header for completeness | require 'json'
module GdsApi::JsonUtils
def get_json(url)
url = URI.parse(url)
response = Net::HTTP.start(url.host, url.port) do |http|
request = url.path
request = request + "?" + url.query if url.query
http.get(request)
end
if response.code.to_i != 200
return nil
else
return JSON.parse(response.body)
end
end
def post_json(url,params)
url = URI.parse(url)
Net::HTTP.start(url.host, url.port) do |http|
post_response = http.post(url.path, params.to_json, {'Content-Type' => 'application/json'})
if post_response.code == '200'
return JSON.parse(post_response.body)
end
end
return nil
end
def to_ostruct(object)
case object
when Hash
OpenStruct.new Hash[object.map { |key, value| [key, to_ostruct(value)] }]
when Array
object.map { |k| to_ostruct(k) }
else
object
end
end
end
| require 'json'
module GdsApi::JsonUtils
def get_json(url)
url = URI.parse(url)
request = url.path
request = request + "?" + url.query if url.query
response = Net::HTTP.start(url.host, url.port) do |http|
http.get(request, {'Accept' => 'application/json'})
end
if response.code.to_i != 200
return nil
else
return JSON.parse(response.body)
end
end
def post_json(url,params)
url = URI.parse(url)
Net::HTTP.start(url.host, url.port) do |http|
post_response = http.post(url.path, params.to_json, {'Content-Type' => 'application/json'})
if post_response.code == '200'
return JSON.parse(post_response.body)
end
end
return nil
end
def to_ostruct(object)
case object
when Hash
OpenStruct.new Hash[object.map { |key, value| [key, to_ostruct(value)] }]
when Array
object.map { |k| to_ostruct(k) }
else
object
end
end
end |
Make the trade-tariff slug live | require 'ostruct'
namespace :panopticon do
desc "Register application metadata with panopticon"
task :register => :environment do
require 'gds_api/panopticon'
logger = GdsApi::Base.logger = Logger.new(STDERR).tap { |l| l.level = Logger::INFO }
logger.info "Registering with panopticon..."
registerer = GdsApi::Panopticon::Registerer.new(owning_app: "tariff")
record = OpenStruct.new(
slug: APP_SLUG,
title: "UK Trade Tariff",
description: "Search for import and export commodity codes and for tax, duty and licenses that apply to your goods",
need_id: "B659",
section: "business/international-trade",
paths: [APP_SLUG],
prefixes: [APP_SLUG],
live: false,
indexable_content: "Search for import and export commodity codes and for tax, duty and licenses that apply to your goods")
registerer.register(record)
end
end
| require 'ostruct'
namespace :panopticon do
desc "Register application metadata with panopticon"
task :register => :environment do
require 'gds_api/panopticon'
logger = GdsApi::Base.logger = Logger.new(STDERR).tap { |l| l.level = Logger::INFO }
logger.info "Registering with panopticon..."
registerer = GdsApi::Panopticon::Registerer.new(owning_app: "tariff")
record = OpenStruct.new(
slug: APP_SLUG,
title: "UK Trade Tariff",
description: "Search for import and export commodity codes and for tax, duty and licenses that apply to your goods",
need_id: "B659",
section: "business/international-trade",
paths: [APP_SLUG],
prefixes: [APP_SLUG],
live: true,
indexable_content: "Search for import and export commodity codes and for tax, duty and licenses that apply to your goods")
registerer.register(record)
end
end
|
Update for newer version of CD API. | #!/usr/bin/env ruby
require 'json'
require 'net/http'
require 'uri'
if ARGV.length < 1
puts "Usage: #{$PROGRAM_NAME} [POD_NAME]"
exit 1
end
uri = URI.parse("https://cocoadocs-api-cocoapods-org.herokuapp.com/pods/#{ARGV[0]}/stats")
quality = Net::HTTP.get_response(uri).body
if quality[0] != '['
puts quality
exit 1
end
quality = JSON.parse(quality)
uri = URI.parse("http://metrics.cocoapods.org/api/v1/pods/#{ARGV[0]}.json")
metrics = JSON.parse(Net::HTTP.get_response(uri).body)
quality.each do |metric|
if (metric['modifier'] > 0 && !metric['applies_for_pod']) ||
(metric['modifier'] < 0 && metric['applies_for_pod'])
puts "🚫 #{metric['title']}: #{metric['description']}"
end
end
puts "\nCurrent quality estimate: #{metrics['cocoadocs']['quality_estimate']}"
| #!/usr/bin/env ruby
require 'json'
require 'net/http'
require 'uri'
if ARGV.length < 1
puts "Usage: #{$PROGRAM_NAME} [POD_NAME]"
exit 1
end
uri = URI.parse("https://cocoadocs-api-cocoapods-org.herokuapp.com/pods/#{ARGV[0]}/stats")
quality = Net::HTTP.get_response(uri).body
if quality[0] != '{'
puts quality
exit 1
end
quality = JSON.parse(quality)['metrics']
uri = URI.parse("http://metrics.cocoapods.org/api/v1/pods/#{ARGV[0]}.json")
metrics = JSON.parse(Net::HTTP.get_response(uri).body)
quality.each do |metric|
if (metric['modifier'] > 0 && !metric['applies_for_pod']) ||
(metric['modifier'] < 0 && metric['applies_for_pod'])
puts "🚫 #{metric['title']}: #{metric['description']}"
end
end
puts "\nCurrent quality estimate: #{metrics['cocoadocs']['quality_estimate']}"
|
Use the same heredoc as everywhere else | # coding: utf-8
lib = File.expand_path('lib', File.dirname(__FILE__))
$LOAD_PATH.push(lib) unless $LOAD_PATH.include?(lib)
require 'erudite/version'
Gem::Specification.new do |gem|
gem.name = 'erudite'
gem.version = Erudite::VERSION
gem.summary = 'Test interactive Ruby examples.'
gem.description = <<-TXT
Erudite helps you turn your documentation into tests. It is like a Ruby
version of the Python doctest module.
TXT
gem.homepage = 'http://taylor.fausak.me/erudite/'
gem.author = 'Taylor Fausak'
gem.email = 'taylor@fausak.me'
gem.license = 'MIT'
gem.executable = 'erudite'
gem.files = %w(.irbrc CHANGELOG.md LICENSE.md README.md) +
Dir.glob(File.join(gem.require_path, '**', '*.rb'))
gem.test_files = Dir.glob(File.join('spec', '**', '*.rb'))
gem.required_ruby_version = '>= 1.9.3'
gem.add_dependency 'parser', '~> 2.2'
gem.add_development_dependency 'coveralls', '~> 0.8'
gem.add_development_dependency 'rake', '~> 10.4'
gem.add_development_dependency 'rspec', '~> 3.2'
gem.add_development_dependency 'rubocop', '~> 0.30'
end
| # coding: utf-8
lib = File.expand_path('lib', File.dirname(__FILE__))
$LOAD_PATH.push(lib) unless $LOAD_PATH.include?(lib)
require 'erudite/version'
Gem::Specification.new do |gem|
gem.name = 'erudite'
gem.version = Erudite::VERSION
gem.summary = 'Test interactive Ruby examples.'
gem.description = <<-'TEXT'
Erudite helps you turn your documentation into tests. It is like a Ruby
version of the Python doctest module.
TEXT
gem.homepage = 'http://taylor.fausak.me/erudite/'
gem.author = 'Taylor Fausak'
gem.email = 'taylor@fausak.me'
gem.license = 'MIT'
gem.executable = 'erudite'
gem.files = %w(.irbrc CHANGELOG.md LICENSE.md README.md) +
Dir.glob(File.join(gem.require_path, '**', '*.rb'))
gem.test_files = Dir.glob(File.join('spec', '**', '*.rb'))
gem.required_ruby_version = '>= 1.9.3'
gem.add_dependency 'parser', '~> 2.2'
gem.add_development_dependency 'coveralls', '~> 0.8'
gem.add_development_dependency 'rake', '~> 10.4'
gem.add_development_dependency 'rspec', '~> 3.2'
gem.add_development_dependency 'rubocop', '~> 0.30'
end
|
Update rubocop requirement from ~> 0.77.0 to ~> 0.78.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.77.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.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
|
Remove railties 4.0 requirement to work with newer versions of rails | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'jsTimezoneDetect/rails/version'
Gem::Specification.new do |spec|
spec.name = "jsTimezoneDetect-rails"
spec.version = JsTimezoneDetect::Rails::VERSION
spec.authors = ["Alexander Popov"]
spec.homepage = "https://github.com/AlexVPopov/jsTimezoneDetect-rails"
spec.license = "MIT"
spec.summary = "The jsTimezoneDetect.js library ready for Rails' asset pipeline."
spec.description = <<-EOF
This script gives you the zone info key representing your device's time zone setting.
The return value is an IANA zone info key (aka the Olson time zone database).
This gem allows for its easy inclusion into the rails asset pipeline.
EOF
spec.files = Dir["{lib,vendor}/**/*"] + ["LICENSE.txt", "README.md"]
spec.require_paths = ["lib"]
spec.add_runtime_dependency 'railties', '~> 4.0', '>= 4.0.0'
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'jsTimezoneDetect/rails/version'
Gem::Specification.new do |spec|
spec.name = "jsTimezoneDetect-rails"
spec.version = JsTimezoneDetect::Rails::VERSION
spec.authors = ["Alexander Popov"]
spec.homepage = "https://github.com/AlexVPopov/jsTimezoneDetect-rails"
spec.license = "MIT"
spec.summary = "The jsTimezoneDetect.js library ready for Rails' asset pipeline."
spec.description = <<-EOF
This script gives you the zone info key representing your device's time zone setting.
The return value is an IANA zone info key (aka the Olson time zone database).
This gem allows for its easy inclusion into the rails asset pipeline.
EOF
spec.files = Dir["{lib,vendor}/**/*"] + ["LICENSE.txt", "README.md"]
spec.require_paths = ["lib"]
spec.add_runtime_dependency 'railties', '>= 4.0.0'
end
|
Fix preparing database schema when using :sql | #module LanguagePack::Test::Ruby
class LanguagePack::Ruby
def compile
instrument 'ruby.test.compile' do
new_app?
Dir.chdir(build_path)
remove_vendor_bundle
install_ruby
install_jvm
setup_language_pack_environment
setup_profiled
allow_git do
install_bundler_in_app
build_bundler("development")
post_bundler
create_database_yml
install_binaries
prepare_tests
end
super
end
end
private
def prepare_tests
schema_load = rake.task("db:schema:load")
db_migrate = rake.task("db:migrate")
return true unless (schema_load.is_defined? || db_migrate.is_defined?)
topic "Preparing test database schema"
[schema_load, db_migrate].each do |rake_task|
if rake_task.is_defined?
rake_task.invoke(env: rake_env)
if rake_task.success?
puts "#{rake_task.task} completed (#{"%.2f" % rake_task.time}s)"
else
error "Could not load test database schema"
end
end
end
end
end
| #module LanguagePack::Test::Ruby
class LanguagePack::Ruby
def compile
instrument 'ruby.test.compile' do
new_app?
Dir.chdir(build_path)
remove_vendor_bundle
install_ruby
install_jvm
setup_language_pack_environment
setup_profiled
allow_git do
install_bundler_in_app
build_bundler("development")
post_bundler
create_database_yml
install_binaries
prepare_tests
end
super
end
end
private
def prepare_tests
schema_load = rake.task("db:schema:load_if_ruby")
structure_load = rake.task("db:structure:load_if_sql")
db_migrate = rake.task("db:migrate")
if schema_load.not_defined? && structure_load.not_defined?
result = detect_schema_format
case result.lines.last.chomp
when "ruby"
schema_load = rake.task("db:schema:load")
when "sql"
structure_load = rake.task("db:structure:load")
else
puts "Could not determine schema/structure from ActiveRecord::Base.schema_format:\n#{result}"
end
end
rake_tasks = [schema_load, structure_load, db_migrate].select(&:is_defined?)
return true if rake_tasks.empty?
topic "Preparing test database"
rake_tasks.each do |rake_task|
rake_task.invoke(env: rake_env)
if rake_task.success?
puts "#{rake_task.task} completed (#{"%.2f" % rake_task.time}s)"
else
error "Could not prepare database for test"
end
end
end
def detect_schema_format
run("rails runner 'puts ActiveRecord::Base.schema_format'")
end
end
|
Improve issue body and title | require 'bundler'
require 'json'
Bundler.require
class Lib2Issue < Sinatra::Base
use Rack::Deflater
configure do
set :logging, true
set :dump_errors, false
set :raise_errors, true
set :show_exceptions, false
end
before do
request.body.rewind
@request_payload = JSON.parse request.body.read
end
post '/webhook' do
content_type :json
puts @request_payload.inspect
client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN'])
client.create_issue(@request_payload['repository'], "Version #{@request_payload['version']} of #{@request_payload['name']} has been released")
status 200
body ''
end
end
| require 'bundler'
require 'json'
Bundler.require
class Lib2Issue < Sinatra::Base
use Rack::Deflater
configure do
set :logging, true
set :dump_errors, false
set :raise_errors, true
set :show_exceptions, false
end
before do
request.body.rewind
@request_payload = JSON.parse request.body.read
end
post '/webhook' do
content_type :json
puts @request_payload.inspect
client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN'])
client.create_issue(@request_payload['repository'], "Upgrade #{@request_payload['name']} to version #{@request_payload['version']}",
"More info: https://libraries.io/#{@request_payload['platform'].downcase}/#{@request_payload['name']}/#{@request_payload['version']}",
labels: ENV['GITHUB_LABELS'])
status 200
body ''
end
end
|
Update podspec version to 1.0.0 | Pod::Spec.new do |s|
s.name = "LVGUtilities"
s.version = "0.3.1"
s.summary = "Basic Swift utility functions."
s.homepage = 'https://github.com/letvargo/LVGUtilities'
s.description = <<-DESC
A group of basic Swift utility functions for performing the following tasks:
- C-pointer bridging
DESC
s.license = 'MIT'
s.author = { "letvargo" => "letvargo@gmail.com" }
s.ios.deployment_target = "8.0"
s.osx.deployment_target = "10.10"
s.source = { :git => "https://github.com/letvargo/LVGUtilities.git", :tag => "0.3.1" }
s.source_files = "Source/**/*"
s.requires_arc = true
s.subspec 'CBridgingFunctions' do |sp|
sp.source_files = 'Source/CBridgingFunctions.swift'
end
s.subspec 'FourCharCodes' do |sp|
sp.source_files = 'Source/FourCharCodeUtilities.swift'
end
s.subspec 'CodedPropertyType' do |sp|
sp.source_files = 'Source/CodedPropertyType.swift'
sp.dependency 'LVGUtilities/FourCharCodes'
end
s.subspec 'CodedErrorType' do |sp|
sp.source_files = 'Source/CodedErrorType.swift'
sp.dependency 'LVGUtilities/FourCharCodes'
end
end | Pod::Spec.new do |s|
s.name = "LVGUtilities"
s.version = "1.0.0"
s.summary = "Basic Swift utility functions."
s.homepage = 'https://github.com/letvargo/LVGUtilities'
s.description = <<-DESC
A group of basic Swift utility functions for performing the following tasks:
- C-pointer bridging
DESC
s.license = 'MIT'
s.author = { "letvargo" => "letvargo@gmail.com" }
s.ios.deployment_target = "8.0"
s.osx.deployment_target = "10.10"
s.source = { :git => "https://github.com/letvargo/LVGUtilities.git", :tag => "1.0.0" }
s.source_files = "Source/**/*"
s.requires_arc = true
s.subspec 'CBridgingFunctions' do |sp|
sp.source_files = 'Source/CBridgingFunctions.swift'
end
s.subspec 'FourCharCodes' do |sp|
sp.source_files = 'Source/FourCharCodeUtilities.swift'
end
s.subspec 'CodedPropertyType' do |sp|
sp.source_files = 'Source/CodedPropertyType.swift'
sp.dependency 'LVGUtilities/FourCharCodes'
end
s.subspec 'CodedErrorType' do |sp|
sp.source_files = 'Source/CodedErrorType.swift'
sp.dependency 'LVGUtilities/FourCharCodes'
end
end |
Fix small typo in spec doc. | require "spec_helper"
describe Mongoid::Extensions::Symbol::Inflections do
describe "invert" do
context "when :asc" do
it "returns :desc" do
:asc.invert.should == :desc
end
end
context "when :ascending" do
it "returns :descending" do
:ascending.invert.should == :descending
end
end
context "when :desc" do
it "returns :asc" do
:desc.invert.should == :asc
end
end
context "when :descending" do
it "returns :ascending" do
:descending.invert.should == :ascending
end
end
end
describe "#gt" do
it 'returns :"foo $gt"' do
ret = :foo.gt
ret.key.should == :foo
ret.operator.should == "gt"
end
end
describe "#near" do
it 'returns :"foo $near"' do
ret = :foo.near
ret.key.should == :foo
ret.operator.should == "near"
end
end
describe "#not" do
it 'returns :"foo not"' do
ret = :foo.not
ret.key.should == :foo
ret.operator.should == "not"
end
end
describe "#within" do
it "returns :foo $within" do
ret = :foo.within
ret.key.should == :foo
ret.operator.should == "within"
end
end
end
| require "spec_helper"
describe Mongoid::Extensions::Symbol::Inflections do
describe "invert" do
context "when :asc" do
it "returns :desc" do
:asc.invert.should == :desc
end
end
context "when :ascending" do
it "returns :descending" do
:ascending.invert.should == :descending
end
end
context "when :desc" do
it "returns :asc" do
:desc.invert.should == :asc
end
end
context "when :descending" do
it "returns :ascending" do
:descending.invert.should == :ascending
end
end
end
describe "#gt" do
it 'returns :"foo $gt"' do
ret = :foo.gt
ret.key.should == :foo
ret.operator.should == "gt"
end
end
describe "#near" do
it 'returns :"foo $near"' do
ret = :foo.near
ret.key.should == :foo
ret.operator.should == "near"
end
end
describe "#not" do
it 'returns :"foo $not"' do
ret = :foo.not
ret.key.should == :foo
ret.operator.should == "not"
end
end
describe "#within" do
it "returns :foo $within" do
ret = :foo.within
ret.key.should == :foo
ret.operator.should == "within"
end
end
end
|
Order posts by created_at desc in admin for easily navigation | class HushCmsAdmin::PostsController < HushCmsAdminController
before_filter :find_category
before_filter :find_post, :except => [ :index, :new, :create ]
def index
end
def show
end
def new
@post = HushCMS::Post.new
end
def create
@post = @category.posts.build(params[:hush_cms_post])
if @post.save
redirect_to hush_cms_admin_category_post_url(@category, @post)
else
prepare_error_messages_for_javascript @post
render :action => 'new'
end
end
def edit
end
def update
if @post.update_attributes(params[:hush_cms_post])
redirect_to hush_cms_admin_category_post_url(@category, @post)
else
prepare_error_messages_for_javascript @post
render :action => 'edit'
end
end
def destroy
@post.destroy
redirect_to hush_cms_admin_category_posts_url(@category)
end
def publish
@post.publish!
redirect_to :back
end
def unpublish
@post.unpublish!
redirect_to :back
end
private
def find_category
@category = HushCMS::Category.find(params[:category_id])
@posts = @category.posts
end
def find_post
@post = @category.posts.find(params[:id])
end
end
| class HushCmsAdmin::PostsController < HushCmsAdminController
before_filter :find_category
before_filter :find_post, :except => [ :index, :new, :create ]
def index
end
def show
end
def new
@post = HushCMS::Post.new
end
def create
@post = @category.posts.build(params[:hush_cms_post])
if @post.save
redirect_to hush_cms_admin_category_post_url(@category, @post)
else
prepare_error_messages_for_javascript @post
render :action => 'new'
end
end
def edit
end
def update
if @post.update_attributes(params[:hush_cms_post])
redirect_to hush_cms_admin_category_post_url(@category, @post)
else
prepare_error_messages_for_javascript @post
render :action => 'edit'
end
end
def destroy
@post.destroy
redirect_to hush_cms_admin_category_posts_url(@category)
end
def publish
@post.publish!
redirect_to :back
end
def unpublish
@post.unpublish!
redirect_to :back
end
private
def find_category
@category = HushCMS::Category.find(params[:category_id])
@posts = @category.posts.all(:order => 'created_at DESC')
end
def find_post
@post = @category.posts.find(params[:id])
end
end
|
Enable one-sided relations for Groups | require 'embedded'
class Group
include Model::Core
field :type
@rdf_types = {:rdfs => [:Container]}
@headings = [{:rdfs => :label}]
# model relations
has_and_belongs_to_many :agents
has_and_belongs_to_many :concepts
has_and_belongs_to_many :resources
# track_history
define_scopes
end | require 'embedded'
class Group
include Model::Core
field :type
@rdf_types = {:rdfs => [:Container]}
@headings = [{:rdfs => :label}]
# model relations
# has_and_belongs_to_many :agents
# has_and_belongs_to_many :concepts
# has_and_belongs_to_many :resources
# track_history
define_scopes
end |
Use the latest version of minitest rather than the version that comes with ruby | # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'clever-ruby/version'
Gem::Specification.new do |gem|
gem.name = "clever-ruby"
gem.version = Clever::VERSION
gem.authors = ["Rafael Garcia", "Alex Zylman"]
gem.email = ["ruby@getclever.com"]
gem.description = %q{Ruby bindings to the Clever API.}
gem.summary = %q{Ruby bindings to the Clever API.}
gem.homepage = "http://github.com/Clever/clever-ruby"
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_runtime_dependency 'multi_json', '~> 1.5.0'
gem.add_runtime_dependency 'rest-client', '~> 1.6.7'
gem.add_development_dependency 'shoulda', '~> 3.3.2'
gem.add_development_dependency 'rdoc', '~> 3.12'
end
| # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'clever-ruby/version'
Gem::Specification.new do |gem|
gem.name = "clever-ruby"
gem.version = Clever::VERSION
gem.authors = ["Rafael Garcia", "Alex Zylman"]
gem.email = ["ruby@getclever.com"]
gem.description = %q{Ruby bindings to the Clever API.}
gem.summary = %q{Ruby bindings to the Clever API.}
gem.homepage = "http://github.com/Clever/clever-ruby"
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_runtime_dependency 'multi_json', '~> 1.5.0'
gem.add_runtime_dependency 'rest-client', '~> 1.6.7'
gem.add_development_dependency 'minitest', '~> 4.4.0'
gem.add_development_dependency 'shoulda', '~> 3.3.2'
gem.add_development_dependency 'rdoc', '~> 3.12'
end
|
Rename instance var everything to makeables | module Bane
class ServiceMaker
def initialize
@everything = {}
Bane::Behaviors::EXPORTED.each { |behavior| @everything[behavior.unqualified_name] = BehaviorMaker.new(behavior) }
Bane::Services::EXPORTED.each { |service| @everything[service.unqualified_name] = service }
end
def all_service_names
@everything.keys.sort
end
def create(service_names, starting_port, host)
service_names
.map { |service_name| @everything.fetch(service_name) { raise UnknownServiceError.new(service_name) } }
.map.with_index { |maker, index| maker.make(starting_port + index, host) }
end
def create_all(starting_port, host)
create(all_service_names, starting_port, host)
end
end
class UnknownServiceError < RuntimeError
def initialize(name)
super "Unknown service: #{name}"
end
end
class BehaviorMaker
def initialize(behavior)
@behavior = behavior
end
def make(port, host)
Services::BehaviorServer.new(port, @behavior.new, host)
end
end
end | module Bane
class ServiceMaker
def initialize
initialize_makeables
end
def all_service_names
makeables.keys.sort
end
def create(service_names, starting_port, host)
service_names
.map { |service_name| makeables.fetch(service_name) { raise UnknownServiceError.new(service_name) } }
.map.with_index { |maker, index| maker.make(starting_port + index, host) }
end
def create_all(starting_port, host)
create(all_service_names, starting_port, host)
end
private
attr_reader :makeables
def initialize_makeables
@makeables = {}
Bane::Behaviors::EXPORTED.each { |behavior| @makeables[behavior.unqualified_name] = BehaviorMaker.new(behavior) }
Bane::Services::EXPORTED.each { |service| @makeables[service.unqualified_name] = service }
end
end
class UnknownServiceError < RuntimeError
def initialize(name)
super "Unknown service: #{name}"
end
end
class BehaviorMaker
def initialize(behavior)
@behavior = behavior
end
def make(port, host)
Services::BehaviorServer.new(port, @behavior.new, host)
end
end
end |
Add more cases in model specs | require 'rails_helper'
RSpec.describe Task, type: :model do
fixtures :tasks
describe '.weekly' do
let(:weekly_task) { tasks(:weekly) }
it 'includes weekly tasks' do
expect(Task.weekly).to include(weekly_task)
end
end
describe '.monthly' do
let(:monthly_task) { tasks(:monthly) }
it 'includes monthly tasks' do
expect(Task.monthly).to include(monthly_task)
end
end
end
| require 'rails_helper'
RSpec.describe Task, type: :model do
fixtures :tasks
let(:weekly_task) { tasks(:weekly) }
let(:monthly_task) { tasks(:monthly) }
describe '.weekly' do
it 'includes weekly tasks' do
expect(Task.weekly).to include(weekly_task)
end
it 'does not include monthly tasks' do
expect(Task.weekly).not_to include(monthly_task)
end
end
describe '.monthly' do
it 'includes monthly tasks' do
expect(Task.monthly).to include(monthly_task)
end
it 'does not include weekly tasks' do
expect(Task.monthly).not_to include(weekly_task)
end
end
end
|
Fix version-loading code in gemspec | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "cleaver"
spec.version = IO.read(File.expand_path('VERSION', __FILE__)) rescue "0.0.1"
spec.authors = ["John Manero"]
spec.email = ["jmanero@dyn.com"]
spec.description = %q{Manage the lifecycle of a deployment with Chef}
spec.summary = %q{Manage the lifecycle of a deployment with Chef}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "thor-scmversion"
spec.add_dependency "berkshelf", "= 2.0.12"
spec.add_dependency "colorize"
spec.add_dependency "growl"
spec.add_dependency "ridley", "= 1.5.3"
spec.add_dependency "thor-scmversion", "= 1.4.0"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "cleaver"
spec.version = IO.read(File.expand_path('../VERSION', __FILE__)) rescue "0.0.1"
spec.authors = ["John Manero"]
spec.email = ["jmanero@dyn.com"]
spec.description = %q{Manage the lifecycle of a deployment with Chef}
spec.summary = %q{Manage the lifecycle of a deployment with Chef}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "thor-scmversion"
spec.add_dependency "berkshelf", "= 2.0.12"
spec.add_dependency "colorize"
spec.add_dependency "growl"
spec.add_dependency "ridley", "= 1.5.3"
spec.add_dependency "thor-scmversion", "= 1.4.0"
end
|
Add status check for erchef | #
# Author:: Adam Jacob (<adam@opscode.com>)
# Author:: Seth Falcon (<seth@opscode.com>)
# Copyright:: Copyright (c) 2011-2012 Opscode, Inc.
#
bootstrap_status_file = "/var/opt/chef-server/bootstrapped"
erchef_dir = "/opt/chef-server/embedded/service/erchef"
# TODO: add a check to curl -skf http://localhost:8000/_status
execute "boostrap-chef-server" do
command "bin/bootstrap-chef-server"
cwd erchef_dir
not_if { File.exists?(bootstrap_status_file) }
end
file bootstrap_status_file do
owner "root"
group "root"
mode "0600"
content "You're bootstraps are belong to Chef"
end
| #
# Author:: Adam Jacob (<adam@opscode.com>)
# Author:: Seth Falcon (<seth@opscode.com>)
# Copyright:: Copyright (c) 2011-2012 Opscode, Inc.
#
bootstrap_status_file = "/var/opt/chef-server/bootstrapped"
erchef_dir = "/opt/chef-server/embedded/service/erchef"
execute "verify-system-status" do
command "curl -sf http://localhost:8000/_status"
retries 20
not_if { File.exists?(bootstrap_status_file) }
end
execute "boostrap-chef-server" do
command "bin/bootstrap-chef-server"
cwd erchef_dir
not_if { File.exists?(bootstrap_status_file) }
end
file bootstrap_status_file do
owner "root"
group "root"
mode "0600"
content "You're bootstraps are belong to Chef"
end
|
Improve Gtk module override implementation. | module GirFFI
module Overrides
module Gtk
def self.included(base)
GirFFI::Builder.setup_function "Gtk", "init"
base.class_eval do
class << self
alias _base_init init
def init
(my_len, my_args) = _base_init ARGV.length + 1, [$0, *ARGV]
my_args.shift
ARGV.replace my_args
end
private :_base_init
end
end
end
end
end
end
| module GirFFI
module Overrides
module Gtk
def self.included(base)
GirFFI::Builder.setup_function "Gtk", "init"
base.extend ClassMethods
base.class_eval do
class << self
alias init_without_auto_argv init
alias init init_with_auto_argv
end
end
end
module ClassMethods
def init_with_auto_argv
(my_len, my_args) = init_without_auto_argv ARGV.length + 1, [$0, *ARGV]
my_args.shift
ARGV.replace my_args
end
end
end
end
end
|
Add guard-cucumber to the bundle | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'aruba-doubles'
s.version = '0.1.1'
s.authors = ["Björn Albers"]
s.email = ["bjoernalbers@googlemail.com"]
s.description = 'Stub command line applications with Cucumber'
s.summary = "#{s.name}-#{s.version}"
s.homepage = 'https://github.com/bjoernalbers/aruba-doubles'
s.add_dependency 'cucumber', '>= 1.0.2'
s.add_development_dependency 'aruba', '>= 0.4.6'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
end
| # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'aruba-doubles'
s.version = '0.1.1'
s.authors = ["Björn Albers"]
s.email = ["bjoernalbers@googlemail.com"]
s.description = 'Stub command line applications with Cucumber'
s.summary = "#{s.name}-#{s.version}"
s.homepage = 'https://github.com/bjoernalbers/aruba-doubles'
s.add_dependency 'cucumber', '>= 1.0.2'
s.add_development_dependency 'aruba', '>= 0.4.6'
s.add_development_dependency 'guard-cucumber', '>= 0.7.3'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
end
|
Improve documentation and layout of code | require_relative 'events'
module Nark
module Plugin
#
# Essentially this is a value object used to store a plugins event block
# which is then used by the middleware to trigger at the right time.
#
class Event
attr_reader :type
attr_reader :method_block
attr_reader :plugin
attr_reader :attributes
protected
attr_writer :type
attr_writer :method_block
attr_writer :plugin
attr_writer :attributes
public
def initialize params
@attributes = params
@type = params[:type]
@method_block = params[:method_block]
@plugin = params[:plugin]
end
def exists?
Nark::Plugin.events.find { |event| method_block == event.method_block }
end
def to_hash
attributes
end
end
end
end
| require_relative 'events'
module Nark
module Plugin
#
# An event based value object allowing use to easily deal with event based functionality.
#
# Used to keep track and interact with a plugin's triggers.
#
# Essentially this is a value object used to store a plugins event block which is then used by the middleware to
# trigger at the right time.
#
class Event
#
# Only allow the object to change the state of the event
#
private
#
# Protect the the object from being changed externally
#
attr_writer :type
attr_writer :method_block
attr_writer :plugin
#
# Used to simplify the way parameters are returned and stored
#
attr_accessor :attributes
#
# Stores the type of event
#
attr_reader :type
#
# Stores the event block to be triggered
#
attr_reader :method_block
#
# Stores the name of the plugin that the event belongs to
#
attr_reader :plugin
#
# Initialise the new Event
#
def initialize params
@attributes = params
@type = params[:type]
@method_block = params[:method_block]
@plugin = params[:plugin]
end
#
# Checks the exists of the plugin in the events collection
#
def exists?
Nark::Plugin.events.find { |event| method_block == event.method_block }
end
#
# Returns a hash of the events attributes
#
def to_hash
attributes
end
end
end
end
|
Bump the version, tweak the summary and set the correct home page. | spec = Gem::Specification.new do |s|
s.name = 'google_analytics'
s.version = '1.1'
s.date = "2008-11-11"
s.author = 'Graeme Mathieson'
s.email = 'mathie@rubaidh.com'
s.has_rdoc = true
s.homepage = 'http://github.com/rubaidh/google_analytics/tree/master'
s.summary = "[Rails] This is a quick 'n' dirty module to easily enable" +
'Google Analytics support in your application.'
s.description = 'By default this gem will output google analytics code for' +
"every page automatically, if it's configured correctly." +
"This is done by adding:\n" +
"Rubaidh::GoogleAnalytics.tracker_id = 'UA-12345-67'\n"
'to your `config/environment.rb`, inserting your own tracker id.'
'This can be discovered by looking at the value assigned to +_uacct+' +
'in the Javascript code.'
s.files = %w( CREDITS MIT-LICENSE README.rdoc Rakefile rails/init.rb
test/google_analytics_test.rb
test/test_helper.rb
test/view_helpers_test.rb
lib/rubaidh.rb
lib/rubaidh/google_analytics.rb
lib/rubaidh/view_helpers.rb
tasks/google_analytics.rake)
s.add_dependency 'actionpack'
end
| spec = Gem::Specification.new do |s|
s.name = 'google_analytics'
s.version = '1.1.1'
s.date = "2009-01-02"
s.author = 'Graeme Mathieson'
s.email = 'mathie@rubaidh.com'
s.has_rdoc = true
s.homepage = 'http://rubaidh.com/portfolio/open-source/google-analytics/'
s.summary = "[Rails] Easily enable Google Analytics support in your Rails application."
s.description = 'By default this gem will output google analytics code for' +
"every page automatically, if it's configured correctly." +
"This is done by adding:\n" +
"Rubaidh::GoogleAnalytics.tracker_id = 'UA-12345-67'\n"
'to your `config/environment.rb`, inserting your own tracker id.'
'This can be discovered by looking at the value assigned to +_uacct+' +
'in the Javascript code.'
s.files = %w( CREDITS MIT-LICENSE README.rdoc Rakefile rails/init.rb
test/google_analytics_test.rb
test/test_helper.rb
test/view_helpers_test.rb
lib/rubaidh.rb
lib/rubaidh/google_analytics.rb
lib/rubaidh/view_helpers.rb
tasks/google_analytics.rake)
s.add_dependency 'actionpack'
end
|
Add test for first POST | require 'spec_helper'
require File.expand_path("../../calfresh_web", __FILE__)
describe CalfreshWeb do
describe 'GET /application/basic_info' do
it 'responds successfully' do
get '/application/basic_info'
expect(last_response.status).to eq(200)
end
end
end
| require 'spec_helper'
require File.expand_path("../../calfresh_web", __FILE__)
describe CalfreshWeb do
describe 'GET /application/basic_info' do
it 'responds successfully' do
get '/application/basic_info'
expect(last_response.status).to eq(200)
end
end
pending
describe 'POST /application/basic_info' do
end
end
|
Tweak unit test config to be better behaved. | require 'coveralls'
if ENV["ENABLE_SIMPLE_COV"]
require 'simplecov'
SimpleCov.start do
add_group "Lib", "lib"
add_filter "/test/"
command_name "Unit Tests"
formatter SimpleCov::Formatter::MultiFormatter[
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
end
end
require 'test/unit'
ENV["QUASAR_ENV"] = "test"
require 'mocha/setup'
module TestHelper
end
| if ENV["COVERAGE"]
require 'coveralls'
require 'codeclimate-test-reporter'
require 'simplecov'
SimpleCov.start do
add_group "Lib", "lib"
add_filter "/test/"
command_name "Unit Tests"
formatter SimpleCov::Formatter::MultiFormatter[
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter,
CodeClimate::TestReporter::Formatter
]
end
end
require 'test/unit'
ENV["QUASAR_ENV"] = "test"
require 'mocha/setup'
module TestHelper
end
|
Use expect instead of should | require 'spec_helper'
describe 'zaqar' do
let :facts do
{
:osfamily => 'Debian'
}
end
let :default_params do
{}
end
[
{},
{}
].each do |param_set|
describe "when #{param_set == {} ? "using default" : "specifying"} class parameters" do
let :param_hash do
param_set == {} ? default_params : params
end
let :params do param_set end
it { should contain_file('/etc/zaqar/').with(
'ensure' => 'directory',
'owner' => 'zaqar',
'mode' => '0770'
)}
end
end
describe 'on Debian platforms' do
let :facts do
{ :osfamily => 'Debian' }
end
let(:params) { default_params }
it {should_not contain_package('zaqar')}
end
describe 'on RedHat platforms' do
let :facts do
{ :osfamily => 'RedHat' }
end
let(:params) { default_params }
it { should contain_package('openstack-zaqar')}
end
end
| require 'spec_helper'
describe 'zaqar' do
let :facts do
{
:osfamily => 'Debian'
}
end
let :default_params do
{}
end
[
{},
{}
].each do |param_set|
describe "when #{param_set == {} ? "using default" : "specifying"} class parameters" do
let :param_hash do
param_set == {} ? default_params : params
end
let :params do param_set end
it { should contain_file('/etc/zaqar/').with(
'ensure' => 'directory',
'owner' => 'zaqar',
'mode' => '0770'
)}
end
end
describe 'on Debian platforms' do
let :facts do
{ :osfamily => 'Debian' }
end
let(:params) { default_params }
it {should_not contain_package('zaqar')}
end
describe 'on RedHat platforms' do
let :facts do
{ :osfamily => 'RedHat' }
end
let(:params) { default_params }
it { expect contain_package('openstack-zaqar')}
end
end
|
Add ability to pass app block | require 'rack/handler'
require 'yars'
module Rack
# We register with the handler lack can load our server.
module Handler
# We boot the server here
class Yars
def self.run(app, options = {})
environment = ENV['RACK_ENV'] || 'development'
default_host = environment == 'development' ? 'localhost' : '0.0.0.0'
host = options.delete(:Host) || default_host
port = options.delete(:Port) || 8080
server = ::Yars::Server.new host, port, app, options
yield server if block_given?
server.start
end
def self.valid_options
{
'Host=HOST' => 'Hostname to listen on (default: locahost)',
'Port=PORT' => 'Port to listen on (default: 8080)',
'Concurrency=NUM' => 'Number of threads to run (default: 16)'
}
end
end
register :yars, Yars
end
end
| require 'rack/handler'
require 'yars'
module Rack
# We register with the handler lack can load our server.
module Handler
# We boot the server here
class Yars
def self.run(app, options = {}, &block)
environment = ENV['RACK_ENV'] || 'development'
default_host = environment == 'development' ? 'localhost' : '0.0.0.0'
app = Rack::Builder.new(&block).to_app if block_given?
host = options.delete(:Host) || default_host
port = options.delete(:Port) || 8080
server = ::Yars::Server.new host, port, app, options
yield server if block_given?
server.start
end
def self.valid_options
{
'Host=HOST' => 'Hostname to listen on (default: locahost)',
'Port=PORT' => 'Port to listen on (default: 8080)',
'Concurrency=NUM' => 'Number of threads to run (default: 16)'
}
end
end
register :yars, Yars
end
end
|
Update Balsamiq Mockups to 3.1.5. | cask :v1 => 'balsamiq-mockups' do
version '3.1.4'
sha256 '36b2be0f506d74df95969c0f43a51a58fec888aee3b1a802e0e0b87b7c93a1b3'
# amazonaws is the official download host per the vendor homepage
url "https://s3.amazonaws.com/build_production/mockups-desktop/Balsamiq_Mockups_#{version}.dmg"
name 'Balsamiq Mockups'
homepage 'https://balsamiq.com/'
license :commercial
app "Balsamiq Mockups #{version.to_i}.app"
end
| cask :v1 => 'balsamiq-mockups' do
version '3.1.5'
sha256 '738c986bc3d43d6a9cd0bbef9e8bd50edf5b5e7b865ff72c8fa9fe9048c662d8'
# amazonaws is the official download host per the vendor homepage
url "https://s3.amazonaws.com/build_production/mockups-desktop/Balsamiq_Mockups_#{version}.dmg"
name 'Balsamiq Mockups'
homepage 'https://balsamiq.com/'
license :commercial
app "Balsamiq Mockups #{version.to_i}.app"
end
|
Use JavaFX bindings to dis-/en-able the ok button. | require 'jrubyfx'
class KeyValueEditor
include JRubyFX::Controller
fxml 'KeyValueEnter.fxml'
# @param [Object] caller The object that should be called back after submit. Ususally the caller
# @param [Object] callback The callback method to be called on caller.
# @param [Object] other_stuff Other stuff that will be passed to the callback as 2nd .. param
def setup(caller, callback, *other_stuff)
@caller = caller
@callback = callback
@other_stuff = other_stuff
setup_validation
end
def setup_validation
@key_field.text_property.add_change_listener do
validate_input
end
@value_field.text_property.add_change_listener do
validate_input
end
end
def validate_input
if @key_field.text.empty? || @value_field.text.empty?
@submit_button.disabled = true
else
@submit_button.disabled = false
end
end
def submit
key = @key_field.text
value = @value_field.text
ret = { :key => key,
:value => value
}
if @caller.respond_to?(@callback)
op = @caller.public_method @callback
op.call ret, *@other_stuff
end
@stage.close
end
def cancel
@stage.close
end
end
| require 'jrubyfx'
class KeyValueEditor
include JRubyFX::Controller
fxml 'KeyValueEnter.fxml'
def initialize
key_field_empty = @key_field.text_property.is_empty
value_field_empty = @value_field.text_property.is_empty
input_invalid = key_field_empty.or(value_field_empty)
@submit_button.disable_property.bind input_invalid
end
# @param [Object] caller The object that should be called back after submit. Ususally the caller
# @param [Object] callback The callback method to be called on caller.
# @param [Object] other_stuff Other stuff that will be passed to the callback as 2nd .. param
def setup(caller, callback, *other_stuff)
@caller = caller
@callback = callback
@other_stuff = other_stuff
end
def submit
key = @key_field.text
value = @value_field.text
ret = { :key => key,
:value => value
}
if @caller.respond_to?(@callback)
op = @caller.public_method @callback
op.call ret, *@other_stuff
end
@stage.close
end
def cancel
@stage.close
end
end
|
Change email addresses from @causes.com to @brigade.com | $LOAD_PATH << File.expand_path('../lib', __FILE__)
require 'diffux_core/version'
Gem::Specification.new do |s|
s.name = 'diffux-core'
s.version = DiffuxCore::VERSION
s.license = 'MIT'
s.summary = 'Diffux Core'
s.description = 'Tools for taking and comparing responsive website snapshots'
s.authors = ['Joe Lencioni', 'Henric Trotzig']
s.email = ['joe.lencioni@causes.com', 'henric.trotzig@causes.com']
s.require_paths = ['lib']
s.files = Dir['lib/**/*']
s.executables = ['diffux-snapshot', 'diffux-compare']
s.required_ruby_version = '>= 2.0.0'
s.add_dependency 'chunky_png', '~>1.3.1'
s.add_dependency 'oily_png', '~> 1.1.1'
s.add_dependency 'phantomjs', '1.9.2.1'
s.add_dependency 'diff-lcs', '~> 1.2'
s.add_development_dependency 'rspec', '~> 2.14'
s.add_development_dependency 'mocha', '~> 1.0'
s.add_development_dependency 'codeclimate-test-reporter'
end
| $LOAD_PATH << File.expand_path('../lib', __FILE__)
require 'diffux_core/version'
Gem::Specification.new do |s|
s.name = 'diffux-core'
s.version = DiffuxCore::VERSION
s.license = 'MIT'
s.summary = 'Diffux Core'
s.description = 'Tools for taking and comparing responsive website snapshots'
s.authors = ['Joe Lencioni', 'Henric Trotzig']
s.email = ['joe.lencioni@brigade.com', 'henric.trotzig@brigade.com']
s.require_paths = ['lib']
s.files = Dir['lib/**/*']
s.executables = ['diffux-snapshot', 'diffux-compare']
s.required_ruby_version = '>= 2.0.0'
s.add_dependency 'chunky_png', '~>1.3.1'
s.add_dependency 'oily_png', '~> 1.1.1'
s.add_dependency 'phantomjs', '1.9.2.1'
s.add_dependency 'diff-lcs', '~> 1.2'
s.add_development_dependency 'rspec', '~> 2.14'
s.add_development_dependency 'mocha', '~> 1.0'
s.add_development_dependency 'codeclimate-test-reporter'
end
|
Set locale even for key-less sources | #! /usr/bin/env ruby
require 'json'
sources = JSON.parse(File.read(File.join(File.dirname($0), 'ubuntu.json')))
successes = sources.select do |src|
puts "-------------------\nAdding #{src.inspect}\n"
if src['key_url']
system("curl -sSL #{src['key_url'].untaint.inspect} | sudo -E env LANG=C.UTF-8 apt-key add -") && system("sudo -E env LANG=C.UTF-8 apt-add-repository -y #{src['sourceline'].untaint.inspect}")
else
system("sudo -E apt-add-repository -y #{src['sourceline'].untaint.inspect}")
end
end
| #! /usr/bin/env ruby
require 'json'
sources = JSON.parse(File.read(File.join(File.dirname($0), 'ubuntu.json')))
successes = sources.select do |src|
puts "-------------------\nAdding #{src.inspect}\n"
if src['key_url']
system("curl -sSL #{src['key_url'].untaint.inspect} | sudo -E env LANG=C.UTF-8 apt-key add -") && system("sudo -E env LANG=C.UTF-8 apt-add-repository -y #{src['sourceline'].untaint.inspect}")
else
system("sudo -E env LANG=C.UTF-8 apt-add-repository -y #{src['sourceline'].untaint.inspect}")
end
end
|
Add unit test for bin/trepan | #!/usr/bin/env ruby
require 'test/unit'
require 'rbconfig'
load File.join(File.dirname(__FILE__), %w(.. .. bin trepan))
# Test bin/trepan Module methods
class TestBinTrepan < Test::Unit::TestCase
include Trepanning
def test_ruby_path
rb_path = ruby_path
assert_equal(true, File.executable?(rb_path),
"#{rb_path} should be an executable Ruby interpreter")
# Let us test that we get *exactly* the same configuration as we
# have in this. I'm a ball buster.
cmd = "#{rb_path} -rrbconfig -e 'puts Marshal.dump(RbConfig::CONFIG)'"
rb_config = Marshal.load(`#{cmd}`)
assert_equal(RbConfig::CONFIG, rb_config,
"#{rb_path} config doesn't match got:
#{rb_config}
expected:
#{RbConfig::CONFIG}
")
end
def test_whence_file
abs_path_me = File.expand_path(__FILE__)
assert_equal(abs_path_me, whence_file(abs_path_me),
"whence_file should have just returned #{abs_path_me}")
basename_me = File.basename(__FILE__)
dirname_me = File.dirname(__FILE__)
# Add my directory onto the beginning of PATH
path_dirs = ENV['PATH'].split(File::PATH_SEPARATOR)
path_dirs.unshift(dirname_me)
ENV['PATH'] = path_dirs.join(File::PATH_SEPARATOR)
assert_equal(File.join(dirname_me, basename_me),
whence_file(basename_me),
"whence_file should have found me")
# Restore old path
path_dirs.shift
ENV['PATH'] = path_dirs.join(File::PATH_SEPARATOR)
end
end
| |
Package palletjack2salt in the tools gem | #-*- ruby -*-
Gem::Specification.new do |s|
s.name = 'palletjack-tools'
s.summary = 'Tools for the Pallet Jack Lightweight Configuration Management Database'
s.description = File.read(File.join(File.dirname(__FILE__), 'README.md'))
s.homepage = 'https://github.com/saab-simc-admin/palletjack'
s.version = '0.0.3'
s.author = 'Karl-Johan Karlsson'
s.email = 'karl-johan.karlsson@saabgroup.com'
s.license = 'MIT'
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '~>2'
s.add_runtime_dependency 'palletjack', s.version
s.add_runtime_dependency 'dns-zone', '~> 0.3'
s.add_runtime_dependency 'ruby-ip', '~> 0.9'
s.files = [ 'README.md', 'LICENSE' ]
s.files += Dir['tools/*']
s.bindir = 'tools/'
s.executables = ['dump_pallet', 'palletjack2kea']
s.has_rdoc = true
end
| #-*- ruby -*-
Gem::Specification.new do |s|
s.name = 'palletjack-tools'
s.summary = 'Tools for the Pallet Jack Lightweight Configuration Management Database'
s.description = File.read(File.join(File.dirname(__FILE__), 'README.md'))
s.homepage = 'https://github.com/saab-simc-admin/palletjack'
s.version = '0.0.3'
s.author = 'Karl-Johan Karlsson'
s.email = 'karl-johan.karlsson@saabgroup.com'
s.license = 'MIT'
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '~>2'
s.add_runtime_dependency 'palletjack', s.version
s.add_runtime_dependency 'dns-zone', '~> 0.3'
s.add_runtime_dependency 'ruby-ip', '~> 0.9'
s.files = [ 'README.md', 'LICENSE' ]
s.files += Dir['tools/*']
s.bindir = 'tools/'
s.executables = ['dump_pallet', 'palletjack2kea', 'palletjack2salt']
s.has_rdoc = true
end
|
Add nested data solution file | # RELEASE 2: NESTED STRUCTURE GOLF
# Hole 1
# Target element: "FORE"
array = [[1,2], ["inner", ["eagle", "par", ["FORE", "hook"]]]]
# attempts:
# ============================================================
p array[1][1][1][0]
p array[1][1][2][0]
# ============================================================
# Hole 2
# Target element: "congrats!"
hash = {outer: {inner: {"almost" => {3 => "congrats!"}}}}
# attempts:
# ============================================================
p hash [:outer][:inner]["almost"][3]
# ============================================================
# Hole 3
# Target element: "finished"
nested_data = {array: ["array", {hash: "finished"}]}
# attempts:
# ============================================================
p nested_data[:array][1][:hash]
# ============================================================
# RELEASE 3: ITERATE OVER NESTED STRUCTURES
number_array = [5, [10, 15], [20,25,30], 35]
number_array.map! { |element|
if element.kind_of?(Array)
element.map!{ |subelement| subelement += 5 }
else
element += 5
end
}
p number_array
# Bonus:
startup_names = ["bit", ["find", "fast", ["optimize", "scope"]]]
startup_names.map! { |element|
if element.kind_of?(Array)
element.map! { |subelement|
if subelement.kind_of?(Array)
subelement.map! {|trielement| trielement+"ly"}
else
subelement+"ly"
end
}
else
element + "ly"
end
}
p startup_names
# REFLECTION
=begin
What are some general rules you can apply to nested arrays?
I think the most important thing to remember is to make sure you are identifying the correct object type for the nested data structure. Once you have that straigtened out, you can easily manipulate that data structure just as you have been doing as long as you keep track of what nested level you are on.
What are some ways you can iterate over nested arrays?
We used map and then used a number of nested if/else statement depending on how many levels deep you need to go.
Did you find any good new methods to implement or did you re-use one you were already familiar with? What was it and why did you decide that was a good option?
The kind_of? method was useful for us when we were iterating through an array that has another array nested in it. With it, we can modify the nested array by using an if statement and checking the object type.
=end | |
Correct `event_host?` with nil check on `@event` | module ApplicationHelper
def admin?
!current_user.nil? and current_user.admin?
end
def event_host?
event_host = nil
unless admin?
else
event_host = EventHost.where("user_id = ? and event_id = ?", current_user.id, @event.id)
end
end
admin? || !event_host.nil?
end
def yes_no (value)
value ? "Yes" : "No"
end
def receipts_exist?
current_user.user_events.any? {|user_event| user_event.total_price > 0}
end
def unpaid_payments?
current_user.user_events.any? {|user_event| user_event.additional_payments.any? {|payment| payment.unpaid?}}
end
def pending_payments
unpaid_payments = []
current_user.user_events.each do |user_event|
user_event.additional_payments.each do |payment|
if payment.unpaid?
unpaid_payments << payment
end
end
end
unpaid_payments
end
end
| module ApplicationHelper
def admin?
!current_user.nil? and current_user.admin?
end
def event_host?
event_host = nil
unless @event.nil?
unless admin?
event_host = EventHost.where("user_id = ? and event_id = ?", current_user.id, @event.id)
end
end
!@event.nil? && (admin? || !event_host.nil?)
end
def yes_no (value)
value ? "Yes" : "No"
end
def receipts_exist?
current_user.user_events.any? {|user_event| user_event.total_price > 0}
end
def unpaid_payments?
current_user.user_events.any? {|user_event| user_event.additional_payments.any? {|payment| payment.unpaid?}}
end
def pending_payments
unpaid_payments = []
current_user.user_events.each do |user_event|
user_event.additional_payments.each do |payment|
if payment.unpaid?
unpaid_payments << payment
end
end
end
unpaid_payments
end
end
|
Make name and presentation accessible in OptionValue | module Spree
class OptionValue < ActiveRecord::Base
belongs_to :option_type
acts_as_list :scope => :option_type
has_and_belongs_to_many :variants, :join_table => 'spree_option_values_variants'
end
end
| module Spree
class OptionValue < ActiveRecord::Base
belongs_to :option_type
acts_as_list :scope => :option_type
has_and_belongs_to_many :variants, :join_table => 'spree_option_values_variants'
attr_accessible :name, :presentation
end
end
|
Implement aggregate failures for feature specs. | # Adds extra matchers for Capybara
module Capybara::TestGroupHelpers
module FeatureHelpers
# Finds the given form with the given selector and target.
#
# @param [String|nil] selector The selector to find the form with.
def find_form(selector, action: nil)
attribute_selector =
if action
format('[action="%s"]', action)
else
''.freeze
end
result = find('form' + attribute_selector)
selector ? result.find(selector) : result
end
end
end
RSpec.configure do |config|
config.include Capybara::TestGroupHelpers::FeatureHelpers, type: :feature
end
| # Adds extra matchers for Capybara
module Capybara::TestGroupHelpers
module FeatureHelpers
# Finds the given form with the given selector and target.
#
# @param [String|nil] selector The selector to find the form with.
def find_form(selector, action: nil)
attribute_selector =
if action
format('[action="%s"]', action)
else
''.freeze
end
result = find('form' + attribute_selector)
selector ? result.find(selector) : result
end
end
end
RSpec.configure do |config|
config.include Capybara::TestGroupHelpers::FeatureHelpers, type: :feature
config.define_derived_metadata do |meta|
meta[:aggregate_failures] = true if !meta.key?(:aggregate_failures) && meta[:type] == :feature
end
end
|
Fix spelling in test script. | #!/usr/bin/env ruby
require 'erb'
require 'tempfile'
require 'tmpdir'
TESTDIR = File.join(File.dirname(__FILE__), 'tests')
if ARGV.size != 2
puts "Usage: #{$0} <path to clipp> <path to config>"
exit 1
end
clipp = ARGV[0]
config = ARGV[1]
failure = false
Dir.chdir(TESTDIR)
Dir.glob('*.erb').each do |test|
base = File.basename(test,'.erb')
print base
STDOUT.flush
erb = ERB.new(IO.read(test))
tmppath = File.join(Dir::tmpdir, 'clipp_tests.conf')
File.open(tmppath, 'w') do |clipp_config|
clipp_config.write(erb.result(binding))
end
test_cmd = "#{clipp} -c #{tmppath}"
if ! system(test_cmd)
puts "FAIL -- clipp existed non-zero"
puts "Command: #{test_cmd}"
failure = true
else
puts "PASS"
end
File.unlink(tmppath) if ! failure
end
exit 1 if failure
| #!/usr/bin/env ruby
require 'erb'
require 'tempfile'
require 'tmpdir'
TESTDIR = File.join(File.dirname(__FILE__), 'tests')
if ARGV.size != 2
puts "Usage: #{$0} <path to clipp> <path to config>"
exit 1
end
clipp = ARGV[0]
config = ARGV[1]
failure = false
Dir.chdir(TESTDIR)
Dir.glob('*.erb').each do |test|
base = File.basename(test,'.erb')
print base
STDOUT.flush
erb = ERB.new(IO.read(test))
tmppath = File.join(Dir::tmpdir, 'clipp_tests.conf')
File.open(tmppath, 'w') do |clipp_config|
clipp_config.write(erb.result(binding))
end
test_cmd = "#{clipp} -c #{tmppath}"
if ! system(test_cmd)
puts "FAIL -- clipp exited non-zero"
puts "Command: #{test_cmd}"
failure = true
else
puts "PASS"
end
File.unlink(tmppath) if ! failure
end
exit 1 if failure
|
Increment statsd keys around consumption | require "poseidon"
module CC
module Kafka
class Consumer
def initialize(client_id, seed_brokers, topic, partition)
@offset = Kafka.offset_model.find_or_create!(
topic: topic,
partition: partition,
)
Kafka.logger.debug("offset: #{@offset.topic}/#{@offset.partition} #{@offset.current}")
@consumer = Poseidon::PartitionConsumer.consumer_for_partition(
client_id,
seed_brokers,
@offset.topic,
@offset.partition,
@offset.current
)
end
def on_message(&block)
@on_message = block
end
def start
trap(:TERM) { stop }
@running = true
while @running do
fetch_messages
end
Kafka.logger.info("shutting down due to TERM signal")
ensure
@consumer.close
end
def stop
@running = false
end
private
def fetch_messages
@consumer.fetch.each do |message|
@offset.set(current: message.offset + 1)
Kafka.offset_model.transaction do
@on_message.call(BSON.deserialize(message.value))
end
end
rescue Poseidon::Errors::UnknownTopicOrPartition
Kafka.logger.debug("topic #{@topic} not created yet")
sleep 1
end
end
end
end
| require "poseidon"
module CC
module Kafka
class Consumer
def initialize(client_id, seed_brokers, topic, partition)
@offset = Kafka.offset_model.find_or_create!(
topic: topic,
partition: partition,
)
Kafka.logger.debug("offset: #{@offset.topic}/#{@offset.partition} #{@offset.current}")
@consumer = Poseidon::PartitionConsumer.consumer_for_partition(
client_id,
seed_brokers,
@offset.topic,
@offset.partition,
@offset.current
)
end
def on_message(&block)
@on_message = block
end
def start
trap(:TERM) { stop }
@running = true
while @running do
fetch_messages
end
Kafka.logger.info("shutting down due to TERM signal")
ensure
@consumer.close
end
def stop
@running = false
end
private
def fetch_messages
@consumer.fetch.each do |message|
Kafka.statsd.increment("messages.received")
Kafka.statsd.time("messages.processing") do
@offset.set(current: message.offset + 1)
Kafka.offset_model.transaction do
@on_message.call(BSON.deserialize(message.value))
end
end
Kafka.statsd.increment("messages.processed")
end
rescue Poseidon::Errors::UnknownTopicOrPartition
Kafka.logger.debug("topic #{@topic} not created yet")
sleep 1
end
end
end
end
|
Allow branches to be used as version in Git Package. | module Rip
class GitPackage < Package
include Sh::Git
handles "file://", "git://", '.git'
memoize :name
def name
source.split('/').last.chomp('.git')
end
def version
return @version if @version
fetch!
Dir.chdir cache_path do
@version = git_rev_parse('origin/master')[0,7]
end
end
def exists?
case source
when /^file:/
file_exists?
when /^git:/
remote_exists?
when /\.git$/
file_exists? || remote_exists?
else
false
end
end
def fetch!
if File.exists? cache_path
Dir.chdir cache_path do
git_fetch('origin')
end
else
git_clone(source, cache_path)
end
end
def unpack!
Dir.chdir cache_path do
git_reset_hard(version)
git_submodule_init
git_submodule_update
end
end
private
def file_exists?
File.exists? File.join(source.sub('file://', ''), '.git')
end
def remote_exists?
return false if git_ls_remote(source).size == 0
return true if !@version
fetch
Dir.chdir(cache_path) do
git_cat_file(@version).size > 0
end
end
end
end
| module Rip
class GitPackage < Package
include Sh::Git
handles "file://", "git://", '.git'
memoize :name
def name
source.split('/').last.chomp('.git')
end
def version
return @version if @version
fetch!
Dir.chdir cache_path do
@version = git_rev_parse('origin/master')[0,7]
end
end
def exists?
case source
when /^file:/
file_exists?
when /^git:/
remote_exists?
when /\.git$/
file_exists? || remote_exists?
else
false
end
end
def fetch!
if File.exists? cache_path
Dir.chdir cache_path do
git_fetch('origin')
end
else
git_clone(source, cache_path)
end
end
def unpack!
Dir.chdir cache_path do
git_reset_hard version_is_branch? ? "origin/#{version}" : version
git_submodule_init
git_submodule_update
end
end
private
def file_exists?
File.exists? File.join(source.sub('file://', ''), '.git')
end
def remote_exists?
return false if git_ls_remote(source).size == 0
return true if !@version
fetch
Dir.chdir(cache_path) do
git_cat_file(@version).size > 0 || version_is_branch?
end
end
def version_is_branch?
git_cat_file("origin/#{version}").size > 0
end
end
end
|
Add a task to create Open Data export via CSV files | task :open_data_export => :environment do
require 'csv'
folder_name = File.join(Rails.root, 'tmp', "open_data_#{Process.pid}")
puts "CSV exporting for open data to #{folder_name}"
Dir.mkdir folder_name
tags_csv = CSV.open(File.join(folder_name, "tags.csv"), "w")
elections_csv = CSV.open(File.join(folder_name, "elections.csv"), "w")
election_tags_csv = CSV.open(File.join(folder_name, "election_tags.csv"), "w")
candidacies_csv = CSV.open(File.join(folder_name, "candidacies.csv"), "w")
propositions_csv = CSV.open(File.join(folder_name, "propositions.csv"), "w")
tags_csv << ['id', 'name']
elections_csv << ['id', 'name', 'date']
election_tags_csv << ['election_id', 'position', 'tag_id', 'parent_tag_id']
candidacies_csv << ['id', 'election_id', 'organization_name', 'candidate_first_name', 'candidate_last_name']
propositions_csv << ['id', 'candidacy_id', 'tag_ids', 'text']
Tag.all.each do |tag|
puts "- #{tag.namespace}"
tags_csv << [
tag.id.to_s,
tag.name
]
end
Election.where(published: true).each do |election|
puts "- #{election.namespace}"
elections_csv << [
election.id.to_s,
election.name,
election.date.to_s
]
election.election_tags.each do |election_tag|
election_tags_csv << [
election_tag.election_id.to_s,
election_tag.position,
election_tag.tag_id,
election_tag.parent_tag_id,
]
end
election.candidacies.where(published: true).each do |candidacy|
puts " - #{candidacy.namespace}"
candidacies_csv << [
candidacy.id.to_s,
candidacy.election_id.to_s,
candidacy.organization.try(:name),
candidacy.candidates.first.first_name,
candidacy.candidates.first.last_name
]
puts " - #{candidacy.propositions.count} propositions"
candidacy.propositions.each do |proposition|
propositions_csv << [
proposition.id.to_s,
proposition.candidacy_id.to_s,
proposition.tag_ids.to_s,
proposition.text
]
end
end
end
elections_csv.close
candidacies_csv.close
propositions_csv.close
end
| |
Fix `undefined method 'arel_table' for Ci::Group:Class` error | module Ci
class GroupVariable < ActiveRecord::Base
extend Gitlab::Ci::Model
include HasVariable
include Presentable
belongs_to :group
alias_attribute :secret_value, :value
validates :key, uniqueness: {
scope: :group_id,
message: "(%{value}) has already been taken"
}
scope :unprotected, -> { where(protected: false) }
end
end
| module Ci
class GroupVariable < ActiveRecord::Base
extend Gitlab::Ci::Model
include HasVariable
include Presentable
belongs_to :group, class_name: "::Group"
alias_attribute :secret_value, :value
validates :key, uniqueness: {
scope: :group_id,
message: "(%{value}) has already been taken"
}
scope :unprotected, -> { where(protected: false) }
end
end
|
Fix events chema in RES repo spec | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'rails_event_store'
require 'example_invoicing_app'
RSpec.configure do |config|
config.disable_monkey_patching!
config.around(:each) do |example|
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Schema.define do
self.verbose = false
create_table(:event_store_events) do |t|
t.string :stream, null: false
t.string :event_type, null: false
t.string :event_id, null: false
t.text :metadata
t.text :data, null: false
t.datetime :created_at, null: false
end
add_index :event_store_events, :stream
add_index :event_store_events, :created_at
add_index :event_store_events, :event_type
add_index :event_store_events, :event_id, unique: true
end
example.run
end
end
| $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'rails_event_store'
require 'example_invoicing_app'
RSpec.configure do |config|
config.disable_monkey_patching!
config.around(:each) do |example|
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Schema.define do
self.verbose = false
create_table(:event_store_events_in_streams, force: true) do |t|
t.string :stream, null: false
t.integer :position, null: true
t.references :event, null: false, type: :string
t.datetime :created_at, null: false
end
add_index :event_store_events_in_streams, [:stream, :position], unique: true
add_index :event_store_events_in_streams, [:created_at]
# add_index :event_store_events_in_streams, [:stream, :event_uuid], unique: true
# add_index :event_store_events_in_streams, [:event_uuid]
create_table(:event_store_events, id: false, force: true) do |t|
t.string :id, limit: 36, primary_key: true, null: false
t.string :event_type, null: false
t.text :metadata
t.text :data, null: false
t.datetime :created_at, null: false
end
add_index :event_store_events, :created_at
end
example.run
end
end
|
Add a troubleshooter validation plugin | module TroubleshooterChecker
class TroubleshooterChecker < Jekyll::Generator
def check_data(troubleshooter)
questions = troubleshooter['questions']
questions.each do |key, question|
answers = question['answers']
fail "No answers for question #{key}" if answers.empty?
question['answers'].each do |answer|
next_question = answer['nextquestion']
fail "Undefined troubleshooter question #{next_question}" unless next_question.nil? or questions.has_key?(next_question)
end
end
end
def generate(site)
check_data(site.data['troubleshooter'])
end
end
end
| |
Update ruby_engine requirement from ~> 1.0 to >= 1, < 3 | # frozen_string_literal: true
# NOTE: Have to use __FILE__ until Ruby 1.x support is dropped
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rspec/pending_for/version'
Gem::Specification.new do |spec|
spec.name = 'rspec-pending_for'
spec.version = Rspec::PendingFor::VERSION
spec.authors = ['Peter Boling']
spec.email = ['peter.boling@gmail.com']
spec.summary = 'Mark specs pending or skipped for specific Ruby engine (e.g. MRI or JRuby) / version combinations'
spec.homepage = 'https://github.com/pboling/rspec-pending_for'
spec.license = 'MIT'
spec.files = Dir['lib/**/*', 'LICENSE', 'README.md']
spec.bindir = 'exe'
spec.require_paths = ['lib']
spec.add_dependency 'rspec-core'
spec.add_dependency 'ruby_engine', '~> 1.0'
spec.add_dependency 'ruby_version', '~> 1.0'
spec.add_development_dependency 'appraisal'
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'minitest', '~> 5.3'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec', '~> 3'
end
| # frozen_string_literal: true
# NOTE: Have to use __FILE__ until Ruby 1.x support is dropped
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rspec/pending_for/version'
Gem::Specification.new do |spec|
spec.name = 'rspec-pending_for'
spec.version = Rspec::PendingFor::VERSION
spec.authors = ['Peter Boling']
spec.email = ['peter.boling@gmail.com']
spec.summary = 'Mark specs pending or skipped for specific Ruby engine (e.g. MRI or JRuby) / version combinations'
spec.homepage = 'https://github.com/pboling/rspec-pending_for'
spec.license = 'MIT'
spec.files = Dir['lib/**/*', 'LICENSE', 'README.md']
spec.bindir = 'exe'
spec.require_paths = ['lib']
spec.add_dependency 'rspec-core'
spec.add_dependency 'ruby_engine', '>= 1', '< 3'
spec.add_dependency 'ruby_version', '~> 1.0'
spec.add_development_dependency 'appraisal'
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'minitest', '~> 5.3'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec', '~> 3'
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.