Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Use smallint for stage index column | class AddIndexToCiStage < ActiveRecord::Migration
include Gitlab::Database::MigrationHelpers
DOWNTIME = false
def change
add_column :ci_stages, :index, :integer
end
end
| class AddIndexToCiStage < ActiveRecord::Migration
include Gitlab::Database::MigrationHelpers
DOWNTIME = false
def change
add_column :ci_stages, :index, :integer, limit: 2
end
end
|
Fix authenticated? to return boolean | module Picturelife
class << self
attr_accessor :client_id
attr_accessor :client_secret
attr_accessor :access_token
attr_reader :redirect_uri
def redirect_uri=(uri)
@redirect_uri = escape_uri(uri)
end
def configured?
@client_id &&
@client_secret &&
@redirect_uri
end
def authenticated?
@access_token
end
def reset_configuration!
@client_id = nil
@client_secret = nil
@redirect_uri = nil
end
def reset_authentication!
@access_token = nil
end
end
end
| module Picturelife
class << self
attr_accessor :client_id
attr_accessor :client_secret
attr_accessor :access_token
attr_reader :redirect_uri
def redirect_uri=(uri)
@redirect_uri = escape_uri(uri)
end
def configured?
@client_id &&
@client_secret &&
@redirect_uri
end
def authenticated?
!! @access_token
end
def reset_configuration!
@client_id = nil
@client_secret = nil
@redirect_uri = nil
end
def reset_authentication!
@access_token = nil
end
end
end
|
Change mind about redirect functionality, do not let people edit slugs | class BlogPost < ActiveRecord::Base
TOPICS = ['other', 'biking', 'cycling']
before_create :generate_slug
belongs_to :author
private
def generate_slug
title = self.title
slug = title.gsub(/[^a-zA-Z\d\s]/, '').gsub(' ', '-').downcase
# TODO: revisit the following logic once the redirects table is
# implemented to account for the fact that a blog post's slug
# could have been changed but also exist in the redirects table.
# This looks for slugs that look like #{current-slug}-2 so we
# can change our slug for this post to increment the end digit.
existing_posts_with_incremented_slug = ActiveRecord::Base.connection.execute("SELECT slug FROM blog_posts WHERE slug ~* '#{slug}-\\d$';").to_a.map{ |h| h['slug'] }
if existing_posts_with_incremented_slug.any?
incremented_values = existing_posts_with_incremented_slug.map do |incremented_slug|
incremented_slug.gsub("#{slug}-", '').to_i
end
new_incremented_value = incremented_values.max + 1
return self.slug = "#{slug}-#{new_incremented_value}"
end
if BlogPost.exists?(slug: slug)
return self.slug = "#{slug}-2"
end
self.slug = slug
end
end
| class BlogPost < ActiveRecord::Base
TOPICS = ['other', 'biking', 'cycling']
before_create :generate_slug
belongs_to :author
private
def generate_slug
title = self.title
slug = title.gsub(/[^a-zA-Z\d\s]/, '').gsub(' ', '-').downcase
# This looks for slugs that look like #{current-slug}-2 so we
# can change our slug for this post to increment the end digit.
existing_posts_with_incremented_slug = ActiveRecord::Base.connection.execute("SELECT slug FROM blog_posts WHERE slug ~* '#{slug}-\\d$';").to_a.map{ |h| h['slug'] }
if existing_posts_with_incremented_slug.any?
incremented_values = existing_posts_with_incremented_slug.map do |incremented_slug|
incremented_slug.gsub("#{slug}-", '').to_i
end
new_incremented_value = incremented_values.max + 1
return self.slug = "#{slug}-#{new_incremented_value}"
end
if BlogPost.exists?(slug: slug)
return self.slug = "#{slug}-2"
end
self.slug = slug
end
end
|
Create gems directory in new applications. | require "merb-gen/helpers"
require "merb-gen/base"
class MerbGenerator < Merb::GeneratorBase
def initialize(args, runtime_options = {})
@base = File.dirname(__FILE__)
@name = args.first
super
@destination_root = @name
end
protected
def banner
<<-EOS.split("\n").map{|x| x.strip}.join("\n")
Creates a Merb application stub.
USAGE: #{spec.name} -g path
Set environment variable MERB_ORM=[activerecord|datamapper|sequel]
to pre-enabled an ORM.
EOS
end
def default_orm?(orm)
ENV['MERB_ORM'] == orm.to_s
end
def default_test_suite?(suite)
return ENV['MERB_TEST_SUITE'] == suite.to_s if ENV['MERB_TEST_SUITE']
options[suite]
end
def display_framework_selections
end
def create_dirs
m.directory 'log'
end
end
| require "merb-gen/helpers"
require "merb-gen/base"
class MerbGenerator < Merb::GeneratorBase
def initialize(args, runtime_options = {})
@base = File.dirname(__FILE__)
@name = args.first
super
@destination_root = @name
end
protected
def banner
<<-EOS.split("\n").map{|x| x.strip}.join("\n")
Creates a Merb application stub.
USAGE: #{spec.name} -g path
Set environment variable MERB_ORM=[activerecord|datamapper|sequel]
to pre-enabled an ORM.
EOS
end
def default_orm?(orm)
ENV['MERB_ORM'] == orm.to_s
end
def default_test_suite?(suite)
return ENV['MERB_TEST_SUITE'] == suite.to_s if ENV['MERB_TEST_SUITE']
options[suite]
end
def display_framework_selections
end
def create_dirs
m.directory 'log'
m.directory 'gems'
end
end
|
Use symbols for payment decorator states | module Spree
Payment.class_eval do
state_machine :initial => 'checkout' do
after_transition :to => 'completed', :do => :create_subscriptions!
end
def create_subscriptions!
self.order.create_subscriptions
end
end
end | module Spree
Payment.class_eval do
state_machine :initial => :checkout do
after_transition :to => :completed, :do => :create_subscriptions!
end
def create_subscriptions!
self.order.create_subscriptions
end
end
end |
Add primary key `id` to `category_featured_topics` and `topic_users` | class AddMissingIdColumns < ActiveRecord::Migration
def up
add_column :category_featured_topics, :id, :primary_key
add_column :topic_users, :id, :primary_key
end
def down
remove_column :category_featured_topics, :id
remove_column :topic_users, :id
end
end | |
Add last name to users | require 'carto/db/migration_helper'
include Carto::Db::MigrationHelper
migration(
Proc.new do
add_column :users, :last_name, :text
end,
Proc.new do
drop_column :users, :last_name
end
)
| |
Fix a silly bug (Thanks mat813) | module TravisSwicegoodGenerators
class MonthlyArchivePage < BaseArchivePage
attr_accessor :posts
def layout_err_msg
"
Hold your horses! monthly_archive_generator plugin, here.
You've enabled me but haven't added a monthly_archive layout.
At least put an empty file there or I'm not going to run.
Missing file:
%s/%s.html
" % ["_layouts", @layout]
end
def initialize(site, year, month, posts)
@year = year
@month = month
@url = "/%04d/%02d/" % [@year, @month]
super(site, posts)
end
def data
super.deep_merge({
"year" => @year,
"month" => @month,
})
end
end
class MonthlyArchiveGenerator < Jekyll::Generator
include ArchiveGenerator
def add_to_bucket(post)
@bucket[post.date.year] ||= default_bucket
@bucket[post.date.year][post.date.month] ||= default_bucket
@bucket[post.date.year][post.date.month][:posts] << post
end
def process
@bucket.each_pair do |year, months|
months[:subs].each_pair do |month, data|
posts = data[:posts]
posts.sort! { |a,b| b.date <=> a.date }
@site.pages << MonthlyArchivePage.new(@site, year, month, posts)
end
end
end
end
end
| module TravisSwicegoodGenerators
class MonthlyArchivePage < BaseArchivePage
attr_accessor :posts
def layout_err_msg
"
Hold your horses! monthly_archive_generator plugin, here.
You've enabled me but haven't added a monthly_archive layout.
At least put an empty file there or I'm not going to run.
Missing file:
%s/%s.html
" % ["_layouts", @layout]
end
def initialize(site, year, month, posts)
@year = year
@month = month
@url = "/%04d/%02d/" % [@year, @month]
super(site, posts)
end
def data
super.deep_merge({
"year" => @year,
"month" => @month,
})
end
end
class MonthlyArchiveGenerator < Jekyll::Generator
include ArchiveGenerator
def add_to_bucket(post)
@bucket[post.date.year] ||= default_bucket
@bucket[post.date.year][:subs][post.date.month] ||= default_bucket
@bucket[post.date.year][:subs][post.date.month][:posts] << post
end
def process
@bucket.each_pair do |year, months|
months[:subs].each_pair do |month, data|
posts = data[:posts]
posts.sort! { |a,b| b.date <=> a.date }
@site.pages << MonthlyArchivePage.new(@site, year, month, posts)
end
end
end
end
end
|
Comment on cache TTL for Whitehall responses | require 'gds_api/organisations'
module Transition
module Import
class WhitehallOrgs
##
# Place to put complete cached copy of orgs API
def cached_org_path
"/tmp/all_whitehall_orgs-#{DateTime.now.strftime('%Y-%m-%d')}.yaml"
end
def organisations
@organisations ||= begin
return YAML.load(File.read(cached_org_path)) if File.exist?(cached_org_path)
api = GdsApi::Organisations.new(Plek.current.find('whitehall-admin'))
api.organisations.with_subsequent_pages.to_a.tap do |orgs|
File.open(cached_org_path, 'w') { |f| f.write(YAML.dump(orgs)) }
end
end
end
def each
organisations.each
end
def by_title
@organisations_hash ||= organisations.inject({}) do |hash, org|
hash[org.title] = org
hash
end
end
end
end
end
| require 'gds_api/organisations'
module Transition
module Import
class WhitehallOrgs
##
# Place to put complete cached copy of orgs API.
# Cache expires when the date changes, so could be valid
# for up to 24 hours.
def cached_org_path
"/tmp/all_whitehall_orgs-#{DateTime.now.strftime('%Y-%m-%d')}.yaml"
end
def organisations
@organisations ||= begin
return YAML.load(File.read(cached_org_path)) if File.exist?(cached_org_path)
api = GdsApi::Organisations.new(Plek.current.find('whitehall-admin'))
api.organisations.with_subsequent_pages.to_a.tap do |orgs|
File.open(cached_org_path, 'w') { |f| f.write(YAML.dump(orgs)) }
end
end
end
def each
organisations.each
end
def by_title
@organisations_hash ||= organisations.inject({}) do |hash, org|
hash[org.title] = org
hash
end
end
end
end
end
|
Handle lifecycle events without an organization | class LifecyclePresenter
attr_reader :subject
def initialize(subject)
@subject = subject
end
def as_json(opts = {})
subject.lifecycle_events.each_with_object({}) do |(event_name, relation_name), h|
if event = subject.send(relation_name)
user = if event.respond_to?(:originating_user)
event.originating_user
else
event.user
end
h[event_name] = {
timestamp: event.created_at,
user: UserPresenter.new(user),
organization: OrganizationIndexPresenter.new(event.organization),
}
end
end
end
end
| class LifecyclePresenter
attr_reader :subject
def initialize(subject)
@subject = subject
end
def as_json(opts = {})
subject.lifecycle_events.each_with_object({}) do |(event_name, relation_name), h|
if event = subject.send(relation_name)
user = if event.respond_to?(:originating_user)
event.originating_user
else
event.user
end
organization = if event.organization.nil?
{}
else
OrganizationIndexPresenter.new(event.organization)
end
h[event_name] = {
timestamp: event.created_at,
user: UserPresenter.new(user),
organization: organization,
}
end
end
end
end
|
Add parens round stuff, clean up comments | require_relative 'hangman'
require_relative 'wordlist'
require_relative 'consolePresenter'
Dir[File.dirname(__FILE__) + "/errors/*.rb"].each {|file| require_relative file }
class Game
def initialize()
# TODO get a word based on language
word = Wordlist.new.get_word
@hangman = Hangman.new( {:word => word} )
@presenter = ConsolePresenter.new
end
def run()
until @hangman.finished?
guess = get_guess
break unless guess
@hangman.guess guess
end
# Clear screen, print final gamestate
@presenter.display_game @hangman
end
def get_guess()
# Loop until @hangman.won or @hangman.lost
begin
# Display game
@presenter.display_game @hangman
# Read input
@presenter.display_error @error
guess = @presenter.ask_for_letter
# Validate input
if guess == "\u0003" # ctrl-c, SIGINT
raise Interrupt
end
if guess == "\u0004" # ctrl-d, EOF
# @hangman.lost
return
end
end while @error = validate(guess)
guess
end
def validate(guess)
begin
@hangman.validate_letter guess
rescue NotLowerCaseLetterError
:inputisnotlowercase
rescue AlreadyGuessedError
:inputhasalreadybeenguessed
rescue ValidateError
:inputisinvalid
end
end
end
| require_relative 'hangman'
require_relative 'wordlist'
require_relative 'consolePresenter'
Dir[File.dirname(__FILE__) + "/errors/*.rb"].each {|file| require_relative file }
class Game
def initialize()
# TODO get a word based on language
word = Wordlist.new.get_word
@hangman = Hangman.new( {:word => word} )
@presenter = ConsolePresenter.new
end
def run()
# Loop until @hangman.won or @hangman.lost, guessing, or potentially quitting
until @hangman.finished?
guess = get_guess
break unless guess
@hangman.guess(guess)
end
# Clear screen, print final gamestate
@presenter.display_game(@hangman)
end
def get_guess()
begin
# Display game
@presenter.display_game(@hangman)
# Read input
@presenter.display_error(@error)
guess = @presenter.ask_for_letter
# Validate input
if guess == "\u0003" # ctrl-c, SIGINT
raise Interrupt
end
if guess == "\u0004" # ctrl-d, EOF
# Quit the game
return
end
end while @error = validate(guess)
guess
end
def validate(guess)
begin
@hangman.validate_letter(guess)
rescue NotLowerCaseLetterError
:inputisnotlowercase
rescue AlreadyGuessedError
:inputhasalreadybeenguessed
rescue ValidateError
:inputisinvalid
end
end
end
|
Add version info to test_launcher | require "optparse"
# This could use some love
class InputParser
ParseError = Class.new(RuntimeError)
BANNER = <<-DESC
Find tests and run them by trying to match an individual test or the name of a test file(s).
See full README: https://github.com/petekinnecom/test_launcher
Usage: `test_launcher "search string" [--all]`
DESC
def initialize(args)
@query = args
@options = {}
option_parser.parse!(args)
rescue OptionParser::ParseError
puts "Invalid arguments"
puts "----"
puts option_parser
exit
end
def query
if @query.size == 0
puts option_parser
exit
elsif @query.size > 1
puts "Concatenating args to single string. (see https://github.com/petekinnecom/test_launcher)"
end
@query.join(" ")
end
def options
@options
end
private
def option_parser
OptionParser.new do |opts|
opts.banner = BANNER
opts.on("-a", "--all", "Run all matching tests. Defaults to false.") do
options[:run_all] = true
end
opts.on("-h", "--help", "Prints this help") do
puts opts
exit
end
opts.on("-f", "--framework framework", "The testing framework being used. Valid options: ['minitest', 'rspec', 'guess']. Defaults to 'guess'") do |framework|
options[:framework] = framework
end
end
end
end
| require "test_launcher/version"
require "optparse"
# This could use some love
class InputParser
ParseError = Class.new(RuntimeError)
BANNER = <<-DESC
Find tests and run them by trying to match an individual test or the name of a test file(s).
See full README: https://github.com/petekinnecom/test_launcher
Usage: `test_launcher "search string" [--all]`
VERSION: #{TestLauncher::VERSION}
DESC
def initialize(args)
@query = args
@options = {}
option_parser.parse!(args)
rescue OptionParser::ParseError
puts "Invalid arguments"
puts "----"
puts option_parser
exit
end
def query
if @query.size == 0
puts option_parser
exit
elsif @query.size > 1
puts "Concatenating args to single string. (see https://github.com/petekinnecom/test_launcher)"
end
@query.join(" ")
end
def options
@options
end
private
def option_parser
OptionParser.new do |opts|
opts.banner = BANNER
opts.on("-a", "--all", "Run all matching tests. Defaults to false.") do
options[:run_all] = true
end
opts.on("-h", "--help", "Prints this help") do
puts opts
exit
end
opts.on("-v", "--version", "Display the version info") do
puts TestLauncher::VERSION
exit
end
opts.on("-f", "--framework framework", "The testing framework being used. Valid options: ['minitest', 'rspec', 'guess']. Defaults to 'guess'") do |framework|
options[:framework] = framework
end
end
end
end
|
Update input definitions to new simple_form specs |
class ImagePreviewInput < SimpleForm::Inputs::Base
def input
resize = options.delete(:size) || '350x100>'
size = resize.sub(/\D$/,'')
keys = options.delete(:attribute_keys)
name = attribute_name.to_s
attribute_keys = @builder.object.attributes.keys.inject([]) do |array, x|
n, a = x.split("_")
n == name && a.present? ? array << a : array
end
template.render("simple_dragonfly_preview/image/form",
f: @builder,
attribute_name: name,
retained_id: (@builder.lookup_model_names + ["retained", name]).join("_"),
image_id: (@builder.lookup_model_names + [name, "preview"]).join("_"),
size: size,
resize: resize,
attribute_keys: attribute_keys.join(","))
end
end
|
class ImagePreviewInput < SimpleForm::Inputs::Base
def input(wrapper_options = nil)
resize = options.delete(:size) || '350x100>'
size = resize.sub(/\D$/,'')
keys = options.delete(:attribute_keys)
name = attribute_name.to_s
attribute_keys = @builder.object.attributes.keys.inject([]) do |array, x|
n, a = x.split("_")
n == name && a.present? ? array << a : array
end
template.render("simple_dragonfly_preview/image/form",
f: @builder,
attribute_name: name,
retained_id: (@builder.lookup_model_names + ["retained", name]).join("_"),
image_id: (@builder.lookup_model_names + [name, "preview"]).join("_"),
size: size,
resize: resize,
attribute_keys: attribute_keys.join(","))
end
end
|
Add functional test for shell_out_with_systems_locale | #
# Copyright:: Copyright (c) 2014 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::Mixin::ShellOut do
include Chef::Mixin::ShellOut
describe "shell_out_with_systems_locale" do
describe "when environment['LC_ALL'] is not set" do
it "should use the default shell_out setting" do
cmd = if windows?
shell_out_with_systems_locale('echo %LC_ALL%')
else
shell_out_with_systems_locale('echo $LC_ALL')
end
# From mixlib-shellout/lib/mixlib/shell_out.rb:
#
# * +environment+: a Hash of environment variables to set before the command
# is run. By default, the environment will *always* be set to 'LC_ALL' => 'C'
# to prevent issues with multibyte characters in Ruby 1.8. To avoid this,
# use :environment => nil for *no* extra environment settings, or
# :environment => {'LC_ALL'=>nil, ...} to set other environment settings
# without changing the locale.
cmd.stdout.chomp.should eq 'C'
end
end
describe "when environment['LC_ALL'] is set" do
it "should use the option's setting" do
cmd = if windows?
shell_out_with_systems_locale('echo %LC_ALL%', :environment => {'LC_ALL' => 'POSIX'})
else
shell_out_with_systems_locale('echo $LC_ALL', :environment => {'LC_ALL' => 'POSIX'})
end
cmd.stdout.chomp.should eq 'POSIX'
end
end
end
end
| |
Add missing require for pip package | # frozen_string_literal: true
module LicenseFinder
class PipPackage < Package
LICENSE_FORMAT = /^License.*::\s*(.*)$/
INVALID_LICENSES = ['', 'UNKNOWN'].to_set
def self.license_names_from_spec(spec)
license = spec['license'].to_s.strip
return [license] unless INVALID_LICENSES.include?(license)
spec
.fetch('classifiers', [])
.select { |c| c =~ LICENSE_FORMAT }
.map { |c| c.gsub(LICENSE_FORMAT, '\1') }
end
def initialize(name, version, spec, options = {})
super(
name,
version,
options.merge(
authors: spec['author'],
summary: spec['summary'],
description: spec['description'],
homepage: spec['home_page'],
spec_licenses: self.class.license_names_from_spec(spec)
)
)
end
def package_manager
'Pip'
end
end
end
| # frozen_string_literal: true
require 'set'
module LicenseFinder
class PipPackage < Package
LICENSE_FORMAT = /^License.*::\s*(.*)$/
INVALID_LICENSES = ['', 'UNKNOWN'].to_set
def self.license_names_from_spec(spec)
license = spec['license'].to_s.strip
return [license] unless INVALID_LICENSES.include?(license)
spec
.fetch('classifiers', [])
.select { |c| c =~ LICENSE_FORMAT }
.map { |c| c.gsub(LICENSE_FORMAT, '\1') }
end
def initialize(name, version, spec, options = {})
super(
name,
version,
options.merge(
authors: spec['author'],
summary: spec['summary'],
description: spec['description'],
homepage: spec['home_page'],
spec_licenses: self.class.license_names_from_spec(spec)
)
)
end
def package_manager
'Pip'
end
end
end
|
Remove the fetch in job builder | module FullCircle
class Builders::JobBuilder
def self.build(hash)
job = Job.new(
id: hash.fetch("id"),
title: hash.fetch("title"),
job_field: hash['jobField'],
education_requirement: hash['educationRequirement'],
company_name: hash['companyName'],
company_addr1: hash['companyAddr1'],
company_city: hash['companyCity'],
company_state: hash['companyState'],
accept_print: hash['acceptPrint'],
company_zip: hash.fetch('companyZip'),
salary: hash['salary'],
hours_type: hash['hoursType'],
display_start: hash['displayStart'],
display_end: hash['displayEnd'],
description: hash['description'],
contact_name: hash['contactName'],
contact_email: hash['contactEmail'],
contact_phone: hash['contactPhone'],
contact_fax: hash['contactFax'],
url: hash['url']
)
end
end
end
| module FullCircle
class Builders::JobBuilder
def self.build(hash)
job = Job.new(
id: hash.fetch("id"),
title: hash.fetch("title"),
job_field: hash['jobField'],
education_requirement: hash['educationRequirement'],
company_name: hash['companyName'],
company_addr1: hash['companyAddr1'],
company_city: hash['companyCity'],
company_state: hash['companyState'],
accept_print: hash['acceptPrint'],
company_zip: hash['companyZip'],
salary: hash['salary'],
hours_type: hash['hoursType'],
display_start: hash['displayStart'],
display_end: hash['displayEnd'],
description: hash['description'],
contact_name: hash['contactName'],
contact_email: hash['contactEmail'],
contact_phone: hash['contactPhone'],
contact_fax: hash['contactFax'],
url: hash['url']
)
end
end
end
|
Change in ruby_application block (database) -> strings instead of attributes | user_account node['rails_app']['name'] do
action :create
end
package 'git' do
action :install
end
#it helps with debugging
#NOTE add tmux config with key set to C-A
package 'tmux' do
action :install
end
#Fix Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable) on Debian - starting rails app
package 'libv8-dev' do
action :install
end
#Install development headers for mysql required by mysql2 gem
package 'libmysqlclient-dev' do
action :install
end
application node['rails_app']['name'] do
owner node['rails_app']['name']
group node['rails_app']['name']
path node['rails_app']['application_path']
repository node['rails_app']['git_repository']
revision 'master'
rails do
database do
database node['rails_app']['database_name']
username node['rails_app']['name']
password node['rails_app']['database_password']
end
end
end
| user_account node['rails_app']['name'] do
action :create
end
package 'git' do
action :install
end
#it helps with debugging
#NOTE add tmux config with key set to C-A
package 'tmux' do
action :install
end
#Fix Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable) on Debian - starting rails app
package 'libv8-dev' do
action :install
end
#Install development headers for mysql required by mysql2 gem
package 'libmysqlclient-dev' do
action :install
end
application node['rails_app']['name'] do
owner node['rails_app']['name']
group node['rails_app']['name']
path node['rails_app']['application_path']
repository node['rails_app']['git_repository']
revision 'master'
rails do
#NOTE it should take attributes, not hardcoded strings
database do
database 'rails_app'
username 'rails_app'
password '12*!asBUApg#'
end
end
end
|
Use encoded version of customer_id for subscriptions | require 'open-uri'
module Mollie
module API
module Resource
class Customers
class Subscriptions < Base
@parent_id = nil
def getResourceObject
Mollie::API::Object::Subscription
end
def getResourceName
customer_id = URI::encode(@parent_id)
"customers/#{@parent_id}/subscriptions"
end
def with(customer)
@parent_id = customer.id
self
end
end
end
end
end
end
| require 'open-uri'
module Mollie
module API
module Resource
class Customers
class Subscriptions < Base
@parent_id = nil
def getResourceObject
Mollie::API::Object::Subscription
end
def getResourceName
customer_id = URI::encode(@parent_id)
"customers/#{customer_id}/subscriptions"
end
def with(customer)
@parent_id = customer.id
self
end
end
end
end
end
end
|
Fix themes breaking rake db:setup because RefinerySetting.table_exists? is false. | # Set up middleware to serve theme files
config.middleware.use "ThemeServer"
# Add or remove theme paths to/from Refinery application
::Refinery::ApplicationController.module_eval do
before_filter do |controller|
controller.view_paths.reject! { |v| v.to_s =~ %r{^themes/} }
if (theme = RefinerySetting[:theme]).present?
# Set up view path again for the current theme.
controller.view_paths.unshift Rails.root.join("themes", theme, "views").to_s
RefinerySetting[:refinery_menu_cache_action_suffix] = "#{theme}_site_menu"
else
# Set the cache key for the site menu (thus expiring the fragment cache if theme changes).
RefinerySetting[:refinery_menu_cache_action_suffix] = "site_menu"
end
end
end
if (theme = RefinerySetting[:theme]).present?
# Set up controller paths, which can only be brought in with a server restart, sorry. (But for good reason)
controller_path = Rails.root.join("themes", theme, "controllers").to_s
::ActiveSupport::Dependencies.load_paths.unshift controller_path
config.controller_paths.unshift controller_path
end
# Include theme functions into application helper.
Refinery::ApplicationHelper.send :include, ThemesHelper
| # Before the application gets setup this will fail badly if there's no database.
if RefinerySetting.table_exists?
# Set up middleware to serve theme files
config.middleware.use "ThemeServer"
# Add or remove theme paths to/from Refinery application
::Refinery::ApplicationController.module_eval do
before_filter do |controller|
controller.view_paths.reject! { |v| v.to_s =~ %r{^themes/} }
if (theme = RefinerySetting[:theme]).present?
# Set up view path again for the current theme.
controller.view_paths.unshift Rails.root.join("themes", theme, "views").to_s
RefinerySetting[:refinery_menu_cache_action_suffix] = "#{theme}_site_menu"
else
# Set the cache key for the site menu (thus expiring the fragment cache if theme changes).
RefinerySetting[:refinery_menu_cache_action_suffix] = "site_menu"
end
end
end
if (theme = RefinerySetting[:theme]).present?
# Set up controller paths, which can only be brought in with a server restart, sorry. (But for good reason)
controller_path = Rails.root.join("themes", theme, "controllers").to_s
::ActiveSupport::Dependencies.load_paths.unshift controller_path
config.controller_paths.unshift controller_path
end
# Include theme functions into application helper.
Refinery::ApplicationHelper.send :include, ThemesHelper
end
|
Remove tasks which require attributes when initialized | class Journal < ActiveRecord::Base
VALID_TASK_TYPES = ["ReviewerReportTask",
"PaperAdminTask",
"MessageTask",
"StandardTasks::TechCheckTask",
"StandardTasks::FigureTask",
"UploadManuscriptTask",
"PaperEditorTask",
"FigureTask",
"DeclarationTask",
"Task",
"PaperReviewerTask",
"RegisterDecisionTask",
"StandardTasks::AuthorsTask"]
has_many :papers, inverse_of: :journal
has_many :journal_roles, inverse_of: :journal
has_many :users, through: :journal_roles
has_many :manuscript_manager_templates
def admins
users.merge(JournalRole.admins)
end
def editors
users.merge(JournalRole.editors)
end
def reviewers
users.merge(JournalRole.reviewers)
end
def logo_url
logo.url if logo
end
def paper_types
self.manuscript_manager_templates.pluck(:paper_type)
end
def mmt_for_paper_type(paper_type)
manuscript_manager_templates.where(paper_type: paper_type).first
end
mount_uploader :logo, LogoUploader
end
| class Journal < ActiveRecord::Base
VALID_TASK_TYPES = ["ReviewerReportTask",
"PaperAdminTask",
"UploadManuscriptTask",
"PaperEditorTask",
"DeclarationTask",
"PaperReviewerTask",
"RegisterDecisionTask",
"StandardTasks::TechCheckTask",
"StandardTasks::FigureTask",
"StandardTasks::AuthorsTask"]
has_many :papers, inverse_of: :journal
has_many :journal_roles, inverse_of: :journal
has_many :users, through: :journal_roles
has_many :manuscript_manager_templates
def admins
users.merge(JournalRole.admins)
end
def editors
users.merge(JournalRole.editors)
end
def reviewers
users.merge(JournalRole.reviewers)
end
def logo_url
logo.url if logo
end
def paper_types
self.manuscript_manager_templates.pluck(:paper_type)
end
def mmt_for_paper_type(paper_type)
manuscript_manager_templates.where(paper_type: paper_type).first
end
mount_uploader :logo, LogoUploader
end
|
Add development dependency on activesupport (>= 3.1) | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'unchanged_validator/version'
Gem::Specification.new do |spec|
spec.name = "unchanged_validator"
spec.version = UnchangedValidator::VERSION
spec.authors = ["Peter Marsh"]
spec.email = ["pete.d.marsh@gmail.com"]
spec.summary = %q{TODO: Write a short summary. Required.}
spec.description = %q{TODO: Write a longer description. Optional.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "activemodel", ">= 3.1"
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake", "~> 10.0"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'unchanged_validator/version'
Gem::Specification.new do |spec|
spec.name = "unchanged_validator"
spec.version = UnchangedValidator::VERSION
spec.authors = ["Peter Marsh"]
spec.email = ["pete.d.marsh@gmail.com"]
spec.summary = %q{TODO: Write a short summary. Required.}
spec.description = %q{TODO: Write a longer description. Optional.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "activemodel", ">= 3.1"
spec.add_development_dependency "activesupport", ">= 3.1"
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake", "~> 10.0"
end
|
Fix broken net checker spec | require "spec_helper"
describe NameChecker::NetChecker do
subject { NameChecker::NetChecker }
describe "check" do
let(:host_name) { "apple" }
let(:tld) { ".com" }
# NOTE: This test assumes there is a ROBO_WHOIS_API_KEY
# set in spec/shec_helper.rb
it "should hit the RoboWhoisChecker if there is an api key" do
NameChecker::RoboWhoisChecker.should_receive(:check)
.with(host_name + tld)
subject.check(host_name, tld)
end
it "should hit the WhoisChecker if there is no api key" do
NameChecker.configuration.stub(:robo_whois_api_key) { nil }
NameChecker::WhoisChecker.should_receive(:check)
.with(host_name + tld)
subject.check(host_name, tld)
end
end
end
| require "spec_helper"
describe NameChecker::NetChecker do
subject { NameChecker::NetChecker }
describe "check" do
let(:host_name) { "apple" }
let(:tld) { ".com" }
it "should hit the RoboWhoisChecker if there is an api key" do
NameChecker.configuration.stub(:robo_whois_api_key) { "123" }
NameChecker::RoboWhoisChecker.should_receive(:check)
.with(host_name + tld)
subject.check(host_name, tld)
end
it "should hit the WhoisChecker if there is no api key" do
NameChecker.configuration.stub(:robo_whois_api_key) { nil }
NameChecker::WhoisChecker.should_receive(:check)
.with(host_name + tld)
subject.check(host_name, tld)
end
end
end
|
Allow ['~> 3.0', '>= 3.0.0'] for refinerycms-core | # Encoding: UTF-8
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'refinerycms-retailers'
s.version = '3.0.0'
s.description = 'Ruby on Rails Retailers extension for Refinery CMS'
s.date = '2014-10-22'
s.summary = 'Retailers extension for Refinery CMS'
s.email = %q{info@bisscomm.com}
s.homepage = %q{http://www.bisscomm.com}
s.authors = ['Brice Sanchez']
s.license = %q{MIT}
s.require_paths = %w(lib)
s.files = Dir["{app,config,db,lib}/**/*"] + ["readme.md"]
# Runtime dependencies
s.add_dependency 'refinerycms-core', '~> 3.0.0'
s.add_dependency 'globalize', ['>= 4.0.0', '< 5.2']
s.add_dependency 'acts_as_indexed', '~> 0.8.0'
s.add_dependency 'carmen-rails', '~> 1.0.1'
s.add_dependency 'actionview-encoded_mail_to', '~> 1.0.5'
# Development dependencies (usually used for testing)
s.add_development_dependency 'refinerycms-testing', '~> 3.0.0'
end
| # Encoding: UTF-8
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'refinerycms-retailers'
s.version = '3.0.0'
s.description = 'Ruby on Rails Retailers extension for Refinery CMS'
s.date = '2014-10-22'
s.summary = 'Retailers extension for Refinery CMS'
s.email = %q{info@bisscomm.com}
s.homepage = %q{http://www.bisscomm.com}
s.authors = ['Brice Sanchez']
s.license = %q{MIT}
s.require_paths = %w(lib)
s.files = Dir["{app,config,db,lib}/**/*"] + ["readme.md"]
# Runtime dependencies
s.add_dependency 'refinerycms-core', ['~> 3.0', '>= 3.0.0']
s.add_dependency 'globalize', ['>= 4.0.0', '< 5.2']
s.add_dependency 'acts_as_indexed', '~> 0.8.0'
s.add_dependency 'carmen-rails', '~> 1.0.1'
s.add_dependency 'actionview-encoded_mail_to', '~> 1.0.5'
end
|
Fix broken duration for backup log message. | module Frakup
class Backupset
include DataMapper::Resource
property :id,
Serial
property :created_at,
DateTime
property :updated_at,
DateTime
has n, :backupelements
has n, :fileobjects, :through => :backupelements
property :started_at,
DateTime
property :finished_at,
DateTime
def self.backup(source, target)
$log.info "Backup started"
$log.info " - source: #{source}"
$log.info " - target: #{target}"
backupset = Backupset.create(
:started_at => Time.now
)
$log.info " Created Backupset ##{backupset.id}"
Pathname.glob(File.join(source, "**", "*")).each do |f|
Backupelement.store(backupset, f)
end
backupset.finished_at = Time.now
backupset.save
$log.info " Backup finished"
$log.info " - duration: #{Time.at(backupset.finished_at - backupset.started_at).gmtime.strftime('%R:%S')}"
$log.info " - backupelements: #{backupset.backupelements.count}"
$log.info " - fileobjects: #{backupset.fileobjects.count}"
$log.info " - size: #{Frakup::Helper.human_size(backupset.fileobjects.sum(:size))}"
end
end
end
| module Frakup
class Backupset
include DataMapper::Resource
property :id,
Serial
property :created_at,
DateTime
property :updated_at,
DateTime
has n, :backupelements
has n, :fileobjects, :through => :backupelements
property :started_at,
DateTime
property :finished_at,
DateTime
def self.backup(source, target)
$log.info "Backup started"
$log.info " - source: #{source}"
$log.info " - target: #{target}"
backupset = Backupset.create(
:started_at => Time.now
)
$log.info " Created Backupset ##{backupset.id}"
Pathname.glob(File.join(source, "**", "*")).each do |f|
Backupelement.store(backupset, f)
end
backupset.finished_at = Time.now
backupset.save
$log.info " Backup finished"
$log.info " - duration: #{Time.at(backupset.finished_at.to_time - backupset.started_at.to_time).gmtime.strftime('%R:%S')}"
$log.info " - backupelements: #{backupset.backupelements.count}"
$log.info " - fileobjects: #{backupset.fileobjects.count}"
$log.info " - size: #{Frakup::Helper.human_size(backupset.fileobjects.sum(:size))}"
end
end
end
|
Allow the ReportPresenter to print the ownership based on changes | module GitEvolution
class ReportPresenter
def initialize(commits)
@commits = commits
@ownership = Hash.new(0)
end
def print
print_commits
puts '-' * 80
puts
print_ownership
end
def print_commits
puts 'Commits:'
@commits.each do |commit|
puts "#{commit.author} (#{Time.at(commit.date.to_i)}) - #{commit.sha}"
puts "#{commit.title}"
puts
@ownership[commit.author] = @ownership[commit.author] + 1
end
end
def print_ownership
puts 'Ownership:'
@ownership.each do |author, count|
puts "#{author} - #{count}/#{@commits.size} (#{(count.to_f / @commits.size * 100).round(2)}%)"
end
end
end
end
| module GitEvolution
class ReportPresenter
def initialize(commits)
@commits = commits
@ownership = { commits: Hash.new(0), changes: Hash.new(0) }
end
def print
print_commits
puts
puts '-' * 80
puts
print_commit_ownership
puts
print_changes_ownership
puts
end
def print_commits
puts 'Commits:'
@commits.each do |commit|
puts "#{commit.author} (#{commit.date}) - #{commit.sha}"
puts "#{commit.subject}"
puts
@ownership[:commits][commit.author] = @ownership[:commits][commit.author] + 1
@ownership[:changes][commit.author] = @ownership[:changes][commit.author] + commit.additions + commit.deletions
end
end
def print_commit_ownership
puts 'Ownership (Commits):'
@ownership[:commits].each do |author, count|
puts "#{author} - #{count}/#{@commits.size} (#{(count.to_f / @commits.size * 100).round(2)}%)"
end
end
def print_changes_ownership
puts 'Ownership (Changes):'
total_additions = @commits.inject(0) { |sum, commit| sum + commit.additions }
total_deletions = @commits.inject(0) { |sum, commit| sum + commit.deletions }
total_changes = total_additions + total_deletions
@ownership[:changes].each do |author, count|
puts "#{author} - #{count}/#{total_changes} (#{(count.to_f / total_changes * 100).round(2)}%)"
end
end
end
end
|
Configure webkit only a single time | # frozen_string_literal: true
require 'proxy_rb/drivers/basic_driver'
begin
require 'capybara/webkit'
rescue LoadError
ProxyRb.logger.error %(Error loading `capybara-webkit`-gem. Please add `gem capybara-webkit` to your `Gemfile`)
exit 1
end
# ProxyRb
module ProxyRb
# Drivers
module Drivers
# Driver for Capybara-Webkit
class WebkitDriver < BasicDriver
# Configure driver
def configure_driver
# rubocop:disable Style/SymbolProc
::Capybara::Webkit.configure do |config|
config.allow_unknown_urls
end
# rubocop:enable Style/SymbolProc
super
end
# Register proxy
#
# @param [HttpProxy] proxy
# The HTTP proxy which should be used for fetching content
def register(proxy)
if proxy.empty?
::Capybara.current_driver = :webkit
return
end
options = {
proxy: {
host: proxy.host,
port: proxy.port,
user: proxy.user,
pass: proxy.password
}
}
unless ::Capybara.drivers.key? proxy.to_ref
::Capybara.register_driver proxy.to_ref do |app|
::Capybara::Webkit::Driver.new(app, Capybara::Webkit::Configuration.to_hash.merge(options))
end
end
::Capybara.current_driver = proxy.to_ref
end
def rescuable_errors
[::Capybara::Webkit::TimeoutError]
end
end
end
end
| # frozen_string_literal: true
require 'proxy_rb/drivers/basic_driver'
begin
require 'capybara/webkit'
rescue LoadError
ProxyRb.logger.error %(Error loading `capybara-webkit`-gem. Please add `gem capybara-webkit` to your `Gemfile`)
exit 1
end
# rubocop:disable Style/SymbolProc
::Capybara::Webkit.configure do |config|
config.allow_unknown_urls
end
# rubocop:enable Style/SymbolProc
# ProxyRb
module ProxyRb
# Drivers
module Drivers
# Driver for Capybara-Webkit
class WebkitDriver < BasicDriver
# Register proxy
#
# @param [HttpProxy] proxy
# The HTTP proxy which should be used for fetching content
def register(proxy)
if proxy.empty?
::Capybara.current_driver = :webkit
return
end
options = {
proxy: {
host: proxy.host,
port: proxy.port,
user: proxy.user,
pass: proxy.password
}
}
unless ::Capybara.drivers.key? proxy.to_ref
::Capybara.register_driver proxy.to_ref do |app|
::Capybara::Webkit::Driver.new(app, Capybara::Webkit::Configuration.to_hash.merge(options))
end
end
::Capybara.current_driver = proxy.to_ref
end
def rescuable_errors
[::Capybara::Webkit::TimeoutError]
end
end
end
end
|
Use the NullLogger by default. | module Marples
module ModelActionBroadcast
TRANSACTION_ACTIONS = :create, :update, :destroy
CALLBACKS = TRANSACTION_ACTIONS + [:save, :commit]
def self.included base
base.class_eval do
# Something that response to #subscribe and #publish - although we
# only use #publish in this mixin.
class_attribute :marples_transport
# You *will* need to set this yourself in each application.
class_attribute :marples_client_name
# If you'd like the actions performed by Marples to be logged, set a
# logger. By default this uses the NullLogger.
class_attribute :marples_logger
self.marples_logger = Rails.logger
CALLBACKS.each do |callback|
callback_action = callback.to_s =~ /e$/ ? "#{callback}d" : "#{callback}ed"
after_callback = "after_#{callback}"
next unless respond_to? after_callback
notify = lambda { |record| record.class.marples_client.send callback_action, record }
if TRANSACTION_ACTIONS.include?(callback) && respond_to?(:after_commit)
after_commit :on => callback, ¬ify
else
send after_callback, ¬ify
end
end
def self.marples_client
@marples_client ||= build_marples_client
end
def self.build_marples_client
Marples::Client.new transport: marples_transport,
client_name: marples_client_name, logger: marples_logger
end
end
end
end
end
| module Marples
module ModelActionBroadcast
TRANSACTION_ACTIONS = :create, :update, :destroy
CALLBACKS = TRANSACTION_ACTIONS + [:save, :commit]
def self.included base
base.class_eval do
# Something that response to #subscribe and #publish - although we
# only use #publish in this mixin.
class_attribute :marples_transport
# You *will* need to set this yourself in each application.
class_attribute :marples_client_name
# If you'd like the actions performed by Marples to be logged, set a
# logger. By default this uses the NullLogger.
class_attribute :marples_logger
self.marples_logger = NullLogger.instance
CALLBACKS.each do |callback|
callback_action = callback.to_s =~ /e$/ ? "#{callback}d" : "#{callback}ed"
after_callback = "after_#{callback}"
next unless respond_to? after_callback
notify = lambda { |record| record.class.marples_client.send callback_action, record }
if TRANSACTION_ACTIONS.include?(callback) && respond_to?(:after_commit)
after_commit :on => callback, ¬ify
else
send after_callback, ¬ify
end
end
def self.marples_client
@marples_client ||= build_marples_client
end
def self.build_marples_client
Marples::Client.new transport: marples_transport,
client_name: marples_client_name, logger: marples_logger
end
end
end
end
end
|
Align columns in "summary" output. | module Swa
module EC2
class Instance
def initialize(aws_instance)
@aws_instance = aws_instance
end
def i
@aws_instance
end
def summary
summary_fields.map { |x| (x || "-") }.join(" ")
end
def summary_fields
name = tags["Name"]
[
i.instance_id,
i.image_id,
i.instance_type,
i.state.name,
(i.private_ip_address || "-"),
(%("#{name}") if name)
]
end
def data
{
"InstanceId" => i.instance_id,
"ImageId" => i.image_id,
"Tags" => tags,
"DATA" => i.data.to_h
}
end
def tags
i.tags.each_with_object({}) do |tag, result|
result[tag.key] = tag.value
end
end
end
end
end
| module Swa
module EC2
class Instance
def initialize(aws_instance)
@aws_instance = aws_instance
end
def i
@aws_instance
end
def summary
[
pad(i.instance_id, 11),
pad(i.image_id, 13),
pad(i.instance_type, 10),
pad(i.state.name, 11),
pad(i.private_ip_address, 15),
pad(i.public_ip_address, 15),
quoted_name
].join(" ")
end
def data
{
"InstanceId" => i.instance_id,
"ImageId" => i.image_id,
"Tags" => tags,
"DATA" => i.data.to_h
}
end
def tags
i.tags.each_with_object({}) do |tag, result|
result[tag.key] = tag.value
end
end
def name
tags["Name"]
end
def quoted_name
%("#{name}") if name
end
private
def pad(s, width)
s = (s || "").to_s
s.ljust(width)
end
end
end
end
|
Use comment subject in policy | class CommentPolicy < ApplicationPolicy
def new?
record.post.member?(user)
end
def create?
new?
end
def update?
author?
end
def edit?
author?
end
def destroy?
author?
end
private
def author?
record.author == user
end
end
| class CommentPolicy < ApplicationPolicy
def new?
record.subject.member?(user)
end
def create?
new?
end
def update?
author?
end
def edit?
author?
end
def destroy?
author?
end
private
def author?
record.author == user
end
end
|
Use correct SLA class name | require 'sidekiq'
require 'roo_on_rails/sidekiq/settings'
module RooOnRails
module Railties
class Sidekiq < Rails::Railtie
initializer 'roo_on_rails.sidekiq' do |app|
require 'hirefire-resource'
$stderr.puts 'initializer roo_on_rails.sidekiq'
break unless ENV.fetch('SIDEKIQ_ENABLED', 'true').to_s =~ /\A(YES|TRUE|ON|1)\Z/i
config_sidekiq
config_hirefire(app)
end
def config_hirefire(app)
unless ENV['HIREFIRE_TOKEN']
warn 'No HIREFIRE_TOKEN token set, auto scaling not enabled'
return
end
add_middleware(app)
end
def config_sidekiq
::Sidekiq.configure_server do |x|
x.options[:concurrency] = RooOnRails::Sidekiq::Settings.concurrency.to_i
x.options[:queues] = RooOnRails::Sidekiq::Settings.queues
end
end
def add_middleware(app)
$stderr.puts 'HIREFIRE_TOKEN set'
app.middleware.use HireFire::Middleware
HireFire::Resource.configure do |config|
config.dyno(:worker) do
RooOnRails::SidekiqSla.queue
end
end
end
end
end
end
| require 'sidekiq'
require 'roo_on_rails/sidekiq/settings'
require 'roo_on_rails/sidekiq/sla_metric'
module RooOnRails
module Railties
class Sidekiq < Rails::Railtie
initializer 'roo_on_rails.sidekiq' do |app|
require 'hirefire-resource'
$stderr.puts 'initializer roo_on_rails.sidekiq'
break unless ENV.fetch('SIDEKIQ_ENABLED', 'true').to_s =~ /\A(YES|TRUE|ON|1)\Z/i
config_sidekiq
config_hirefire(app)
end
def config_hirefire(app)
unless ENV['HIREFIRE_TOKEN']
warn 'No HIREFIRE_TOKEN token set, auto scaling not enabled'
return
end
add_middleware(app)
end
def config_sidekiq
::Sidekiq.configure_server do |x|
x.options[:concurrency] = RooOnRails::Sidekiq::Settings.concurrency.to_i
x.options[:queues] = RooOnRails::Sidekiq::Settings.queues
end
end
def add_middleware(app)
$stderr.puts 'HIREFIRE_TOKEN set'
app.middleware.use HireFire::Middleware
HireFire::Resource.configure do |config|
config.dyno(:worker) do
RooOnRails::Sidekiq::SlaMetric.queue
end
end
end
end
end
end
|
Enable tables and footnotes options in redcarpet | # If you want to add Redcarpet options, this is the file you need to use.
# Just follow the Redcarpet documentation and everything will be fine, or
# at least I hope so.
#
# Check the Redcarpet README for more information.
#
# https://github.com/vmg/redcarpet
#
require 'redcarpet'
Carpetbomb.configure do |config|
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML,
:autolink => true,
:space_after_headers => true,
:fenced_code_blocks => true)
config.render do |markdown_source|
markdown.render(markdown_source)
end
end
| # If you want to add Redcarpet options, this is the file you need to use.
# Just follow the Redcarpet documentation and everything will be fine, or
# at least I hope so.
#
# Check the Redcarpet README for more information.
#
# https://github.com/vmg/redcarpet
#
require 'redcarpet'
Carpetbomb.configure do |config|
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML,
:autolink => true,
:tables => true,
:footnotes => true,
:space_after_headers => true,
:fenced_code_blocks => true)
config.render do |markdown_source|
markdown.render(markdown_source)
end
end
|
Drop local dir before fetching local | #!/usr/bin/env ruby
# The git clone is a bit of a hack, but seems like the easiest solution to pulling in different projects
#
# Intentionally doing git clone and rake cruise in separate processes to ensure that all of the
# local overrides are loaded by Rake.
project_name = ARGV.first
case project_name
when "racing_on_rails"
exec "rake cruise"
when "aba", "atra", "obra", "wsba"
exec "git clone git@butlerpress.com:#{project_name}.git local && rake cruise"
else
raise "Don't know how to build project named: '#{project_name}'"
end
| #!/usr/bin/env ruby
# The git clone is a bit of a hack, but seems like the easiest solution to pulling in different projects
#
# Intentionally doing git clone and rake cruise in separate processes to ensure that all of the
# local overrides are loaded by Rake.
project_name = ARGV.first
case project_name
when "racing_on_rails"
exec "rake cruise"
when "aba", "atra", "obra", "wsba"
exec "rm -rf local && git clone git@butlerpress.com:#{project_name}.git local && rake cruise"
else
raise "Don't know how to build project named: '#{project_name}'"
end
|
Refactor object_key logic to a real plugin. This deprecates the unique_key mixin | #------------------------------------------------------------------------------
#
# TransamObjectKey
#
# Adds a unique object key to a model
#
#------------------------------------------------------------------------------
module TransamObjectKey
extend ActiveSupport::Concern
included do
# Always generate a unique object key before saving to the database
before_validation(:on => :create) do
generate_object_key(:object_key)
end
validates :object_key, :presence => true, :uniqueness => true, :length => { is: 12 }
end
def generate_object_key(column)
begin
self[column] = (Time.now.to_f * 10000000).to_i.to_s(24).upcase
end #while self.exists?(column => self[column])
end
def to_param
object_key
end
end
| |
Use ikgo/gocode for Go 1.11 modules | goget 'github.com/Ladicle/git-prompt'
goget 'github.com/ariarijp/crontoc'
goget 'github.com/atotto/clipboard/cmd/gocopy' do
binary_name 'gocopy'
end
goget 'github.com/atotto/clipboard/cmd/gopaste' do
binary_name 'gopaste'
end
goget 'github.com/mdempsky/gocode'
goget 'golang.org/x/lint/golint'
goget 'golang.org/x/tools/cmd/goimports'
| goget 'github.com/Ladicle/git-prompt'
goget 'github.com/ariarijp/crontoc'
goget 'github.com/atotto/clipboard/cmd/gocopy' do
binary_name 'gocopy'
end
goget 'github.com/atotto/clipboard/cmd/gopaste' do
binary_name 'gopaste'
end
# Workarond: github.com/mdempsky/gocode is not support Go 1.11 modules
goget 'github.com/ikgo/gocode'
goget 'golang.org/x/lint/golint'
goget 'golang.org/x/tools/cmd/goimports'
|
Change methods to class constants | class Complement
def self.of_dna(dna_str)
dna_str.gsub(/[#{dna_to_rna.keys.join}]/, dna_to_rna)
end
def self.of_rna(rna_str)
rna_str.gsub(/[#{rna_to_dna.keys.join}]/, rna_to_dna)
end
def self.dna_to_rna
{
'G' => 'C',
'C' => 'G',
'T' => 'A',
'A' => 'U'
}
end
def self.rna_to_dna
dna_to_rna.invert
end
end | class Complement
DNA_TO_RNA = {
'G' => 'C',
'C' => 'G',
'T' => 'A',
'A' => 'U'
}
RNA_TO_DNA = DNA_TO_RNA.invert
def self.of_dna(dna_str)
dna_str.gsub(/[#{DNA_TO_RNA.keys.join}]/, DNA_TO_RNA)
end
def self.of_rna(rna_str)
rna_str.gsub(/[#{RNA_TO_DNA.keys.join}]/, RNA_TO_DNA)
end
end |
Mark unimplemented spec as pending | require 'spec_helper'
describe 'Deleting Files', type: :feature do
let(:image) { File.open('spec/fixtures/image.png', 'r') }
let(:instance) { FeatureUploader.new }
before do
instance.aws_acl = 'public-read'
instance.store!(image)
end
it 'deletes the image when assigned a `nil` value' do
end
end
| require 'spec_helper'
describe 'Deleting Files', type: :feature do
let(:image) { File.open('spec/fixtures/image.png', 'r') }
let(:instance) { FeatureUploader.new }
before do
instance.aws_acl = 'public-read'
instance.store!(image)
end
it 'deletes the image when assigned a `nil` value'
end
|
Support RailsConfig objects for credentials | module MiqToolsServices
class Bugzilla
include ServiceMixin
class << self
attr_accessor :credentials
end
delegate :credentials, :to => self
def initialize
service # initialize the service
end
def service
@service ||= begin
require 'active_bugzilla'
bz = ActiveBugzilla::Service.new(*credentials.values_at("bugzilla_uri", "username", "password"))
ActiveBugzilla::Base.service = bz
end
end
def self.ids_in_git_commit_message(message)
ids = []
message.each_line.collect do |line|
match = %r{^\s*https://bugzilla\.redhat\.com//?show_bug\.cgi\?id=(?<bug_id>\d+)$}.match(line)
ids << match[:bug_id].to_i if match
end
ids
end
end
end
| module MiqToolsServices
class Bugzilla
include ServiceMixin
class << self
attr_accessor :credentials
end
delegate :credentials, :to => self
def initialize
service # initialize the service
end
def service
@service ||= begin
require 'active_bugzilla'
bz = ActiveBugzilla::Service.new(
credentials["bugzilla_uri"],
credentials["username"],
credentials["password"]
)
ActiveBugzilla::Base.service = bz
end
end
def self.ids_in_git_commit_message(message)
ids = []
message.each_line.collect do |line|
match = %r{^\s*https://bugzilla\.redhat\.com//?show_bug\.cgi\?id=(?<bug_id>\d+)$}.match(line)
ids << match[:bug_id].to_i if match
end
ids
end
end
end
|
Tweak bootstrap flash helper a bit to use danger instead of error alert class | # pinched from https://github.com/seyhunak/twitter-bootstrap-rails
module BootstrapFlashHelper
# extends ....................................................................
# includes ...................................................................
# constants ..................................................................
ALERT_TYPES = [:error, :info, :success, :warning] unless const_defined?(:ALERT_TYPES)
# additional config ..........................................................
# class methods ..............................................................
# helper methods .............................................................
def bootstrap_flash
flash_messages = []
flash.each do |type, message|
# Skip empty messages, e.g. for devise messages set to nothing in a locale file.
next if message.blank?
type = type.to_sym
type = :success if type == :notice
type = :error if type == :alert
next unless ALERT_TYPES.include?(type)
Array(message).each do |msg|
text = content_tag(:div,
content_tag(:button, raw("×"), :class => "close", "data-dismiss" => "alert") +
msg.html_safe, :class => "alert fade in alert-#{type}")
flash_messages << text if msg
end
end
flash_messages.join("\n").html_safe
end
# protected instance methods .................................................
# private instance methods ...................................................
end
| # pinched from https://github.com/seyhunak/twitter-bootstrap-rails
module BootstrapFlashHelper
# extends ....................................................................
# includes ...................................................................
# constants ..................................................................
ALERT_TYPES = [ :success, :info, :warning, :danger ] unless const_defined?(:ALERT_TYPES)
# additional config ..........................................................
# class methods ..............................................................
# helper methods .............................................................
def bootstrap_flash
flash_messages = []
flash.each do |type, message|
# Skip empty messages, e.g. for devise messages set to nothing in a locale file.
next if message.blank?
type = type.to_sym
type = :success if type == :notice
type = :danger if type == :alert
next unless ALERT_TYPES.include?(type)
Array(message).each do |msg|
text = content_tag(:div,
content_tag(:button, raw("×"), :class => "close", "data-dismiss" => "alert") +
msg.html_safe, :class => "alert fade in alert-#{type}")
flash_messages << text if msg
end
end
flash_messages.join("\n").html_safe
end
# protected instance methods .................................................
# private instance methods ...................................................
end
|
Add 'listen' to core dependencies. | require "spec_helper"
describe(GitHubPages::Dependencies) do
CORE_DEPENDENCIES = %w(
jekyll kramdown liquid rouge rdiscount redcarpet RedCloth
jekyll-sass-converter github-pages-health-check
).freeze
PLUGINS = described_class::VERSIONS.keys - CORE_DEPENDENCIES
it "exposes its gem versions" do
expect(described_class.gems).to be_a(Hash)
end
it "exposes relevant versions of dependencies, self and Ruby" do
expect(described_class.versions).to be_a(Hash)
expect(described_class.versions).to include("ruby")
expect(described_class.versions).to include("github-pages")
end
context "jekyll core dependencies" do
CORE_DEPENDENCIES.each do |gem|
it "exposes #{gem} dependency version" do
expect(described_class.gems[gem]).to be_a(String)
expect(described_class.gems[gem]).not_to be_empty
end
end
end
context "plugins" do
PLUGINS.each do |plugin|
it "whitelists the #{plugin} plugin" do
expect(GitHubPages::Configuration::PLUGIN_WHITELIST).to include(plugin)
end
end
end
it "exposes versions as Strings only" do
described_class.versions.values.each do |version|
expect(version).to be_a(String)
end
end
end
| require "spec_helper"
describe(GitHubPages::Dependencies) do
CORE_DEPENDENCIES = %w(
jekyll kramdown liquid rouge rdiscount redcarpet RedCloth
jekyll-sass-converter github-pages-health-check listen
).freeze
PLUGINS = described_class::VERSIONS.keys - CORE_DEPENDENCIES
it "exposes its gem versions" do
expect(described_class.gems).to be_a(Hash)
end
it "exposes relevant versions of dependencies, self and Ruby" do
expect(described_class.versions).to be_a(Hash)
expect(described_class.versions).to include("ruby")
expect(described_class.versions).to include("github-pages")
end
context "jekyll core dependencies" do
CORE_DEPENDENCIES.each do |gem|
it "exposes #{gem} dependency version" do
expect(described_class.gems[gem]).to be_a(String)
expect(described_class.gems[gem]).not_to be_empty
end
end
end
context "plugins" do
PLUGINS.each do |plugin|
it "whitelists the #{plugin} plugin" do
expect(GitHubPages::Configuration::PLUGIN_WHITELIST).to include(plugin)
end
end
end
it "exposes versions as Strings only" do
described_class.versions.values.each do |version|
expect(version).to be_a(String)
end
end
end
|
Add spec for ignoring encoding options in 1.8 | require File.expand_path('../../../spec_helper', __FILE__)
describe "File#initialize" do
it "needs to be reviewed for spec completeness"
end
ruby_version_is '1.9' do
describe "File#initialize" do
it 'accepts encoding options in mode parameter' do
io = File.new(__FILE__, 'r:UTF-8:iso-8859-1')
io.external_encoding.to_s.should == 'UTF-8'
io.internal_encoding.to_s.should == 'ISO-8859-1'
end
it 'accepts encoding options as a hash parameter' do
io = File.new(__FILE__, 'r', :encoding => 'UTF-8:iso-8859-1')
io.external_encoding.to_s.should == 'UTF-8'
io.internal_encoding.to_s.should == 'ISO-8859-1'
end
end
end
| require File.expand_path('../../../spec_helper', __FILE__)
describe "File#initialize" do
it "needs to be reviewed for spec completeness"
end
ruby_version_is '1.8' do
describe "File#initialize" do
it 'ignores encoding options in mode parameter' do
lambda { File.new(__FILE__, 'r:UTF-8:iso-8859-1') }.should_not raise_error
end
end
end
ruby_version_is '1.9' do
describe "File#initialize" do
it 'accepts encoding options in mode parameter' do
io = File.new(__FILE__, 'r:UTF-8:iso-8859-1')
io.external_encoding.to_s.should == 'UTF-8'
io.internal_encoding.to_s.should == 'ISO-8859-1'
end
it 'accepts encoding options as a hash parameter' do
io = File.new(__FILE__, 'r', :encoding => 'UTF-8:iso-8859-1')
io.external_encoding.to_s.should == 'UTF-8'
io.internal_encoding.to_s.should == 'ISO-8859-1'
end
end
end
|
Fix CSS selector for logging out in tests | require 'selenium-webdriver'
require 'yaml'
# Utility methods for tests
module EprSpecHelper
# @note
# I know, a singleton might be improper, but I didn't want tests to perform
# too many logins and logouts in case GitHub finds this activity
# suspicious.
#
# @return [Selenium::WebDriver::Driver]
# Chrome driver instance with the enhanced_pull_request extension loaded
def self.driver
@driver ||= Selenium::WebDriver.for(
:chrome, args: ["--load-extension=#{File.join(__dir__, '..')}"]
)
end
# Logs into GitHub.
def self.login
driver.get('https://github.com/login')
driver.find_element(:name, 'login').send_keys(config['login'])
password_field = EprSpecHelper.driver.find_element(:name, 'password')
password_field.send_keys(config['password'])
password_field.submit
end
# Logs out of GitHub.
#
# @note This assumes the driver is on a page with the avatar dropdown menu
def self.logout
avatar_icon = driver.find_element(:css, '.header-nav-link .avatar')
avatar_icon.location_once_scrolled_into_view
avatar_icon.click
driver.find_element(:class, 'logout-form').click
end
# @return [Hash{String => Object}] GitHub credentials for testing
def self.config
@config ||= YAML.load_file(File.join(__dir__, 'config.yml'))
end
end
| require 'selenium-webdriver'
require 'yaml'
# Utility methods for tests
module EprSpecHelper
# @note
# I know, a singleton might be improper, but I didn't want tests to perform
# too many logins and logouts in case GitHub finds this activity
# suspicious.
#
# @return [Selenium::WebDriver::Driver]
# Chrome driver instance with the enhanced_pull_request extension loaded
def self.driver
@driver ||= Selenium::WebDriver.for(
:chrome, args: ["--load-extension=#{File.join(__dir__, '..')}"]
)
end
# Logs into GitHub.
def self.login
driver.get('https://github.com/login')
driver.find_element(:name, 'login').send_keys(config['login'])
password_field = EprSpecHelper.driver.find_element(:name, 'password')
password_field.send_keys(config['password'])
password_field.submit
end
# Logs out of GitHub.
#
# @note This assumes the driver is on a page with the avatar dropdown menu
def self.logout
avatar_icon = driver.find_element(:css, '.HeaderNavlink .avatar')
avatar_icon.location_once_scrolled_into_view
avatar_icon.click
driver.find_element(:class, 'logout-form').click
end
# @return [Hash{String => Object}] GitHub credentials for testing
def self.config
@config ||= YAML.load_file(File.join(__dir__, 'config.yml'))
end
end
|
Add failing test for access control | require 'spec_helper'
RSpec.feature "Access control", type: :feature do
def log_in_as_editor(editor)
user = FactoryGirl.create(editor)
GDS::SSO.test_user = user
end
before do
fields = [
:base_path,
:content_id,
:title,
:public_updated_at,
:details,
:description,
]
publishing_api_has_fields_for_format('specialist_document', [], fields)
end
context "as a CMA Editor" do
before do
log_in_as_editor(:cma_editor)
end
scenario "visiting /cma-cases" do
visit "/cma-cases"
expect(page.status_code).to eq(200)
expect(page).to have_content("CMA Cases")
end
scenario "visiting /aaib-reports" do
visit "/aaib-reports"
expect(page.current_path).to eq("/cma-cases")
expect(page).to have_content("You aren't permitted to access AAIB Reports")
end
end
context "as an AAIB Editor" do
before do
log_in_as_editor(:aaib_editor)
end
scenario "visiting /aaib-reports" do
visit "/aaib-reports"
expect(page.status_code).to eq(200)
expect(page).to have_content("AAIB Reports")
end
scenario "visiting /cma-cases" do
visit "/cma-cases"
expect(page.current_path).to eq("/aaib-reports")
expect(page).to have_content("You aren't permitted to access CMA Cases")
end
end
end
| |
Update stats feature specs to run against sensu api v0.10.2 | require 'spec_helper'
describe "Stats" do
before :all do
load "#{Rails.root}/db/seeds.rb"
end
before :each do
user = FactoryGirl.create(:user)
user.add_role :admin
sign_in_user(user)
visit '/stats'
end
it "should show the stats page" do
page.should have_content "Stats"
end
it "should show clients by subscriptions" do
within("#clients-by-subscriptions") { find("td", :text => "test") }
end
it "should show clients by environment" do
within("#clients-by-environment") { find("td", :text => "None") }
end
it "should show miscellaneous client stats" do
within("#clients-misc tbody") do
find("td", :text => "Total Clients")
page.should have_content Client.all.count
end
end
it "should show events by check" do
within("#events-by-check") do
page.should have_content "test"
end
end
it "should show events by environment" do
within("#events-by-environment") do
page.should have_content "1"
end
end
it "should show events per client" do
within("#events-per-client") do
page.should have_content "i-424242"
end
end
it "should show miscellaneous event stats" do
within("#events-misc") do
page.should have_content "Total Events"
end
end
end
| |
Use a Set for simpler, more efficient lookups. | # encoding: utf-8
#
# Ruby implementation of the string similarity described by Simon White
# at: http://www.catalysoft.com/articles/StrikeAMatch.html
#
# Based on Java implementation of the article
#
# Author: Wilker Lúcio <wilkerlucio@gmail.com>
#
module Text
module SimonSimilarity
def compare_strings(str1, str2)
pairs1 = word_letter_pairs(str1.upcase)
pairs2 = word_letter_pairs(str2.upcase)
intersection = 0
union = pairs1.length + pairs2.length
pairs1.each do |pair1|
pairs2.each_with_index do |pair2, j|
if pair1 == pair2
intersection += 1
pairs2.delete_at(j)
break
end
end
end
(2.0 * intersection) / union
end
private
def word_letter_pairs(str)
str.split(/\s+/).map{ |word| letter_pairs(word) }.flatten(1)
end
def letter_pairs(str)
(0 ... (str.length - 1)).map { |i| str[i, 2] }
end
extend self
end
end
| # encoding: utf-8
#
# Ruby implementation of the string similarity described by Simon White
# at: http://www.catalysoft.com/articles/StrikeAMatch.html
#
# Based on Java implementation of the article
#
# Author: Wilker Lúcio <wilkerlucio@gmail.com>
#
require "set"
module Text
module SimonSimilarity
def compare_strings(str1, str2)
pairs1 = word_letter_pairs(str1.upcase)
pairs2 = word_letter_pairs(str2.upcase)
lookup = Set.new(pairs2)
intersection = 0
union = pairs1.length + pairs2.length
pairs1.each do |pair|
if lookup.include?(pair)
lookup.delete pair
intersection += 1
end
end
(2.0 * intersection) / union
end
private
def word_letter_pairs(str)
str.split(/\s+/).map{ |word| letter_pairs(word) }.flatten(1)
end
def letter_pairs(str)
(0 ... (str.length - 1)).map { |i| str[i, 2] }
end
extend self
end
end
|
Fix some linked page aren't visited. | require "test_helper"
feature "VisitAllPage" do
scenario "全てのリンクからページを辿ってエラーが起きないことを確認する" do
visit root_path
visited = []
visit_all_links(visited)
end
private
def visit_all_links(visited)
return if visited.include? current_path
visited << current_path
all('a').each do |a|
visit a[:href] && visit_all_links(visited)
end
end
end
| require "test_helper"
feature "VisitAllPage" do
scenario "全てのリンクからページを辿ってエラーが起きないことを確認する" do
visit root_path
visited = []
visit_all_links(visited)
end
private
def visit_all_links(visited)
return if visited.include? current_path
visited << current_path
all('a').each do |a|
visit a[:href]
visit_all_links(visited)
end
end
end
|
Add interface to EC2 service | require 'aws-sdk'
require 'contracts'
require_relative 'service'
module StackatoLKG
module Amazon
class EC2 < Service
Contract None => ArrayOf[::Aws::EC2::Types::Vpc]
def vpcs
@vpcs ||= vpcs!
end
Contract None => ArrayOf[::Aws::EC2::Types::Vpc]
def vpcs!
@vpcs = call_api(:describe_vpcs).vpcs
end
Contract None => ArrayOf[::Aws::EC2::Types::Subnet]
def subnets
@subnets ||= subnets!
end
Contract None => ArrayOf[::Aws::EC2::Types::Subnet]
def subnets!
@subnets = call_api(:describe_subnets).subnets
end
Contract None => ArrayOf[::Aws::EC2::Types::Instance]
def instances
@instances ||= instances!
end
Contract None => ArrayOf[::Aws::EC2::Types::Instance]
def instances!
@instances = call_api(:describe_instances)
.reservations
.flat_map(&:instances)
end
Contract None => ArrayOf[::Aws::EC2::Types::Address]
def addresses
@addresses ||= addresses!
end
Contract None => ArrayOf[::Aws::EC2::Types::Address]
def addresses!
@addresses = call_api(:describe_addresses).addresses
end
Contract None => ArrayOf[::Aws::EC2::Types::TagDescription]
def tags
@tags ||= tags!
end
Contract None => ArrayOf[::Aws::EC2::Types::TagDescription]
def tags!
@tags = call_api(:describe_tags).tags
end
Contract None => ::Aws::EC2::Types::Vpc
def create_vpc
call_api(:create_vpc, cidr_block: config.cidr_block).vpc
end
Contract ArrayOf[String], ArrayOf[{ key: String, value: String}] => Bool
def create_tags(resources, tags)
call_api(:create_tags, resources: resources, tags: tags).successful?
end
Contract String, Args[String] => Bool
def assign_name(name, *resources)
create_tags(resources, [{ key: 'Name', value: name } ])
end
Contract KeywordArgs[
type: Optional[String],
key: Optional[String],
value: Optional[String]
] => ArrayOf[::Aws::EC2::Types::TagDescription]
def tagged(type: nil, key: nil, value: nil)
tags
.select { |tag| type.nil? || tag.resource_type == type }
.select { |tag| tag.key == (key || 'Name') }
.select { |tag| value.nil? || tag.value == value }
end
private
def client
Aws::EC2::Client
end
end
end
end
| |
Add support for :each to FeaturesByName instances | require 'forwardable'
module FlipFab
class FeaturesByName
extend Forwardable
def initialize features_by_name={}
@features_by_name = features_by_name
end
def [] name
raise "no feature has been defined with the name: #{name}" if @features_by_name[name].nil?
@features_by_name[name]
end
def with_context context
FeaturesByName.new Hash[@features_by_name.map{|name, feature| [name, (feature.with_context context)]}]
end
def_delegators :@features_by_name, :[]=, :clear, :count
end
end
| require 'forwardable'
module FlipFab
class FeaturesByName
extend Forwardable
def initialize features_by_name={}
@features_by_name = features_by_name
end
def [] name
raise "no feature has been defined with the name: #{name}" if @features_by_name[name].nil?
@features_by_name[name]
end
def with_context context
FeaturesByName.new Hash[@features_by_name.map{|name, feature| [name, (feature.with_context context)]}]
end
def_delegators :@features_by_name, :[]=, :clear, :count, :each
end
end
|
Return nil if ConfigurationFile is unreadable. | # lib/frecon/configuration_file.rb
#
# Copyright (C) 2015 Christopher Cooper, Sam Craig, Tiger Huang, Vincent Mai, Sam Mercier, and Kristofer Rye
#
# This file is part of FReCon, an API for scouting at FRC Competitions, which is
# licensed under the MIT license. You should have received a copy of the MIT
# license with this program. If not, please see
# <http://opensource.org/licenses/MIT>.
require "yaml"
require "frecon/configuration"
module FReCon
class ConfigurationFile
attr_accessor :filename
def initialize(filename)
@filename = filename
end
def read
data = open(@filename, "rb") do |io|
io.read
end
Configuration.new(YAML.load(data))
end
end
end
| # lib/frecon/configuration_file.rb
#
# Copyright (C) 2015 Christopher Cooper, Sam Craig, Tiger Huang, Vincent Mai, Sam Mercier, and Kristofer Rye
#
# This file is part of FReCon, an API for scouting at FRC Competitions, which is
# licensed under the MIT license. You should have received a copy of the MIT
# license with this program. If not, please see
# <http://opensource.org/licenses/MIT>.
require "yaml"
require "frecon/configuration"
module FReCon
class ConfigurationFile
attr_accessor :filename
def initialize(filename)
@filename = filename
end
def read
begin
data = open(@filename, "rb") do |io|
io.read
end
Configuration.new(YAML.load(data))
rescue Errno::ENOENT
nil
end
Configuration.new(YAML.load(data))
end
end
end
|
Fix a mistake in regular expression | # frozen_string_literal: true
module LinkThumbnailer
class Response
def initialize(response)
@response = response
end
def charset
@charset ||= extract_charset
end
def body
@body ||= extract_body
end
private
def extract_charset
content_type = @response['Content-Type'] || ''
m = content_type.match(/charset=(\w+)/)
(m && m[1]) || @response.body.scrub =~ /<meta[^>]*charset\s*=\s*["']?(.+)["']/i && $1.upcase || ''
end
def extract_body
should_convert_body_to_utf8? ? convert_encoding_to_utf8(@response.body, charset) : @response.body
end
def should_convert_body_to_utf8?
charset != '' && charset != 'utf-8'
end
def convert_encoding_to_utf8(body, from)
Encoding::Converter.new(from, 'utf-8').convert(body)
rescue EncodingError
body
end
end
end
| # frozen_string_literal: true
module LinkThumbnailer
class Response
def initialize(response)
@response = response
end
def charset
@charset ||= extract_charset
end
def body
@body ||= extract_body
end
private
def extract_charset
content_type = @response['Content-Type'] || ''
m = content_type.match(/charset=([\w-]+)/)
(m && m[1]) || @response.body.scrub =~ /<meta[^>]*charset\s*=\s*["']?(.+?)["' >]/i && $1 || ''
end
def extract_body
should_convert_body_to_utf8? ? convert_encoding_to_utf8(@response.body, charset) : @response.body
end
def should_convert_body_to_utf8?
charset != '' && charset != 'utf-8'
end
def convert_encoding_to_utf8(body, from)
Encoding::Converter.new(from, 'utf-8').convert(body)
rescue EncodingError
body
end
end
end
|
Use sh in rake task instead of system | namespace :gulp_assets do
desc "Compile Gulp Assets"
task :precompile do
system('gulp precompile')
end
end
Rake::Task['assets:precompile'].enhance ['gulp_assets:precompile']
| namespace :gulp_assets do
desc "Compile Gulp Assets"
task :precompile do
sh "gulp precompile"
end
end
Rake::Task['assets:precompile'].enhance ['gulp_assets:precompile']
|
Add me to Gemspec :blue_heart: | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'udp2sqs_server/version'
Gem::Specification.new do |spec|
spec.name = "udp2sqs_server"
spec.version = Udp2sqsServer::VERSION
spec.authors = ["MalcyL, mmmmmrob"]
spec.email = ["malcolm@landonsonline.me.uk, rob@dynamicorange.com"]
spec.description = %q{Simple UDP server. Posts UDP payloads to a configured AWS SQS queue.}
spec.summary = %q{See also udp2sqs-client}
spec.homepage = ""
spec.license = "AGPL3"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "propono"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "mocha"
spec.add_development_dependency "minitest", "~> 5.0.8"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'udp2sqs_server/version'
Gem::Specification.new do |spec|
spec.name = "udp2sqs_server"
spec.version = Udp2sqsServer::VERSION
spec.authors = ["MalcyL, mmmmmrob", "iHiD"]
spec.email = ["malcolm@landonsonline.me.uk, rob@dynamicorange.com", "jeremy@meducation.net"]
spec.description = %q{Simple UDP server. Posts UDP payloads to a configured AWS SQS queue.}
spec.summary = %q{See also udp2sqs-client}
spec.homepage = ""
spec.license = "AGPL3"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "propono"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "mocha"
spec.add_development_dependency "minitest", "~> 5.0.8"
end
|
Add pin class method spec; not passing yet | require 'rails_helper'
RSpec.describe Pin, type: :model do
describe 'validations' do
it { is_expected.to validate_numericality_of :lat }
it { is_expected.to validate_numericality_of :lng }
it { is_expected.to validate_numericality_of :user_id }
it { is_expected.to validate_presence_of :name }
it { is_expected.to validate_presence_of :appeal }
it { is_expected.to validate_presence_of :lat }
it { is_expected.to validate_presence_of :lng }
end
describe 'associations' do
it { is_expected.to belong_to :user }
it { is_expected.to have_many :comments }
it { is_expected.to have_many :pintags }
end
describe 'class method' do
it "changes the tag object's to a string" do
end
end
end
| require 'rails_helper'
RSpec.describe Pin, type: :model do
let!(:pin) { create(:pin)}
describe 'validations' do
it { is_expected.to validate_numericality_of :lat }
it { is_expected.to validate_numericality_of :lng }
it { is_expected.to validate_numericality_of :user_id }
it { is_expected.to validate_presence_of :name }
it { is_expected.to validate_presence_of :appeal }
it { is_expected.to validate_presence_of :lat }
it { is_expected.to validate_presence_of :lng }
end
describe 'associations' do
it { is_expected.to belong_to :user }
it { is_expected.to have_many :comments }
it { is_expected.to have_many :pintags }
end
describe 'class method' do
it "changes the tag object's to a string" do
expect(Pin.tags_to_s(pin)).to eq "Quirky"
end
end
end
|
Add auto-restart setting to containers | module Conjure
module Provision
module Docker
class Host
def initialize(platform)
@platform = platform
end
def built_image_name(dockerfile_directory)
result = @platform.with_directory(dockerfile_directory) do |remote_dir|
@platform.run "docker build #{remote_dir}"
end
if match = result.match(/Successfully built ([0-9a-z]+)/)
match[1]
else
raise "Failed to build Docker image, output was #{result}"
end
end
def started_container_id(image_name, daemon_command, run_options = nil)
all_options = "-d #{run_options.to_s} #{image_name} #{daemon_command}"
@platform.run("docker run #{all_options}").strip
end
def container_ip_address(container_id)
format = "{{ .NetworkSettings.IPAddress }}"
@platform.run("docker inspect --format '#{format}' #{container_id}").strip
end
end
end
end
end
| module Conjure
module Provision
module Docker
class Host
def initialize(platform)
@platform = platform
end
def built_image_name(dockerfile_directory)
result = @platform.with_directory(dockerfile_directory) do |remote_dir|
@platform.run "docker build #{remote_dir}"
end
if match = result.match(/Successfully built ([0-9a-z]+)/)
match[1]
else
raise "Failed to build Docker image, output was #{result}"
end
end
def started_container_id(image_name, daemon_command, run_options = nil)
all_options = "-d --restart=always #{run_options.to_s} #{image_name} #{daemon_command}"
@platform.run("docker run #{all_options}").strip
end
def container_ip_address(container_id)
format = "{{ .NetworkSettings.IPAddress }}"
@platform.run("docker inspect --format '#{format}' #{container_id}").strip
end
end
end
end
end
|
Change struct to a real class | module Travis::API::V3
class Models::Subscription < Struct.new(:id, :valid_to, :plan, :coupon, :status, :source, :billing_info, :credit_card_info, :owner)
def initialize(attributes = {})
super(
attributes.fetch('id'),
attributes.fetch('valid_to') && DateTime.parse(attributes.fetch('valid_to')),
attributes.fetch('plan'),
attributes['coupon'],
attributes.fetch('status'),
attributes.fetch('source'),
attributes['billing_info'],
attributes['credit_card_info'],
attributes.fetch('owner'))
end
end
end
| module Travis::API::V3
class Models::Subscription
attr_reader :id, :valid_to, :plan, :coupon, :status, :source, :billing_info, :credit_card_info, :owner
def initialize(attributes = {})
@id = attributes.fetch('id')
@valid_to = attributes.fetch('valid_to') && DateTime.parse(attributes.fetch('valid_to'))
@plan = attributes.fetch('plan')
@coupon = attributes['coupon']
@status = attributes.fetch('status')
@source = attributes.fetch('source')
@billing_info = attributes['billing_info']
@credit_card_info = attributes['credit_card_info']
@owner = attributes.fetch('owner')
end
end
end
|
Add to_f to fix float probabilities problem | class StrokeCounter::Keyboard::Logger
attr_reader :logs
def initialize(args = {})
@logs = []
end
def add_log(log)
if log.is_a? Hash
@logs << log
true
else
false
end
end
def analyze
return { left: nil, right: nil} if @logs.size == 0
{ left: left_strokes.size / @logs.size.to_f, right: right_strokes.size / @logs.size.to_f,
probabilities: probabilities
}
end
def left_strokes
hand_strokes(:left)
end
def right_strokes
hand_strokes(:right)
end
def hand_strokes(hand)
@logs.select { |log| log[:hand] == hand}
end
def probabilities
hand = nil
counts = { r2l: 0, l2r: 0 }
size = { right: 0, left: 0}
@logs.each do |log|
size[log[:hand]] += 1
counts[:r2l] += 1 if hand == :right && log[:hand] == :left
counts[:l2r] += 1 if hand == :left && log[:hand] == :right
hand = log[:hand]
end
size[hand] -= 1 unless hand.nil?
l2r = counts[:l2r] / size[:left] rescue nil
r2l = counts[:r2l] / size[:right] rescue nil
{ left_to_right: l2r, right_to_left: r2l }
end
end
| class StrokeCounter::Keyboard::Logger
attr_reader :logs
def initialize(args = {})
@logs = []
end
def add_log(log)
if log.is_a? Hash
@logs << log
true
else
false
end
end
def analyze
return { left: nil, right: nil} if @logs.size == 0
{ left: left_strokes.size / @logs.size.to_f, right: right_strokes.size / @logs.size.to_f,
probabilities: probabilities
}
end
def left_strokes
hand_strokes(:left)
end
def right_strokes
hand_strokes(:right)
end
def hand_strokes(hand)
@logs.select { |log| log[:hand] == hand}
end
def probabilities
hand = nil
counts = { r2l: 0, l2r: 0 }
size = { right: 0, left: 0}
@logs.each do |log|
size[log[:hand]] += 1
counts[:r2l] += 1 if hand == :right && log[:hand] == :left
counts[:l2r] += 1 if hand == :left && log[:hand] == :right
hand = log[:hand]
end
size[hand] -= 1 unless hand.nil?
l2r = counts[:l2r] / size[:left].to_f rescue nil
r2l = counts[:r2l] / size[:right].to_f rescue nil
{ left_to_right: l2r, right_to_left: r2l }
end
end
|
Add method to create request | require "text2voice/version"
module Text2voice
# Your code goes here...
end
| require "text2voice/version"
module Text2voice
def initialize(api_key)
@api_key = api_key
end
def speaker(speaker_name)
end
def emotion(emotion: nil, level: nil)
end
def pitch(param)
end
def volulme(param)
end
def speak(text)
end
def save(wav)
end
def play(wav)
end
def create_request(text, speaker, emotion, emotion_level, pitch, speed, volume)
end
end
|
Load in fake auth details for test | # Generated by cucumber-sinatra. (2013-12-03 12:11:29 +0000)
ENV['RACK_ENV'] = 'test'
require File.join(File.dirname(__FILE__), '..', '..', 'lib/metrics-api.rb')
require 'capybara'
require 'capybara/cucumber'
require 'rspec'
require 'cucumber/api_steps'
require 'database_cleaner'
require 'database_cleaner/cucumber'
DatabaseCleaner.strategy = :truncation
Capybara.app = MetricsApi
class MetricsApiWorld
include Capybara::DSL
include RSpec::Expectations
include RSpec::Matchers
def app
MetricsApi
end
end
World do
MetricsApiWorld.new
end
| # Generated by cucumber-sinatra. (2013-12-03 12:11:29 +0000)
ENV['RACK_ENV'] = 'test'
ENV['METRICS_API_USERNAME'] = 'foo'
ENV['METRICS_API_PASSWORD'] = 'bar'
require File.join(File.dirname(__FILE__), '..', '..', 'lib/metrics-api.rb')
require 'capybara'
require 'capybara/cucumber'
require 'rspec'
require 'cucumber/api_steps'
require 'database_cleaner'
require 'database_cleaner/cucumber'
DatabaseCleaner.strategy = :truncation
Capybara.app = MetricsApi
class MetricsApiWorld
include Capybara::DSL
include RSpec::Expectations
include RSpec::Matchers
def app
MetricsApi
end
end
World do
MetricsApiWorld.new
end
|
Allow the widget to be loaded in an iframe | class TeamNameController < ApplicationController
skip_before_action :verify_authenticity_token, only: [:create]
def create
@colour_palette = [
"purple",
"mauve",
"fuschia",
"pink",
"baby-pink",
"red",
"mellow-red",
"orange",
"brown",
"yellow",
"grass-green",
"green",
"turquoise",
"light-blue"
]
end
def create_sign
sign_params = params.permit(:team_name, :colour)
team_name = sign_params[:team_name]
colour = sign_params[:colour]
uri_team_name = URI::encode(sign_params[:team_name]).gsub('_', '__').gsub('.', '_')
uri_colour = URI::encode(sign_params[:colour])
if !team_name.strip.empty? && !colour.strip.empty?
redirect_to "/sign/#{uri_team_name}/#{uri_colour}"
elsif !team_name.strip.empty?
redirect_to "/sign/#{uri_team_name}"
else
redirect_to "/create"
end
end
def sign
@colour = params[:colour]
@team_name = params[:team_name].gsub('_', '.').gsub('__', '_')
@page_title = "#{params[:team_name].gsub('_', '.').gsub('__', '_')} – "
end
end
| class TeamNameController < ApplicationController
skip_before_action :verify_authenticity_token, only: [:create]
after_action :allow_iframe, only: :sign
def create
@colour_palette = [
"purple",
"mauve",
"fuschia",
"pink",
"baby-pink",
"red",
"mellow-red",
"orange",
"brown",
"yellow",
"grass-green",
"green",
"turquoise",
"light-blue"
]
end
def create_sign
sign_params = params.permit(:team_name, :colour)
team_name = sign_params[:team_name]
colour = sign_params[:colour]
uri_team_name = URI::encode(sign_params[:team_name]).gsub('_', '__').gsub('.', '_')
uri_colour = URI::encode(sign_params[:colour])
if !team_name.strip.empty? && !colour.strip.empty?
redirect_to "/sign/#{uri_team_name}/#{uri_colour}"
elsif !team_name.strip.empty?
redirect_to "/sign/#{uri_team_name}"
else
redirect_to "/create"
end
end
def sign
@colour = params[:colour]
@team_name = params[:team_name].gsub('_', '.').gsub('__', '_')
@page_title = "#{params[:team_name].gsub('_', '.').gsub('__', '_')} – "
end
private
def allow_iframe
response.headers.except! 'X-Frame-Options'
end
end
|
Add a Rake task to mark an asset as deleted | namespace :assets do
desc "Mark an asset as deleted and remove from S3"
task :delete_and_remove_from_s3, [:id] => :environment do |_t, args|
asset = Asset.find(args.fetch(:id))
asset.delete
Services.cloud_storage.delete(asset)
end
end
| namespace :assets do
desc "Mark an asset as deleted"
task :delete, [:id] => :environment do |_t, args|
Asset.find(args.fetch(:id)).delete
end
desc "Mark an asset as deleted and remove from S3"
task :delete_and_remove_from_s3, [:id] => :environment do |_t, args|
asset = Asset.find(args.fetch(:id))
asset.delete
Services.cloud_storage.delete(asset)
end
end
|
Add short description to product backend | Deface::Override.new(:virtual_path => "spree/admin/products/_form",
:name => "admin_products_form_add_child_price",
:insert_before => "[data-hook='admin_product_form_right'] div.alpha.two.columns",
:text => <<eos
<%= f.field_container :child_price do %>
<%= f.label :child_price, raw(Spree.t(:child_price) + content_tag(:span, ' *', :class => "required")) %>
<%= f.text_field :child_price, :value => number_to_currency(@product.child_price, :unit => '') %>
<%= f.error_message_on :child_price %>
<% end %>
eos
)
| Deface::Override.new(:virtual_path => "spree/admin/products/_form",
:name => "admin_products_form_add_child_price",
:insert_before => "[data-hook='admin_product_form_right'] div.alpha.two.columns",
:text => <<eos
<%= f.field_container :child_price do %>
<%= f.label :child_price, raw(Spree.t(:child_price) + content_tag(:span, ' *', :class => "required")) %>
<%= f.text_field :child_price, :value => number_to_currency(@product.child_price, :unit => '') %>
<%= f.error_message_on :child_price %>
<% end %>
eos
)
Deface::Override.new(:virtual_path => "spree/admin/products/_form",
:name => "admin_products_form_add_short_description",
:insert_bottom => "[data-hook='admin_product_form_additional_fields']",
:text => <<eos
<%= f.field_container :short_description do %>
<%= f.label :short_description, 'Short description' %>
<%= f.text_area :short_description, {:rows => '13', :class => 'fullwidth'} %>
<%= f.error_message_on :short_description %>
<% end %>
eos
)
|
Check editor-3 feature flag in organization owner if applicable | # encoding: utf-8
module Carto
module Builder
module BuilderUsersModule
def builder_users_only
render_404 unless current_user && builder_user?(current_user)
end
def builder_user?(user)
user.has_feature_flag?('editor-3')
end
end
end
end
| # encoding: utf-8
module Carto
module Builder
module BuilderUsersModule
def builder_users_only
render_404 unless current_user && builder_user?(current_user)
end
def builder_user?(user)
manager_user(user).has_feature_flag?('editor-3')
end
def manager_user(user)
org = user.organization
org ? org.owner : user
end
end
end
end
|
Store original user in variable | class Admin::ImpersonationsController < Admin::ApplicationController
skip_before_action :authenticate_admin!
before_action :authenticate_impersonator!
def destroy
redirect_path = admin_user_path(current_user)
warden.set_user(impersonator, scope: :user)
session[:impersonator_id] = nil
redirect_to redirect_path
end
private
def impersonator
@impersonator ||= User.find(session[:impersonator_id]) if session[:impersonator_id]
end
def authenticate_impersonator!
render_404 unless impersonator && impersonator.is_admin? && !impersonator.blocked?
end
end
| class Admin::ImpersonationsController < Admin::ApplicationController
skip_before_action :authenticate_admin!
before_action :authenticate_impersonator!
def destroy
original_user = current_user
warden.set_user(impersonator, scope: :user)
session[:impersonator_id] = nil
redirect_to admin_user_path(original_user)
end
private
def impersonator
@impersonator ||= User.find(session[:impersonator_id]) if session[:impersonator_id]
end
def authenticate_impersonator!
render_404 unless impersonator && impersonator.is_admin? && !impersonator.blocked?
end
end
|
Add Cache-Control headers for product show action using fresh_when | module Spree
class ProductsController < Spree::StoreController
before_filter :load_product, :only => :show
rescue_from ActiveRecord::RecordNotFound, :with => :render_404
helper 'spree/taxons'
respond_to :html
def index
@searcher = build_searcher(params)
@products = @searcher.retrieve_products
@taxonomies = Spree::Taxonomy.includes(root: :children)
end
def show
return unless @product
@variants = @product.variants_including_master.active(current_currency).includes([:option_values, :images])
@product_properties = @product.product_properties.includes(:property)
referer = request.env['HTTP_REFERER']
if referer
begin
referer_path = URI.parse(request.env['HTTP_REFERER']).path
# Fix for #2249
rescue URI::InvalidURIError
# Do nothing
else
if referer_path && referer_path.match(/\/t\/(.*)/)
@taxon = Spree::Taxon.find_by_permalink($1)
end
end
end
end
private
def accurate_title
@product ? @product.name : super
end
def load_product
if try_spree_current_user.try(:has_spree_role?, "admin")
@products = Product.with_deleted
else
@products = Product.active(current_currency)
end
@product = @products.friendly.find(params[:id])
end
end
end
| module Spree
class ProductsController < Spree::StoreController
before_filter :load_product, :only => :show
rescue_from ActiveRecord::RecordNotFound, :with => :render_404
helper 'spree/taxons'
respond_to :html
def index
@searcher = build_searcher(params)
@products = @searcher.retrieve_products
@taxonomies = Spree::Taxonomy.includes(root: :children)
end
def show
return unless @product
@variants = @product.variants_including_master.active(current_currency).includes([:option_values, :images])
@product_properties = @product.product_properties.includes(:property)
referer = request.env['HTTP_REFERER']
if referer
begin
referer_path = URI.parse(request.env['HTTP_REFERER']).path
# Fix for #2249
rescue URI::InvalidURIError
# Do nothing
else
if referer_path && referer_path.match(/\/t\/(.*)/)
@taxon = Spree::Taxon.find_by_permalink($1)
end
end
end
fresh_when @product
end
private
def accurate_title
@product ? @product.name : super
end
def load_product
if try_spree_current_user.try(:has_spree_role?, "admin")
@products = Product.with_deleted
else
@products = Product.active(current_currency)
end
@product = @products.friendly.find(params[:id])
end
end
end
|
Make the rails version in the gemspec more restrictive | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "transam_spatial/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "transam_spatial"
s.version = TransamSpatial::VERSION
s.authors = ["Julian Ray"]
s.email = ["jray@camsys.com"]
s.homepage = "http://www.camsys.com"
s.summary = "Spatial Extensions for TransAM."
s.description = "Spatial Extensions for TransAM."
s.license = "MIT"
s.metadata = { "load_order" => "100" }
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.add_dependency 'rails', '>=4.0.9'
s.add_dependency "geocoder"
s.add_development_dependency "georuby", '~> 2.2.1'
s.add_development_dependency "rspec-rails"
s.add_development_dependency "factory_girl_rails"
s.add_development_dependency "database_cleaner"
s.add_development_dependency "mysql2"
s.add_development_dependency "cucumber-rails"
s.add_development_dependency "shoulda-matchers"
s.add_development_dependency "codacy-coverage"
s.add_development_dependency 'simplecov'
end
| $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "transam_spatial/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "transam_spatial"
s.version = TransamSpatial::VERSION
s.authors = ["Julian Ray"]
s.email = ["jray@camsys.com"]
s.homepage = "http://www.camsys.com"
s.summary = "Spatial Extensions for TransAM."
s.description = "Spatial Extensions for TransAM."
s.license = "MIT"
s.metadata = { "load_order" => "100" }
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.add_dependency 'rails', '~> 4.1.9'
s.add_dependency "geocoder"
s.add_development_dependency "georuby", '~> 2.2.1'
s.add_development_dependency "rspec-rails"
s.add_development_dependency "factory_girl_rails"
s.add_development_dependency "database_cleaner"
s.add_development_dependency "mysql2"
s.add_development_dependency "cucumber-rails"
s.add_development_dependency "shoulda-matchers"
s.add_development_dependency "codacy-coverage"
s.add_development_dependency 'simplecov'
end
|
Add initializer to add the observer to event | events_observer_debit_canceled = Neighborly::Balanced::EventsObserver::DebitCanceled.new
Neighborly::Balanced::Event.add_observer(events_observer_debit_canceled, :perform)
| |
Add comments fixtures for development | ActiveRecord::Base.observers.disable :all
Issue.all.limit(10).each_with_index do |issue, i|
5.times do
Note.seed(:id, [{
project_id: issue.project.id,
author_id: issue.project.team.users.sample.id,
note: Faker::Lorem.sentence,
noteable_id: issue.id,
noteable_type: 'Issue'
}])
end
end
| |
Add support for EWS Url | module AutodiscoverPlus
class PoxResponse
VERSIONS = {
8 => {
0 => "Exchange2007",
1 => "Exchange2007_SP1",
2 => "Exchange2007_SP1",
3 => "Exchange2007_SP1",
},
14 => {
0 => "Exchange2010",
1 => "Exchange2010_SP1",
2 => "Exchange2010_SP2",
3 => "Exchange2010_SP2",
},
15 => {
0 => "Exchange2013",
1 => "Exchange2013_SP1",
}
}
attr_reader :xml
def initialize(response)
@xml = Nokogiri::XML(response)
end
def exchange_version
hexver = xml.xpath("//s:ServerVersion", s: "http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a")[0].text
ServerVersionParser.new(hexver).exchange_version
end
end
end
| module AutodiscoverPlus
class PoxResponse
VERSIONS = {
8 => {
0 => "Exchange2007",
1 => "Exchange2007_SP1",
2 => "Exchange2007_SP1",
3 => "Exchange2007_SP1",
},
14 => {
0 => "Exchange2010",
1 => "Exchange2010_SP1",
2 => "Exchange2010_SP2",
3 => "Exchange2010_SP2",
},
15 => {
0 => "Exchange2013",
1 => "Exchange2013_SP1",
}
}
RESPONSE_SCHEMA = "http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a"
attr_reader :xml
def initialize(response)
@xml = Nokogiri::XML(response)
end
def exchange_version
hexver = xml.xpath("//s:ServerVersion", s: RESPONSE_SCHEMA)[0].text
ServerVersionParser.new(hexver).exchange_version
end
def ews_url
v = xml.xpath("//s:EwsUrl[../s:Type='EXPR']", s: RESPONSE_SCHEMA).text
v.empty? ? nil : v
end
end
end
|
Add new specs. Comment lines can be placed between fluent dot now | require_relative '../spec_helper'
describe "The comment" do
ruby_version_is "2.7" do
it "can be placed between fluent dot now" do
code = <<~CODE
10
# some comment
.to_s
CODE
eval(code).should == '10'
end
end
end
| |
Fix error in former migration. | class ChangeRereviewAndResubmissionDeadlines < ActiveRecord::Migration
def change
resubmission_deadlines = DueDate.where(:deadline_type_id=>3)
resubmission_deadlines.each do |resubmission_deadline|
resubmission_deadline.deadline_type = 1
resubmission_deadline.submission_allowed_id=3
resubmission_deadline.save
end
rereview_deadlines = DueDate.where(:deadline_type_id=>4)
rereview_deadlines.each do |resubmission_deadline|
rereview_deadline.deadline_type = 1
rereview_deadline.submission_allowed_id=3
rereview_deadline.save
end
end
end
| class ChangeRereviewAndResubmissionDeadlines < ActiveRecord::Migration
def change
resubmission_deadlines = DueDate.where(:deadline_type_id=>3)
resubmission_deadlines.each do |resubmission_deadline|
resubmission_deadline.deadline_type = 1
resubmission_deadline.submission_allowed_id=3
resubmission_deadline.save
end
rereview_deadlines = DueDate.where(:deadline_type_id=>4)
rereview_deadlines.each do |resubmission_deadline|
rereview_deadline.deadline_type = 2
rereview_deadline.submission_allowed_id=3
rereview_deadline.save
end
end
end
|
Add win32console if on windows | module Jstdutil
class RedGreen
# Borrowed from the ruby redgreen gem
# Not included as a gem dependency since it drags in Test::Unit
# and friends, which is overkill for our situation
module Color
COLORS = { :clear => 0, :red => 31, :green => 32, :yellow => 33 }
def self.method_missing(color_name, *args)
color(color_name) + args.first + color(:clear)
end
def self.color(color)
"\e[#{COLORS[color.to_sym]}m"
end
end
#
# Process report from JsTestDriver and colorize it with beautiful
# colors. Returns report with encoded colors.
#
def self.format(report)
report.split("\n").collect do |line|
if line =~ /Passed: \d+; Fails: (\d+); Errors:? (\d+)/
Color.send($1.to_i + $2.to_i != 0 ? :red : :green, line)
elsif line =~ /^[\.EF]+$/
line.gsub(/\./, Color.green(".")).gsub(/F/, Color.red("F")).gsub("E", Color.yellow("E"))
elsif line =~ /failed/
Color.red(line)
elsif line =~ /passed/
Color.green(line)
elsif line =~ /error/
Color.yellow(line)
else
line
end
end.join("\n")
end
end
end
| begin
require 'Win32/Console/ANSI' if PLATFORM =~ /win32/
rescue LoadError
raise 'You must gem install win32console to use color on Windows'
end
module Jstdutil
class RedGreen
# Borrowed from the ruby redgreen gem
# Not included as a gem dependency since it drags in Test::Unit
# and friends, which is overkill for our situation
module Color
COLORS = { :clear => 0, :red => 31, :green => 32, :yellow => 33 }
def self.method_missing(color_name, *args)
color(color_name) + args.first + color(:clear)
end
def self.color(color)
"\e[#{COLORS[color.to_sym]}m"
end
end
#
# Process report from JsTestDriver and colorize it with beautiful
# colors. Returns report with encoded colors.
#
def self.format(report)
report.split("\n").collect do |line|
if line =~ /Passed: \d+; Fails: (\d+); Errors:? (\d+)/
Color.send($1.to_i + $2.to_i != 0 ? :red : :green, line)
elsif line =~ /^[\.EF]+$/
line.gsub(/\./, Color.green(".")).gsub(/F/, Color.red("F")).gsub("E", Color.yellow("E"))
elsif line =~ /failed/
Color.red(line)
elsif line =~ /passed/
Color.green(line)
elsif line =~ /error/
Color.yellow(line)
else
line
end
end.join("\n")
end
end
end
|
Add another attribute to Post struct to check that is not included. | require 'cutest'
require_relative '../lib/json_serializer'
Post = Struct.new :id, :title
class PostSerializer < JsonSerializer
attribute :id
attribute :title
attribute :slug
def slug
"#{ object.id }-#{ object.title }"
end
end
test 'converts defined attributes into json' do
post = Post.new 1, 'tsunami'
serializer = PostSerializer.new post
result = {
id: 1,
title: 'tsunami',
slug: '1-tsunami'
}
assert_equal result.to_json, serializer.to_json
end
class PostWithRootSerializer < JsonSerializer
root :post
attribute :id
attribute :title
end
test 'defines root' do
post = Post.new 1, 'tsunami'
serializer = PostWithRootSerializer.new post
result = { post: post.to_h }.to_json
assert_equal result, serializer.to_json
end
| require 'cutest'
require_relative '../lib/json_serializer'
Post = Struct.new :id, :title, :created_at
class PostSerializer < JsonSerializer
attribute :id
attribute :title
attribute :slug
def slug
"#{ object.id }-#{ object.title }"
end
end
test 'converts defined attributes into json' do
post = Post.new 1, 'tsunami'
serializer = PostSerializer.new post
result = {
id: 1,
title: 'tsunami',
slug: '1-tsunami'
}
assert_equal result.to_json, serializer.to_json
end
class PostWithRootSerializer < JsonSerializer
root :post
attribute :id
attribute :title
end
test 'defines root' do
post = Post.new 1, 'tsunami'
serializer = PostWithRootSerializer.new post
result = { post: { id: 1, title: 'tsunami' } }.to_json
assert_equal result, serializer.to_json
end
|
Use more strict SQL in payments query | class WelcomeController < ApplicationController
def index
@total_invoiced = Invoice.all.map{|i| i.total}.sum
@total_payments_received = Payment.sum :amount
@total_invoices_unpaid = @total_invoiced - @total_payments_received
@payments_by_sponsor = Payment.select('*, sum(amount) as total').group('invoice_id')
end
def about
adapter = Rails.configuration.database_configuration[Rails.env]['adapter']
url = Rails.configuration.database_configuration[Rails.env]['url']
if adapter == 'sqlite3'
@db_server_version = ActiveRecord::Base.connection.execute('select sqlite_version()')[0][0]
@db_adapter = "SQLite3"
elsif adapter == 'postgresql' || /^postgresql/ =~ url
@db_server_version = ActiveRecord::Base.connection.execute('select version()').first['version']
@db_adapter = "PostgreSQL"
else
@db_adapter = "Database"
@db_server_version = "unknown"
end
end
end
| class WelcomeController < ApplicationController
def index
@total_invoiced = Invoice.all.map{|i| i.total}.sum
@total_payments_received = Payment.sum :amount
@total_invoices_unpaid = @total_invoiced - @total_payments_received
@payments_by_sponsor = Payment.select('*, sum(amount) as total').group('invoice_id, id')
end
def about
adapter = Rails.configuration.database_configuration[Rails.env]['adapter']
url = Rails.configuration.database_configuration[Rails.env]['url']
if adapter == 'sqlite3'
@db_server_version = ActiveRecord::Base.connection.execute('select sqlite_version()')[0][0]
@db_adapter = "SQLite3"
elsif adapter == 'postgresql' || /^postgresql/ =~ url
@db_server_version = ActiveRecord::Base.connection.execute('select version()').first['version']
@db_adapter = "PostgreSQL"
else
@db_adapter = "Database"
@db_server_version = "unknown"
end
end
end
|
Update pod spec version to 0.14.3 | Pod::Spec.new do |s|
s.name = 'ObjectMapperDeep'
s.version = '0.14.2'
s.license = 'MIT'
s.summary = 'JSON Object mapping written in Swift, support deep array mapping'
s.homepage = 'https://github.com/tonyli508/ObjectMapperDeep'
s.social_media_url = 'https://twitter.com/tonyli508'
s.authors = { 'Li Jiantang' => 'tonyli508@gmail.com' }
s.source = { :git => 'https://github.com/tonyli508/ObjectMapperDeep.git', :tag => s.version.to_s }
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.9'
s.requires_arc = 'true'
s.source_files = 'ObjectMapper/**/*.swift'
end
| Pod::Spec.new do |s|
s.name = 'ObjectMapperDeep'
s.version = '0.14.3'
s.license = 'MIT'
s.summary = 'JSON Object mapping written in Swift, support deep array mapping'
s.homepage = 'https://github.com/tonyli508/ObjectMapperDeep'
s.social_media_url = 'https://twitter.com/tonyli508'
s.authors = { 'Li Jiantang' => 'tonyli508@gmail.com' }
s.source = { :git => 'https://github.com/tonyli508/ObjectMapperDeep.git', :tag => s.version.to_s }
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.9'
s.requires_arc = 'true'
s.source_files = 'ObjectMapper/**/*.swift'
end
|
Correct some warnings in gemspec | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'capistrano/send/version'
Gem::Specification.new do |spec|
spec.name = "capistrano-send"
spec.version = Capistrano::Send::VERSION
spec.authors = ["Guillaume Dott"]
spec.email = ["guillaume+github@dott.fr"]
spec.summary = %q{Send notifications after a deploy with Capistrano}
spec.homepage = "https://github.com/gdott9/capistrano-send"
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 "libnotify", "~> 0.9.0"
spec.add_development_dependency "mail", "~> 2.6.3"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'capistrano/send/version'
Gem::Specification.new do |spec|
spec.name = "capistrano-send"
spec.version = Capistrano::Send::VERSION
spec.authors = ["Guillaume Dott"]
spec.email = ["guillaume+github@dott.fr"]
spec.summary = %q{Send notifications after a deploy with Capistrano}
spec.description = %q{This gem provides some notifiers to send notifications after a deploy with Capistrano.}
spec.homepage = "https://github.com/gdott9/capistrano-send"
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 "libnotify", "~> 0.9.0"
spec.add_development_dependency "mail", "~> 2.6"
end
|
Change API Motions Query To Use Multiple Criteria | class Api::MotionsController < ApiController
def index
@motions = if @@query.empty?
Motion.all
else
Motion.where("lower(amendment_text) LIKE ?", @@query)
end
paginate json: @motions.order(change_query_order), per_page: change_per_page
end
def show
@motion = Motion.find(params[:id])
render json: @motion, serializer: MotionDetailSerializer
end
end
| class Api::MotionsController < ApiController
def index
councillor_id = params[:councillor_id]
item_id = params[:item_id]
motion_type_id = params[:motion_type_id]
@motions = Motion.all
@motions.where("lower(amendment_text) LIKE ?", @@query) unless @@query.empty?
@motions = @motions.where("councillor_id = ?", councillor_id) if councillor_id.present?
@motions = @motions.where("item_id = ?", item_id) if item_id.present?
@motions = @motions.where("motion_type_id = ?", motion_type_id) if motion_type_id.present?
paginate json: @motions.order(change_query_order), per_page: change_per_page
end
def show
@motion = Motion.find(params[:id])
render json: @motion, serializer: MotionDetailSerializer
end
end
|
Update gem version to 0.4.6 | # frozen_string_literal: true
Gem::Specification.new do |spec|
spec.name = "no-style-please"
spec.version = "0.4.5"
spec.authors = ["Riccardo Graziosi"]
spec.email = ["riccardo.graziosi97@gmail.com"]
spec.summary = "A (nearly) no-CSS, fast, minimalist Jekyll theme."
spec.homepage = "https://github.com/riggraz/no-style-please"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").select { |f| f.match(%r!^(assets|_layouts|_includes|_sass|LICENSE|README|_config\.yml)!i) }
spec.add_runtime_dependency "jekyll", "~> 3.9.0"
spec.add_runtime_dependency "jekyll-feed", "~> 0.15.1"
spec.add_runtime_dependency "jekyll-seo-tag", "~> 2.7.1"
end
| # frozen_string_literal: true
Gem::Specification.new do |spec|
spec.name = "no-style-please"
spec.version = "0.4.6"
spec.authors = ["Riccardo Graziosi"]
spec.email = ["riccardo.graziosi97@gmail.com"]
spec.summary = "A (nearly) no-CSS, fast, minimalist Jekyll theme."
spec.homepage = "https://github.com/riggraz/no-style-please"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").select { |f| f.match(%r!^(assets|_layouts|_includes|_sass|LICENSE|README|_config\.yml)!i) }
spec.add_runtime_dependency "jekyll", "~> 3.9.0"
spec.add_runtime_dependency "jekyll-feed", "~> 0.15.1"
spec.add_runtime_dependency "jekyll-seo-tag", "~> 2.7.1"
end
|
Remove tests around feedback form | require 'rails_helper'
RSpec.feature 'Submit feedback', js: true do
include FeaturesHelper
# The body contains two fields which can vary:
#
# * referrer: The port changes from run to run
# * user_agent: This differs between local machines and Circle CI
#
# This matcher truncates these fields.
normalised_body = lambda do |r1, r2|
normalised = [r1.body, r2.body].map { |req|
req.sub(/,"referrer":.+$/, '}')
}
normalised.first == normalised.last
end
custom_matchers = [:method, :uri, :host, :path, :valid_uuid, normalised_body]
scenario 'including prisoner details', vcr: {
match_requests_on: custom_matchers,
cassette_name: :submit_feedback
} do
text = 'How many times did the Batmobile catch a flat?'
email_address = 'user@test.example.com'
prisoner_number = 'A1234BC'
prisoner_dob_day = 1
prisoner_dob_month = 1
prisoner_dob_year = 1999
prison_name = 'Leeds'
visit booking_requests_path(locale: 'en')
click_link 'Contact us'
fill_in 'Your message', with: text
fill_in 'Prisoner number', with: prisoner_number
fill_in 'Day', with: prisoner_dob_day
fill_in 'Month', with: prisoner_dob_month
fill_in 'Year', with: prisoner_dob_year
select_prison prison_name
fill_in 'Your email address', with: email_address
click_button 'Send'
expect(page).to have_text('Thank you for your feedback')
end
scenario 'no prisoner details', vcr: {
match_requests_on: custom_matchers,
cassette_name: :submit_feedback_no_prisoner_details
} do
text = 'How many times did the Batmobile catch a flat?'
email_address = 'user@test.example.com'
visit booking_requests_path(locale: 'en')
click_link 'Contact us'
fill_in 'Your message', with: text
fill_in 'Your email address', with: email_address
click_button 'Send'
expect(page).to have_text('Thank you for your feedback')
end
end
| require 'rails_helper'
RSpec.feature 'Submit feedback', js: true do
include FeaturesHelper
# The body contains two fields which can vary:
#
# * referrer: The port changes from run to run
# * user_agent: This differs between local machines and Circle CI
#
# This matcher truncates these fields.
normalised_body = lambda do |r1, r2|
normalised = [r1.body, r2.body].map { |req|
req.sub(/,"referrer":.+$/, '}')
}
normalised.first == normalised.last
end
custom_matchers = [:method, :uri, :host, :path, :valid_uuid, normalised_body]
end
|
Change homepage to github page | Gem::Specification.new do |s|
s.name = 'smart_logger'
s.version = '0.1.0'
s.date = '2012-04-15'
s.summary = "Smart tagged log"
s.description = "Smart grouping of log entries"
s.authors = ["Boris Dinkevich"]
s.email = 'do@itlater.com'
s.homepage = 'http://rubygems.org/gems/smart_logger'
s.files = ["lib/smart_logger.rb",
"lib/smart_logger/active_support.rb",
"lib/smart_logger/logger.rb",
"lib/smart_logger/rack.rb",
"lib/smart_logger/resque.rb",
]
end
| Gem::Specification.new do |s|
s.name = 'smart_logger'
s.version = '0.1.0'
s.date = '2012-04-15'
s.summary = "Smart tagged log"
s.description = "Smart grouping of log entries"
s.authors = ["Boris Dinkevich"]
s.email = 'do@itlater.com'
s.homepage = 'https://github.com/borisd/smart_logger'
s.files = ["lib/smart_logger.rb",
"lib/smart_logger/active_support.rb",
"lib/smart_logger/logger.rb",
"lib/smart_logger/rack.rb",
"lib/smart_logger/resque.rb",
]
end
|
Use the smaller and default log format in dev | # Taken from: http://cbpowell.wordpress.com/2013/08/09/beautiful-logging-for-ruby-on-rails-4/
class ActiveSupport::Logger::SimpleFormatter
SEVERITY_TO_TAG_MAP = {'DEBUG'=>'meh', 'INFO'=>'fyi', 'WARN'=>'hmm', 'ERROR'=>'wtf', 'FATAL'=>'omg', 'UNKNOWN'=>'???'}
SEVERITY_TO_COLOR_MAP = {'DEBUG'=>'0;37', 'INFO'=>'32', 'WARN'=>'33', 'ERROR'=>'31', 'FATAL'=>'31', 'UNKNOWN'=>'37'}
USE_HUMOROUS_SEVERITIES = false
def call(severity, time, progname, msg)
if USE_HUMOROUS_SEVERITIES
formatted_severity = sprintf("%-3s",SEVERITY_TO_TAG_MAP[severity])
else
formatted_severity = sprintf("%-5s",severity)
end
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S.") << time.usec.to_s[0..2].rjust(3)
color = SEVERITY_TO_COLOR_MAP[severity]
"\033[0;37m#{formatted_time}\033[0m [\033[#{color}m#{formatted_severity}\033[0m] #{msg.strip} (pid:#{$$})\n"
end
end | # Taken from: http://cbpowell.wordpress.com/2013/08/09/beautiful-logging-for-ruby-on-rails-4/
unless Rails.env == "development"
class ActiveSupport::Logger::SimpleFormatter
SEVERITY_TO_TAG_MAP = {'DEBUG'=>'meh', 'INFO'=>'fyi', 'WARN'=>'hmm', 'ERROR'=>'wtf', 'FATAL'=>'omg', 'UNKNOWN'=>'???'}
SEVERITY_TO_COLOR_MAP = {'DEBUG'=>'0;37', 'INFO'=>'32', 'WARN'=>'33', 'ERROR'=>'31', 'FATAL'=>'31', 'UNKNOWN'=>'37'}
USE_HUMOROUS_SEVERITIES = false
def call(severity, time, progname, msg)
if USE_HUMOROUS_SEVERITIES
formatted_severity = sprintf("%-3s",SEVERITY_TO_TAG_MAP[severity])
else
formatted_severity = sprintf("%-5s",severity)
end
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S.") << time.usec.to_s[0..2].rjust(3)
color = SEVERITY_TO_COLOR_MAP[severity]
"\033[0;37m#{formatted_time}\033[0m [\033[#{color}m#{formatted_severity}\033[0m] #{msg.strip} (pid:#{$$})\n"
end
end
end
|
Make the version a bit dynamic. | Gem::Specification.new do |spec|
spec.homepage = "https://github.com/envygeeks/mongoid-find_by"
spec.summary = "Add ActiveRecord like finders to Mongoid."
spec.required_ruby_version = '>= 1.9.3'
spec.name = "mongoid-find_by"
spec.has_rdoc = false
spec.license = "MIT"
spec.version = 0.3
spec.require_paths = ["lib"]
spec.authors = "Jordon Bedwell"
spec.email = "envygeeks@gmail.com"
spec.add_runtime_dependency("mongoid", "~> 3.0.19")
spec.add_development_dependency("rake", "~> 10.0.3")
spec.add_development_dependency("rspec", "~> 2.12.0")
spec.add_development_dependency("shoulda-matchers", "~> 1.4.2")
spec.files = %w(Readme.md License Rakefile Gemfile) + Dir.glob('lib/**/*')
spec.description = "'Add ActiveRecord like finders to your Mongoid install."
end
| $:.unshift(File.expand_path('../lib', __FILE__))
require "mongoid-find_by"
Gem::Specification.new do |spec|
spec.homepage = "https://github.com/envygeeks/mongoid-find_by"
spec.summary = "Add ActiveRecord like finders to Mongoid."
spec.required_ruby_version = '>= 1.9.3'
spec.name = "mongoid-find_by"
spec.has_rdoc = false
spec.license = "MIT"
spec.require_paths = ["lib"]
spec.authors = "Jordon Bedwell"
spec.email = "envygeeks@gmail.com"
spec.version = Mongoid::Finders::FindBy::VERSION
spec.add_runtime_dependency("mongoid", "~> 3.0.19")
spec.add_development_dependency("rake", "~> 10.0.3")
spec.add_development_dependency("rspec", "~> 2.12.0")
spec.add_development_dependency("shoulda-matchers", "~> 1.4.2")
spec.files = %w(Readme.md License Rakefile Gemfile) + Dir.glob('lib/**/*')
spec.description = "'Add ActiveRecord like finders to your Mongoid install."
end
|
Add a benchmark about using JS Symbols vs Strings | Benchmark.ips do |x|
%x{
var o = {}
o[Symbol.for('foo')] = 123
o.foo = 123
var foo = Symbol('foo')
o[foo] = 123
var a = 0, b = 0, c = 0
}
x.report('global symbol') do
`a += o[Symbol.for('foo')]`
end
x.report('symbol') do
`a += o[foo]`
end
x.report('ident') do
`b += o.foo`
end
x.report('string') do
`c += o['foo']`
end
x.compare!
end
| |
Update history to be run as part of upload script | require "log4r"
class Admin < Application
include Log4r
before :ensure_has_admin_privileges
def index
render
end
def upload
if params[:file]
file = Upload.new(params[:file][:filename])
log = Logger.new 'upload_log'
pf = PatternFormatter.new(:pattern => "<b>[%l]</b> %m")
file_log = Log4r::FileOutputter.new('output_log', :filename => [Merb.root, "public", "logs", file.directory].join("/"), :truncate => false, :formatter => pf)
log.add(file_log)
log.level = INFO
file.move(params[:file][:tempfile].path)
Merb.run_later do
log.info("File has been uploaded to the server. Now processing it into a bunch of csv files")
file.process_excel_to_csv
log.info("CSVs extraction complete. Processing files.")
file.load_csv(log)
log.info("<h2>Processing complete! Your MIS is now ready for use. Please take a note of all the errors reported here(if any) and rectify them.</h2>")
end
redirect "/admin/upload_status/#{file.directory}"
else
render
end
end
def upload_status
render
end
end
| require "log4r"
class Admin < Application
include Log4r
before :ensure_has_admin_privileges
def index
render
end
def upload
if params[:file]
file = Upload.new(params[:file][:filename])
log = Logger.new 'upload_log'
pf = PatternFormatter.new(:pattern => "<b>[%l]</b> %m")
file_log = Log4r::FileOutputter.new('output_log', :filename => [Merb.root, "public", "logs", file.directory].join("/"), :truncate => false, :formatter => pf)
log.add(file_log)
log.level = INFO
file.move(params[:file][:tempfile].path)
Merb.run_later do
log.info("File has been uploaded to the server. Now processing it into a bunch of csv files")
file.process_excel_to_csv
log.info("CSV extraction complete. Processing files.")
file.load_csv(log)
log.info("CSV files are now loaded into the DB. Creating loan schedules.")
`rake mock:update_history`
log.info("<h2>Processing complete! Your MIS is now ready for use. Please take a note of all the errors reported here(if any) and rectify them.</h2>")
end
redirect "/admin/upload_status/#{file.directory}"
else
render
end
end
def upload_status
render
end
end
|
Fix accidental error instead of 404. | module Community
class TopicsController < ::ActionController::Base
layout 'community'
def show
@topic = Community::Topic.find_by_slug params[:id]
not_found! if @topic.nil?
@first_post = @topic.posts.order(:created_at).first
@posts = @topic.posts.order(:created_at).page(params[:page]).per(20)
end
end
end
| module Community
class TopicsController < ::ActionController::Base
layout 'community'
def show
@topic = Community::Topic.find_by_slug params[:id]
raise ActionController::RoutingError.new('Not Found') if @topic.nil?
@first_post = @topic.posts.order(:created_at).first
@posts = @topic.posts.order(:created_at).page(params[:page]).per(20)
end
end
end
|
Add GraphicsMagick as a new package | module Autoparts
module Packages
class GraphicsMagick < Package
name 'graphics_magick'
version '1.3.19'
description 'GraphicsMagick: the swiss army knife of image processing.'
category Category::UTILITIES
source_url 'http://downloads.sourceforge.net/project/graphicsmagick/graphicsmagick/1.3.19/GraphicsMagick-1.3.19.tar.gz'
source_sha1 '4176b88a046319fe171232577a44f20118c8cb83'
source_filetype 'tar.gz'
def compile
Dir.chdir('GraphicsMagick-1.3.19') do
args = [
"--prefix=#{prefix_path}"
]
execute './configure', *args
execute 'make'
end
end
def install
Dir.chdir('GraphicsMagick-1.3.19') do
execute 'make', 'install'
end
end
def graphics_magick_path
bin_path + 'graphics_magick'
end
end
end
end
| |
Create new branch with specs passing and features failing | require_relative 'spec_helper'
describe 'simple passing test' do
it 'passes' do
say_hello.must_equal 'Hello'
# expect(say_hello).to_equal 'Hello'
end
end
describe 'simple failing test' do
it 'fails' do
# Only the must_equal format gives the file and line where the failure occurred
say_bye.must_equal 'Bye'
# expect(say_bye).to_equal 'Bye'
end
end
| require_relative 'spec_helper'
describe 'simple passing test' do
it 'passes' do
say_hello.must_equal 'Hello'
# expect(say_hello).to_equal 'Hello'
end
end
describe 'simple failing test' do
it 'fails' do
# Only the must_equal format gives the file and line where the failure occurred
say_bye.must_equal 'Hello'
# say_bye.must_equal 'Bye'
# expect(say_bye).to_equal 'Bye'
end
end
|
Update bash-it sha to latest for chruby support | node.default['versions']['bash_it'] = '5cb0ecc1c813bc5619e0f708b8015a4596a37d6c'
| node.default['versions']['bash_it'] = '8bf641baec4316cebf1bc1fd2757991f902506dc'
|
Increase aruba timeout for Travis rbx-2.0. | require 'aruba/cucumber'
Before do
@aruba_timeout_seconds = 30
end
| require 'aruba/cucumber'
Before do
@aruba_timeout_seconds = 300
end
|
Make InspectableMockServer register request before holding it | require_relative 'mock_server'
=begin
It must be working without threads.
Just on fibers.
It must *return* control after each step.
Like so:
```
send request
server.accept_one_connection
....
server.respond
```
Hint: a client must be on fibers too.
=end
class InspectableMockServer < MockServer
attr_reader :request_queue
def run_async
self.request_queue = []
self.hold_requests = true
super
end
def respond_to_first
request_queue.shift.signal
sleep(0.05) # TODO: get rid of this shame (join thread in specs?)
end
def respond_to_all
request_queue.each(&:signal)
request_queue.clear
end
def dont_hold_requests
self.hold_requests = false
respond_to_all
end
protected
attr_writer :request_queue
attr_accessor :hold_requests
def handle_connection(client_socket)
if hold_requests
condition = Celluloid::Condition.new
request_queue << condition
read_request client_socket
condition.wait
write_response client_socket
else
super
end
end
end
| require_relative 'mock_server'
=begin
It must be working without threads.
Just on fibers.
It must *return* control after each step.
Like so:
```
send request
server.accept_one_connection
....
server.respond
```
Hint: a client must be on fibers too.
=end
class InspectableMockServer < MockServer
attr_reader :request_queue
def run_async
self.request_queue = []
self.hold_requests = true
super
end
def respond_to_first
request_queue.shift.signal
sleep(0.05) # TODO: get rid of this shame (join thread in specs?)
end
def respond_to_all
request_queue.each(&:signal)
request_queue.clear
end
def dont_hold_requests
self.hold_requests = false
respond_to_all
end
protected
attr_writer :request_queue
attr_accessor :hold_requests
def handle_connection(client_socket)
if hold_requests
read_request client_socket
hold_request
write_response client_socket
else
super
end
end
def hold_request
Celluloid::Condition.new.tap do |condition|
request_queue << condition
condition.wait
end
end
end
|
Test all 9 positions are empty | require 'spec_helper'
describe TicTacToe do
it 'has a version number' do
expect(TicTacToe::VERSION).not_to be nil
end
it 'has a board' do
game = TicTacToe::Board.new
expect(game).to be_an_instance_of TicTacToe::Board
end
describe TicTacToe::Board do
before :each do
@game = TicTacToe::Board.new
end
it 'initially has empty positions' do
expect(@game.pos [1,1]).to eq(" ")
end
end
end
| require 'spec_helper'
describe TicTacToe do
it 'has a version number' do
expect(TicTacToe::VERSION).not_to be nil
end
it 'has a board' do
game = TicTacToe::Board.new
expect(game).to be_an_instance_of TicTacToe::Board
end
describe TicTacToe::Board do
before :each do
@game = TicTacToe::Board.new
end
it 'initially has 9 empty positions' do
(1..3).each do |x|
(1..3).each do |y|
expect(@game.pos [x,y]).to eq(" ")
end
end
end
end
end
|
Make it a match type | ####
#
# ElectroCode Channel Welcomer and AutoAssigner
#
####
class WelcomePlugin
include Cinch::Plugin
listen_to :PRIVMSG, use_prefix: false, method: :doWelcome
def doWelcome(m,bleh)
if m.channel == "#debug"
Channel("#Situation_Room").send("A message was sent to #debug")
end
end
end
| ####
#
# ElectroCode Channel Welcomer and AutoAssigner
#
####
class WelcomePlugin
include Cinch::Plugin
match /(.*)/i, react_on: :channel, use_prefix: false, method: :doWelcome
def doWelcome(m, bleh)
if m.channel == "#debug"
Channel("#Situation_Room").send("A message was sent to #debug")
end
end
end
|
Add tests for Utils class | require 'rubygems/test_case'
require 'rubygems/comparator'
class TestGemComparatorUtils < Gem::TestCase
def setup
super
# This should pull in Gem::Comparator::Utils
@test_comparator = Class.new(Gem::Comparator::Base).new
end
def test_param_exist?
params = (Gem::Comparator::Utils::SPEC_PARAMS +
Gem::Comparator::Utils::SPEC_FILES_PARAMS +
Gem::Comparator::Utils::DEPENDENCY_PARAMS +
Gem::Comparator::Utils::GEMFILE_PARAMS)
params.each do |param|
assert_equal true, @test_comparator.send(:param_exists?, param)
end
assert_equal false, @test_comparator.send(:param_exists?, 'i_dont_exist')
end
def test_filter_params
params = Gem::Comparator::Utils::SPEC_PARAMS
assert_equal ['license'], @test_comparator.send(:filter_params, params, 'license')
end
def test_filter_for_brief_mode
exclude = Gem::Comparator::Utils::FILTER_WHEN_BRIEF + ['not_excluded']
assert_equal ['not_excluded'], @test_comparator.send(:filter_for_brief_mode, exclude)
end
end
| |
Make all the regexes case-insensitive. | class Memes
@memes = {
# "a wild ruby library appears"
:pokemon => /a wild (.*) appears/,
# "I don't always write regexp but when I do they break"
:dos_equis => /I don'?t always (.*) but when I do? (.*)/,
# "North Korea is best Korea"
:is_best => /(\w*\b) (\w*\b) is best (\w*\b)/,
# Yo dawg I heard you like regexp so I put a regexp in your regexp so you can blah
:yo_dawg => /yo dawg I hea?rd you like (.*) so I put a (.*) in your (.*) so you can (.*) while you (.*)/,
# cant tell if this project is going to go anywhere or just end up on the bottom of my github profile
# not sure if blah or blah
:fry => /(can'?t tell|not sure) if (.*) or (.*)/,
# lets take all the memes and put them over here
:patrick => /let'?s take all the (.*) and put them over here/,
# soon
:soon => /soon/,
# Y U NO?
:y_u_no? => /(.*) Y U NO (.*)?/,
}
end
| class Memes
@memes = {
# "a wild ruby library appears"
:pokemon => /a wild (.*) appears/i,
# "I don't always write regexp but when I do they break"
:dos_equis => /I don'?t always (.*) but when I do? (.*)/i,
# "North Korea is best Korea"
:is_best => /(\w*\b) (\w*\b) is best (\w*\b)/i,
# Yo dawg I heard you like regexp so I put a regexp in your regexp so you can blah
:yo_dawg => /yo dawg I hea?rd you like (.*) so I put a (.*) in your (.*) so you can (.*) while you (.*)/i,
# cant tell if this project is going to go anywhere or just end up on the bottom of my github profile
# not sure if blah or blah
:fry => /(can'?t tell|not sure) if (.*) or (.*)/i,
# lets take all the memes and put them over here
:patrick => /let'?s take all the (.*) and put them over here/i,
# soon
:soon => /soon/i,
# Y U NO?
:y_u_no? => /(.*) Y U NO (.*)?/i,
}
end
|
Add spec for not overwriting the image_url on profile update | # Copyright (c) 2010, Diaspora Inc. This file is
# licensed under the Affero General Public License version 3. See
# the COPYRIGHT file.
require 'spec_helper'
describe UsersController do
before do
@user = Factory.create(:user)
sign_in :user, @user
@user.aspect(:name => "lame-os")
end
describe '#update' do
context 'with a profile photo set' do
before do
@user.person.profile.image_url = "http://tom.joindiaspora.com/images/user/tom.jpg"
@user.person.profile.save
end
it "doesn't overwrite the profile photo when an empty string is passed in" do
image_url = @user.person.profile.image_url
put("update", :id => @user.id, "user"=> {"profile"=>
{"image_url" => "",
"last_name" => @user.person.profile.last_name,
"first_name" => @user.person.profile.first_name}})
@user.person.profile.image_url.should == image_url
end
end
end
end
| |
Add newline at end of file | class PricesUrl
def initialize(url)
raise InvalidURL, "You must give an url, ie http://www.ns.nl/api" unless url
@url = url
end
def url (opts = {date: nil, from: "", to: ""})
opts[:date] = opts[:date].strftime("%d%m%Y") if opts[:date]
uri = URI.escape(opts.collect{|k,v| "#{k}=#{v}"}.join('&'))
"#{@url}?#{uri}"
end
class InvalidURL < StandardError
end
end | class PricesUrl
def initialize(url)
raise InvalidURL, "You must give an url, ie http://www.ns.nl/api" unless url
@url = url
end
def url (opts = {date: nil, from: "", to: ""})
opts[:date] = opts[:date].strftime("%d%m%Y") if opts[:date]
uri = URI.escape(opts.collect{|k,v| "#{k}=#{v}"}.join('&'))
"#{@url}?#{uri}"
end
class InvalidURL < StandardError
end
end
|
Add ability to inject a redis connection | module Carto
class GCloudUserSettings
REDIS_PREFIX = 'do_settings'
REDIS_KEYS = %i(service_account bq_public_project
gcp_execution_project bq_project bq_dataset
gcs_bucket).freeze
def initialize(username)
@username = username
end
def update(attributes)
if attributes.present?
store attributes
else
remove
end
end
def read
Hash[REDIS_KEYS.zip($users_metadata.hmget(key, *REDIS_KEYS))]
end
private
def store(attributes)
$users_metadata.hmset(key, *values(attributes).to_a)
end
def values(attributes)
attributes.symbolize_keys.slice(*REDIS_KEYS)
end
def remove
$users_metadata.del(key)
end
def key
"#{REDIS_PREFIX}:#{@username}"
end
end
end
| module Carto
class GCloudUserSettings
REDIS_PREFIX = 'do_settings'
REDIS_KEYS = %i(service_account bq_public_project
gcp_execution_project bq_project bq_dataset
gcs_bucket).freeze
def initialize(username, redis = $users_metadata)
@username = username
@redis = redis
end
def update(attributes)
if attributes.present?
store attributes
else
remove
end
end
def read
Hash[REDIS_KEYS.zip(@redis.hmget(key, *REDIS_KEYS))]
end
private
def store(attributes)
@redis.hmset(key, *values(attributes).to_a)
end
def values(attributes)
attributes.symbolize_keys.slice(*REDIS_KEYS)
end
def remove
@redis.del(key)
end
def key
"#{REDIS_PREFIX}:#{@username}"
end
end
end
|
Stop other sound from playing in tutorial | class TutorialController < UIViewController
include SoundsHelpers
def loadView
if finished_with_van_noorden?
@layout = TutorialLayoutMillerAndHeise.new
@type = :miller_and_heise
else
@layout = TutorialLayout.new
@sound1 = Tone.new('tutorial_1.wav')
@sound2 = Tone.new('tutorial_2.wav')
@type = :van_noorden
end
@sound1.finished_playing = Proc.new {NSLog "Finished"}
@sound2.finished_playing = Proc.new {NSLog "Finished"}
self.view = @layout.view
@one_button = @layout.play_one_button
@two_button = @layout.play_two_button
@start_button = @layout.start_button
end
def viewDidLoad
@one_button.when(UIControlEventTouchUpInside) {@sound1.play}
@two_button.when(UIControlEventTouchUpInside) {@sound2.play}
@start_button.when(UIControlEventTouchUpInside) do
if @type == :miller_and_heise
start_miller_and_heise_test
else
start_van_noorden_test
end
end
end
def shouldAutorotate
false
end
end
| class TutorialController < UIViewController
include SoundsHelpers
def loadView
if finished_with_van_noorden?
@layout = TutorialLayoutMillerAndHeise.new
@type = :miller_and_heise
else
@layout = TutorialLayout.new
@sound1 = Tone.new('tutorial_1.wav')
@sound2 = Tone.new('tutorial_2.wav')
@type = :van_noorden
end
@sound1.finished_playing = Proc.new {NSLog "Finished"}
@sound2.finished_playing = Proc.new {NSLog "Finished"}
self.view = @layout.view
@one_button = @layout.play_one_button
@two_button = @layout.play_two_button
@start_button = @layout.start_button
end
def viewDidLoad
@one_button.when(UIControlEventTouchUpInside) do
@sound2.stop if @sound2.is_playing?
@sound1.play
end
@two_button.when(UIControlEventTouchUpInside) do
@sound1.stop if @sound1.is_playing?
@sound2.play
end
@start_button.when(UIControlEventTouchUpInside) do
if @type == :miller_and_heise
start_miller_and_heise_test
else
start_van_noorden_test
end
end
end
def shouldAutorotate
false
end
end
|
Add 2 more service tests - sshd enabled - node_exporter disabled (enabled by confd) | require 'spec_helper'
# These shouldn't be enabled, our own startup logic starts it up
describe service('consul') do
it { should_not be_enabled }
end
# These should be enabled
describe service('confd') do
it { should be_enabled }
end
describe service('td-agent') do
it { should be_enabled }
end
describe service('ntpd') do
it { should be_enabled }
end
| require 'spec_helper'
# These shouldn't be enabled, our own startup logic starts it up
describe service('consul') do
it { should_not be_enabled }
end
describe service('node_exporter') do
it { should_not be_enabled }
end
# These should be enabled
describe service('sshd') do
it { should be_enabled }
end
describe service('confd') do
it { should be_enabled }
end
describe service('td-agent') do
it { should be_enabled }
end
describe service('ntpd') do
it { should be_enabled }
end
|
Allow mediawiki image reference by upload page name | class Blog < ApplicationRecord
include MyplaceonlineActiveRecordIdentityConcern
include AllowExistingConcern
def self.properties
[
{ name: :blog_name, type: ApplicationRecord::PROPERTY_TYPE_STRING },
{ name: :notes, type: ApplicationRecord::PROPERTY_TYPE_MARKDOWN },
{ name: :blog_files, type: ApplicationRecord::PROPERTY_TYPE_FILES },
{ name: :blog_posts, type: ApplicationRecord::PROPERTY_TYPE_CHILDREN },
]
end
validates :blog_name, presence: true
def display
blog_name
end
child_files
child_properties(name: :blog_posts, sort: "updated_at DESC")
def identity_file_by_name(name)
result = nil
name = name.downcase
Rails.logger.debug{"Blog.identity_file_by_name searching for: #{name}"}
self.blog_files.each do |blog_file|
checkname = blog_file.identity_file.file_file_name.downcase
i = checkname.rindex(".")
if !i.nil?
checkname = checkname[0..i-1]
end
Rails.logger.debug{"Blog.identity_file_by_name comparing: #{checkname}"}
if checkname == name
result = blog_file.identity_file
end
end
result
end
end
| class Blog < ApplicationRecord
include MyplaceonlineActiveRecordIdentityConcern
include AllowExistingConcern
def self.properties
[
{ name: :blog_name, type: ApplicationRecord::PROPERTY_TYPE_STRING },
{ name: :notes, type: ApplicationRecord::PROPERTY_TYPE_MARKDOWN },
{ name: :blog_files, type: ApplicationRecord::PROPERTY_TYPE_FILES },
{ name: :blog_posts, type: ApplicationRecord::PROPERTY_TYPE_CHILDREN },
]
end
validates :blog_name, presence: true
def display
blog_name
end
child_files
child_properties(name: :blog_posts, sort: "updated_at DESC")
def identity_file_by_name(name)
result = nil
name = name.downcase
name2 = name.gsub(" ", "_")
Rails.logger.debug{"Blog.identity_file_by_name searching for: #{name} or #{name2}"}
self.blog_files.each do |blog_file|
checkname = blog_file.identity_file.file_file_name.downcase
i = checkname.rindex(".")
if !i.nil?
checkname = checkname[0..i-1]
end
Rails.logger.debug{"Blog.identity_file_by_name comparing: #{checkname}"}
if checkname == name || checkname == name2
result = blog_file.identity_file
end
end
result
end
end
|
Add OmniGraffle 5 Standard cask | cask :v1 => 'omnigraffle5' do
version '5.4.4'
sha256 '7bcc64093f46bd4808b1a4cb86cf90c0380a5c5ffffd55ce8f742712818558df'
url "http://www.omnigroup.com/ftp/pub/software/MacOSX/10.6/OmniGraffle-#{version}.dmg"
homepage 'http://www.omnigroup.com/products/omnigraffle'
license :closed
app 'OmniGraffle 5.app'
end
| |
Use a nicer equation for load profile. | class LoadProfile < ActiveRecord::Base
belongs_to :city
validates_presence_of :hour
validates_presence_of :demand
validates :city, :presence => true
before_validation :calculate_demand, :on => :create
def to_s
"#{demand} MW @ #{hour}:00"
end
private
def calculate_demand
if (8..23).to_a.include? self.hour
# oversimplified parabola
self.demand = -0.1 * ((self.hour - 15) ** 2) + 4
end
end
end
| class LoadProfile < ActiveRecord::Base
belongs_to :city
validates_presence_of :hour
validates_presence_of :demand
validates :city, :presence => true
before_validation :calculate_demand, :on => :create
def to_s
"#{demand} MW @ #{hour}:00"
end
private
def calculate_demand
if (8..23).to_a.include? self.hour
# oversimplified parabola
self.demand = -0.1 * ((0.42 * self.hour - 5) ** 4) + 100
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.