Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add entities to the seed | i = 0
5.times do |x|
5.times do |y|
MapPoint.create!(x: x, y: y, zone: "Zone#{i}")
i += 1
end
end
| i = 0
5.times do |x|
5.times do |y|
map_point = MapPoint.create(x: x, y: y, zone: "Zone#{i}")
map_point.entities.build(name: "Test#{i}", description: "This is a simple description", map_point_id: map_point)
map_point.save
i += 1
end
end
|
Copy changes from another branch | class UsersController < ApplicationController
def new
@user = User.new
render 'new'
end
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
redirect_to '/'
else
p '8' * 88
p @user.errors.full_messages
render 'new'
end
end
def show
@user = User.find(params[:id])
end
def update
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :phone)
end
end
| class UsersController < ApplicationController
def new
@user = User.new
render 'new'
end
def create
@user = User.new(user_params)
if @user.save
redirect_to '/'
else
render 'new'
end
end
def show
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
# if @user.update()
end
def edit
@user = User.find(params[:id])
render "edit"
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :phone)
end
def topic_params
p"*"*90
p params.require(:user).permit(:topic1, :topic2, :topic3)
end
end
|
Add Method User's Full Name To User Model | class User < ActiveRecord::Base
authenticates_with_sorcery!
has_many :user_votes
has_many :items, through: :user_votes
validates :email, presence: true
validates :first_name, presence: true
validates :last_name, presence: true
validates :password, length: { minimum: 8 }, unless: :allow_to_validate
validates :password, confirmation: true
validates :password_confirmation, presence: true, on: :create, unless: :allow_to_validate
validates :email, uniqueness: true
def allow_to_validate
password.blank?
end
def has_no_votes?
user_votes.count == 0
end
end
| class User < ActiveRecord::Base
authenticates_with_sorcery!
has_many :user_votes
has_many :items, through: :user_votes
validates :email, presence: true
validates :first_name, presence: true
validates :last_name, presence: true
validates :password, length: { minimum: 8 }, unless: :allow_to_validate
validates :password, confirmation: true
validates :password_confirmation, presence: true, on: :create, unless: :allow_to_validate
validates :email, uniqueness: true
def display_full_name
"#{first_name} #{last_name}"
end
def allow_to_validate
password.blank?
end
def has_no_votes?
user_votes.count == 0
end
end
|
Add performance test for poller enqueue | # -*- encoding : utf-8 -*-
require './test/test_helper'
require 'benchmark'
describe 'Perfromance Poller' do
X = 10000
before do
Sidekiq.redis = REDIS
Sidekiq.redis do |conn|
conn.flushdb
end
#clear all previous saved data from redis
Sidekiq.redis do |conn|
conn.keys("cron_job*").each do |key|
conn.del(key)
end
end
args = {
queue: "default",
cron: "*/2 * * * *",
klass: "CronTestClass"
}
X.times do |i|
Sidekiq::Cron::Job.create(args.merge(name: "Test#{i}"))
end
@poller = Sidekiq::Cron::Poller.new
now = Time.now.utc
enqueued_time = Time.new(now.year, now.month, now.day, now.hour + 1, 10, 5)
Time.stubs(:now).returns(enqueued_time)
end
it 'should enqueue 10000 jobs in less than 30s' do
Sidekiq.redis do |conn|
assert_equal 0, conn.llen("queue:default"), 'Queue should be empty'
end
bench = Benchmark.measure {
@poller.enqueue
}
Sidekiq.redis do |conn|
assert_equal X, conn.llen("queue:default"), 'Queue should be full'
end
assert_operator 30, :>, bench.real
end
end
| |
Add caching of select filters' collections | module ActiveAdmin
module Inputs
module Filters
class SelectInput < ::Formtastic::Inputs::SelectInput
include Base
def input_name
return method if seems_searchable?
searchable_method_name + (multiple? ? '_in' : '_eq')
end
def searchable_method_name
if searchable_has_many_through?
"#{reflection.through_reflection.name}_#{reflection.foreign_key}"
else
name = method.to_s
name.concat '_id' if reflection
name
end
end
# Provide the AA translation to the blank input field.
def include_blank
I18n.t 'active_admin.any' if super
end
def input_html_options_name
"#{object_name}[#{input_name}]" # was "#{object_name}[#{association_primary_key}]"
end
# Would normally return true for has_many and HABTM, which would subsequently
# cause the select field to be multi-select instead of a dropdown.
def multiple_by_association?
false
end
# Provides an efficient default lookup query if the attribute is a DB column.
def collection
if !options[:collection] && column
pluck_column
else
super
end
end
def pluck_column
klass.reorder("#{method} asc").distinct.pluck method
end
end
end
end
end
| module ActiveAdmin
module Inputs
module Filters
class SelectInput < ::Formtastic::Inputs::SelectInput
include Base
def input_name
return method if seems_searchable?
searchable_method_name + (multiple? ? '_in' : '_eq')
end
def searchable_method_name
if searchable_has_many_through?
"#{reflection.through_reflection.name}_#{reflection.foreign_key}"
else
name = method.to_s
name.concat '_id' if reflection
name
end
end
# Provide the AA translation to the blank input field.
def include_blank
I18n.t 'active_admin.any' if super
end
def input_html_options_name
"#{object_name}[#{input_name}]" # was "#{object_name}[#{association_primary_key}]"
end
# Would normally return true for has_many and HABTM, which would subsequently
# cause the select field to be multi-select instead of a dropdown.
def multiple_by_association?
false
end
# Provides an efficient default lookup query if the attribute is a DB column.
def collection
cache_on_demand do
if !options[:collection] && column
pluck_column
else
super
end
end
end
def pluck_column
klass.reorder("#{method} asc").distinct.pluck method
end
def cache_on_demand(&block)
if options[:cache]
cache_name = "#{klass.name}/#{method}"
cache_name = "#{cache_name}/#{options[:cache_key].call}" if options[:cache_key]
cache_filter(cache_name, &block)
else
yield
end
end
end
end
end
end
|
Check if callback url param is valid | module Parametrizer
module Parsers
class CallbackUrlParser
attr_accessor :call_back_url
def initialize(request_params)
@call_back_url = request_params['call_back_url']
end
end
end
end | module Parametrizer
module Parsers
class CallbackUrlParser
attr_accessor :call_back_url
def initialize(request_params)
@call_back_url = ( request_params['call_back_url'] =~ URI::regexp ).present? ? request_params['call_back_url'] : nil
end
end
end
end |
Fix bug trying to delete figure | class FiguresController < ApplicationController
rescue_from ActiveRecord::RecordNotFound, with: :render_404
before_action :authenticate_user!
def create
figures = Array.wrap(figure_params.delete(:attachment))
figures.select! {|f| Figure.acceptable_content_type? f.content_type }
new_figures = figures.map do |figure|
paper.figures.create(figure_params.merge(attachment: figure))
end
respond_to do |f|
f.html { redirect_to edit_paper_path paper }
f.json { render json: new_figures }
end
end
def destroy
if paper_policy.paper.present?
paper.figures.find(params[:id]).destroy
head :ok
else
head :forbidden
end
end
private
def paper
@paper ||= begin
paper_policy.paper.tap do |p|
raise ActiveRecord::RecordNotFound unless p.present?
end
end
end
def paper_policy
@paper_policy ||= PaperPolicy.new(params[:paper_id], current_user)
end
def figure_params
params.require(:figure).permit(:attachment, attachment: [])
end
def render_404
return head 404
end
end
| class FiguresController < ApplicationController
rescue_from ActiveRecord::RecordNotFound, with: :render_404
before_action :authenticate_user!
def create
figures = Array.wrap(figure_params.delete(:attachment))
figures.select! {|f| Figure.acceptable_content_type? f.content_type }
new_figures = figures.map do |figure|
paper.figures.create(figure_params.merge(attachment: figure))
end
respond_to do |f|
f.html { redirect_to edit_paper_path paper }
f.json { render json: new_figures }
end
end
def destroy
if paper_policy.paper.present?
paper.figures.find(params[:id]).destroy
head :ok
else
head :forbidden
end
end
private
def paper
@paper ||= begin
paper_policy.paper.tap do |p|
raise ActiveRecord::RecordNotFound unless p.present?
end
end
end
def paper_policy
@paper_policy ||= PaperPolicy.new(params[:paper_id].presence || figure_paper.id, current_user)
end
def figure_paper
Figure.find(params[:id]).paper
end
def figure_params
params.require(:figure).permit(:attachment, attachment: [])
end
def render_404
return head 404
end
end
|
Use @all_events to build XML results | xml.instruct!
xml.events do
(@weekly_series + @events + @competitions).each do |event|
xml.event do
xml.id event.id
xml.name event.full_name
xml.date event.date
end
end
end
| xml.instruct!
xml.events do
(@all_events).each do |event|
xml.event do
xml.id event.id
xml.name event.full_name
xml.date event.date
end
end
end
|
Fix circular argument reference warning | module SVGPath
# Capital letters means absolutely positioned, lower cases means relatively positioned.
COMMANDS = {
moveto: "M",
lineto: "L",
horizontal_lineto: "H",
vertical_lineto: "V",
curveto: "C",
smooth_curveto: "S",
quadratic_bezier_curve: "Q",
smooth_quadratic_bezier_curveto: "T",
elliptical_arc: "A",
closepath: "Z"
}
module Absolute
def self.elliptical_arc(rx:, ry:, x_axis_rotation: 0, large_arc_flag: 0, sweep_flag: 0, x:, y:, opts: {})
data = [rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, x, y].join(" ")
[COMMANDS.fetch(:elliptical_arc), data]
end
def self.circular_arc(r: r, x_axis_rotation: 0, large_arc_flag: 0, sweep_flag: 0, x:, y:, opts: {})
elliptical_arc(rx: r,
ry: r,
x_axis_rotation: x_axis_rotation,
large_arc_flag: large_arc_flag,
sweep_flag: sweep_flag,
x: x,
y: y,
opts: opts)
end
def self.move_to(x:, y:)
[COMMANDS.fetch(:moveto), x, ",", y]
end
end
end
| module SVGPath
# Capital letters means absolutely positioned, lower cases means relatively positioned.
COMMANDS = {
moveto: "M",
lineto: "L",
horizontal_lineto: "H",
vertical_lineto: "V",
curveto: "C",
smooth_curveto: "S",
quadratic_bezier_curve: "Q",
smooth_quadratic_bezier_curveto: "T",
elliptical_arc: "A",
closepath: "Z"
}
module Absolute
def self.elliptical_arc(rx:, ry:, x_axis_rotation: 0, large_arc_flag: 0, sweep_flag: 0, x:, y:, opts: {})
data = [rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, x, y].join(" ")
[COMMANDS.fetch(:elliptical_arc), data]
end
def self.circular_arc(r:, x_axis_rotation: 0, large_arc_flag: 0, sweep_flag: 0, x:, y:, opts: {})
elliptical_arc(rx: r,
ry: r,
x_axis_rotation: x_axis_rotation,
large_arc_flag: large_arc_flag,
sweep_flag: sweep_flag,
x: x,
y: y,
opts: opts)
end
def self.move_to(x:, y:)
[COMMANDS.fetch(:moveto), x, ",", y]
end
end
end
|
Add code comments to CSP config | SecureHeaders::Configuration.default do |config|
# Unblock PDF downloading for student report
config.x_download_options = nil
config.csp = {
default_src: %w('self' https:),
script_src: %w(https:),
object_src: %w('self')
}
# Turn off Content Security Policy (CSP) rules for development and test envs
if Rails.env.test? || Rails.env.development?
config.csp = SecureHeaders::OPT_OUT
config.cookies = SecureHeaders::OPT_OUT
end
end
| SecureHeaders::Configuration.default do |config|
# Unblock PDF downloading for student report
config.x_download_options = nil
config.csp = {
default_src: %w('self' https:), # This is the same as Configuration.default.
# SecureHeaders requires a non-nil default_src csp.
script_src: %w(https:), # This is the same as Configuration.default.
# SecureHeaders requires a non-nil script_src csp.
object_src: %w('self') # This is more lenient than Configuration.default.
# This enables viewing the Student Report PDF.
}
# Turn off Content Security Policy (CSP) rules for development and test envs
if Rails.env.test? || Rails.env.development?
config.csp = SecureHeaders::OPT_OUT
config.cookies = SecureHeaders::OPT_OUT
end
end
|
Use admin endpoint for get_network | module Fog
module Compute
class VcloudDirector
class Real
# Retrieve an organization network.
#
# @param [String] id Object identifier of the network.
# @return [Excon::Response]
# * body<~Hash>:
#
# @raise [Fog::Compute::VcloudDirector::Forbidden]
#
# @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-Network.html
# @since vCloud API version 0.9
def get_network_complete(id)
request(
:expects => 200,
:idempotent => true,
:method => 'GET',
:parser => Fog::ToHashDocument.new,
:path => "network/#{id}"
)
end
end
class Mock
def get_network_complete(id)
unless network = data[:networks][id]
raise Fog::Compute::VcloudDirector::Forbidden.new(
'This operation is denied.'
)
end
Fog::Mock.not_implemented
end
end
end
end
end
| module Fog
module Compute
class VcloudDirector
class Real
# Retrieve an organization network.
#
# @param [String] id Object identifier of the network.
# @return [Excon::Response]
# * body<~Hash>:
#
# @raise [Fog::Compute::VcloudDirector::Forbidden]
#
# @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-Network.html
# @since vCloud API version 0.9
def get_network_complete(id)
request(
:expects => 200,
:idempotent => true,
:method => 'GET',
:parser => Fog::ToHashDocument.new,
:path => "admin/network/#{id}"
)
end
end
class Mock
def get_network_complete(id)
unless network = data[:networks][id]
raise Fog::Compute::VcloudDirector::Forbidden.new(
'This operation is denied.'
)
end
Fog::Mock.not_implemented
end
end
end
end
end
|
Remove refunded paymentDetails from ExpenseItem export | class Exporters::PaymentDetailsExporter
attr_accessor :expense_item
def initialize(expense_item)
@expense_item = expense_item
end
def headers
[
"Expense Item",
"Details: #{expense_item.details_label}",
"Id",
"First Name",
"Last Name",
"Age",
"City",
"State",
"Country of Residence",
"Country Representing",
"Email",
"Club",
"Free with registration?"
]
end
def rows
data = []
expense_item.payment_details.includes(:payment).each do |payment_detail|
next unless payment_detail.payment.completed
data << add_element(payment_detail, "No")
end
expense_item.free_items_with_reg_paid.each do |registrant_expense_item|
data << add_element(registrant_expense_item, "Yes")
end
data
end
private
def add_element(element, free_with_reg)
reg = element.registrant
[
element.expense_item.to_s,
element.details,
reg.bib_number,
reg.first_name,
reg.last_name,
reg.age,
reg.contact_detail.city,
reg.contact_detail.state,
reg.contact_detail.country_residence,
reg.contact_detail.country_representing,
reg.contact_detail.email,
reg.club,
free_with_reg
]
end
end
| class Exporters::PaymentDetailsExporter
attr_accessor :expense_item
def initialize(expense_item)
@expense_item = expense_item
end
def headers
[
"Expense Item",
"Details: #{expense_item.details_label}",
"Id",
"First Name",
"Last Name",
"Age",
"City",
"State",
"Country of Residence",
"Country Representing",
"Email",
"Club",
"Free with registration?"
]
end
def rows
data = []
expense_item.payment_details.includes(:payment).each do |payment_detail|
next unless payment_detail.payment.completed
next if payment_detail.refunded?
data << add_element(payment_detail, "No")
end
expense_item.free_items_with_reg_paid.each do |registrant_expense_item|
data << add_element(registrant_expense_item, "Yes")
end
data
end
private
def add_element(element, free_with_reg)
reg = element.registrant
[
element.expense_item.to_s,
element.details,
reg.bib_number,
reg.first_name,
reg.last_name,
reg.age,
reg.contact_detail.city,
reg.contact_detail.state,
reg.contact_detail.country_residence,
reg.contact_detail.country_representing,
reg.contact_detail.email,
reg.club,
free_with_reg
]
end
end
|
Use order.currency instead of fixed value | class PayuOrder
include Rails.application.routes.url_helpers
def self.params(order, ip, order_url, notify_url, continue_url)
products = order.line_items.map do |li|
{
name: li.product.name,
unit_price: (li.price * 100).to_i,
quantity: li.quantity
}
end
description = I18n.t('order_description',
name: Spree::Config.site_name)
description = I18n.transliterate(description)
{
merchant_pos_id: OpenPayU::Configuration.merchant_pos_id,
customer_ip: ip,
ext_order_id: order.id,
description: description,
currency_code: 'PLN',
total_amount: (order.total * 100).to_i,
order_url: order_url,
notify_url: notify_url,
continue_url: continue_url,
buyer: {
email: order.email,
phone: order.bill_address.phone,
first_name: order.bill_address.firstname,
last_name: order.bill_address.lastname,
language: 'PL',
delivery: {
street: order.shipping_address.address1,
postal_code: order.shipping_address.zipcode,
city: order.shipping_address.city,
country_code: order.bill_address.country.iso
}
},
products: products
}
end
end
| class PayuOrder
include Rails.application.routes.url_helpers
def self.params(order, ip, order_url, notify_url, continue_url)
products = order.line_items.map do |li|
{
name: li.product.name,
unit_price: (li.price * 100).to_i,
quantity: li.quantity
}
end
description = I18n.t('order_description',
name: Spree::Config.site_name)
description = I18n.transliterate(description)
{
merchant_pos_id: OpenPayU::Configuration.merchant_pos_id,
customer_ip: ip,
ext_order_id: order.id,
description: description,
currency_code: order.currency,
total_amount: (order.total * 100).to_i,
order_url: order_url,
notify_url: notify_url,
continue_url: continue_url,
buyer: {
email: order.email,
phone: order.bill_address.phone,
first_name: order.bill_address.firstname,
last_name: order.bill_address.lastname,
language: 'PL',
delivery: {
street: order.shipping_address.address1,
postal_code: order.shipping_address.zipcode,
city: order.shipping_address.city,
country_code: order.bill_address.country.iso
}
},
products: products
}
end
end
|
Add site cookbook for jenkins | #
# Cookbook Name:: jenkins
# Recipe:: _proxy_apache2
#
# Author:: Fletcher Nichol <fnichol@nichol.ca>
#
# Copyright 2011, Fletcher Nichol
#
# 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.
#
include_recipe 'apache2::default'
www_redirect = (node['jenkins']['http_proxy']['www_redirect'] == 'enable')
host_name = node['jenkins']['http_proxy']['host_name'] || node['fqdn']
if node['jenkins']['http_proxy']['cas_validate_server'] == 'cas'
apache_module 'mod_auth_cas'
end
if node['jenkins']['http_proxy']['ssl']['enabled']
include_recipe 'apache2::mod_ssl'
end
apache_module 'proxy'
apache_module 'proxy_http'
apache_module 'vhost_alias'
if www_redirect || node['jenkins']['http_proxy']['ssl']['redirect_http']
apache_module 'rewrite'
end
template "#{node['apache']['dir']}/htpasswd" do
variables(:username => node['jenkins']['http_proxy']['basic_auth_username'],
:password => node['jenkins']['http_proxy']['basic_auth_password'])
owner node['apache']['user']
group node['apache']['user']
mode '0600'
end
template "#{node['apache']['dir']}/sites-available/jenkins" do
source 'apache_jenkins.erb'
owner 'root'
group 'root'
mode '0644'
variables(
:host_name => host_name,
:www_redirect => www_redirect
)
if File.exists?("#{node['apache']['dir']}/sites-enabled/jenkins")
notifies :restart, 'service[apache2]'
end
end
apache_site '000-default' do
enable false
end
apache_site 'jenkins' do
enable true
end
| |
Add script to separate enrollments by renewal/initial | # Takes a list of enrollment group IDs in an array and filters them into initial and shop renewals.
eg_ids = %w()
policies = Policy.where(:eg_id => {"$in" => eg_ids})
found = policies.map(&:eg_id)
not_found = eg_ids - found
def renewal_or_initial(policy)
if policy.transaction_set_enrollments.any?{|tse| tse.transaction_kind == "initial_enrollment"}
return "initial"
else
return "renewal"
end
end
renewal_enrollments = []
initial_enrollments = []
policies.each do |pol|
result = renewal_or_initial(pol)
if result == "initial"
initial_enrollments << pol
elsif result == "renewal"
renewal_enrollments << pol
end
end
initial_enrollments.sort!
renewal_enrollments.sort!
initial_en = File.new("initial_enrollments.txt","w")
initial_enrollments.each do |ie|
initial_en.puts(ie.eg_id)
end
renewal_en = File.new("renewal_enrollments.txt","w")
renewal_enrollments.each do |re|
renewal_en.puts(re.eg_id)
end
not_found_file = File.new("enrollment_not_found.txt","w")
not_found.each do |nf|
not_found_file.puts(nf)
end | |
Add Gosu to gemspec. Add myself to authors. | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'nyan/version'
Gem::Specification.new do |spec|
spec.name = "nyan"
spec.version = Nyan::VERSION
spec.authors = ["Alex Coco"]
spec.email = ["alex.coco@shopify.com"]
spec.description = %q{Nyan cat game in Ruby with Gosu}
spec.summary = %q{Nyan cat game}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'nyan/version'
Gem::Specification.new do |spec|
spec.name = "nyan"
spec.version = Nyan::VERSION
spec.authors = ["Alex Coco", "Antoine Grondin"]
spec.email = ["alex.coco@shopify.com", "antoine.grondin@shopify.com"]
spec.description = %q{Nyan cat game in Ruby with Gosu}
spec.summary = %q{Nyan cat game}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_dependency "gosu", "~> 0.7"
end
|
Add solution to ruby file | first_name = "Liz"
last_name = "Roche"
age = 26
describe 'first_name' do
it "is defined as a local variable" do
expect(defined?(first_name)).to eq 'local-variable'
end
it "is a String" do
expect(first_name).to be_a String
end
end
describe 'last_name' do
it "is defined as a local variable" do
expect(defined?(last_name)).to eq 'local-variable'
end
it "be a String" do
expect(last_name).to be_a String
end
end
describe 'age' do
it "is defined as a local variable" do
expect(defined?(age)).to eq 'local-variable'
end
it "is an integer" do
expect(age).to be_a Fixnum
end
end | |
Revert "Bump to 0.1.2 after file rename" | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "rspec-hue"
spec.version = '0.1.2'
spec.authors = ["larskrantz"]
spec.email = ["lars.krantz@alaz.se"]
spec.description = %q{Light up philips hue when testing}
spec.summary = %q{Let Hue indicate if tests are passing or not}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.required_ruby_version = Gem::Requirement.new(">=1.9.3")
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_runtime_dependency "rspec"
spec.add_runtime_dependency "huey"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "rspec-hue"
spec.version = '0.1.1'
spec.authors = ["larskrantz"]
spec.email = ["lars.krantz@alaz.se"]
spec.description = %q{Light up philips hue when testing}
spec.summary = %q{Let Hue indicate if tests are passing or not}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.required_ruby_version = Gem::Requirement.new(">=1.9.3")
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_runtime_dependency "rspec"
spec.add_runtime_dependency "huey"
end
|
Fix source files in podspec | Pod::Spec.new do |spec|
spec.name = 'Publinks'
spec.version = '0.1.0'
spec.summary = 'Safe, simple publish-subscribe in Swift'
spec.homepage = 'https://github.com/remarkableio/Publinks'
spec.license = { :type => 'MIT', :file => 'LICENSE' }
spec.author = {
'Giles Van Gruisen' => 'giles@vangruisen.com',
}
spec.source = { :git => 'https://github.com/remarkableio/Publinks.git', :tag => "v#{spec.version}" }
spec.source_files = 'Source/**/*.{h,swift}'
spec.requires_arc = true
spec.ios.deployment_target = '8.0'
end | Pod::Spec.new do |spec|
spec.name = 'Publinks'
spec.version = '0.1.0'
spec.summary = 'Safe, simple publish-subscribe in Swift'
spec.homepage = 'https://github.com/remarkableio/Publinks'
spec.license = { :type => 'MIT', :file => 'LICENSE' }
spec.author = {
'Giles Van Gruisen' => 'giles@vangruisen.com',
}
spec.source = { :git => 'https://github.com/remarkableio/Publinks.git', :tag => "v#{spec.version}" }
spec.source_files = '**/*.{h,swift}'
spec.requires_arc = true
spec.ios.deployment_target = '8.0'
end |
Add `secret` column to Settings | # frozen_string_literal: true
#
# Copyright (C) 2022 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
class AddSecretToSettings < ActiveRecord::Migration[6.0]
tag :predeploy
def change
add_column :settings, :secret, :boolean, default: false, null: false, if_not_exists: true
end
end
| |
Use :manual_ack as a more descriptive name | #!/usr/bin/env ruby
# encoding: utf-8
require "bunny"
conn = Bunny.new
conn.start
ch = conn.create_channel
q = ch.queue("task_queue", :durable => true)
ch.prefetch(1)
puts " [*] Waiting for messages. To exit press CTRL+C"
begin
q.subscribe(:ack => true, :block => true) do |delivery_info, properties, body|
puts " [x] Received '#{body}'"
# imitate some work
sleep 1.0
puts " [x] Done"
ch.ack(delivery_info.delivery_tag)
end
rescue Interrupt => _
conn.close
end
| #!/usr/bin/env ruby
# encoding: utf-8
require "bunny"
conn = Bunny.new
conn.start
ch = conn.create_channel
q = ch.queue("task_queue", :durable => true)
ch.prefetch(1)
puts " [*] Waiting for messages. To exit press CTRL+C"
begin
q.subscribe(:manual_ack => true, :block => true) do |delivery_info, properties, body|
puts " [x] Received '#{body}'"
# imitate some work
sleep 1.0
puts " [x] Done"
ch.ack(delivery_info.delivery_tag)
end
rescue Interrupt => _
conn.close
end
|
Add spec for automatic logout after specified time period | require 'rails_helper'
RSpec.describe "login timeout", type: :request, csrf: false do
let(:user_attributes) do
{
first_name: "System",
last_name: "Administrator",
email: "admin@petition.parliament.uk",
password: "L3tme1n!",
password_confirmation: "L3tme1n!"
}
end
let(:login_params) do
{ email: "admin@petition.parliament.uk", password: "L3tme1n!" }
end
let!(:user) { FactoryGirl.create(:sysadmin_user, user_attributes) }
before do
host! "moderate.petition.parliament.uk"
https!
end
it "logs out automatically after a certain time period" do
Site.instance.update(login_timeout: 600)
travel_to 2.minutes.ago do
post "/admin/user_sessions", admin_user_session: login_params
expect(response).to redirect_to("/admin")
end
get "/admin"
expect(response).to be_successful
travel_to 10.minutes.from_now do
get "/admin"
expect(response).to redirect_to("/admin/login")
end
end
end
| |
Remove tzinfo dependency from Action Pack | version = File.read(File.expand_path('../../RAILS_VERSION', __FILE__)).strip
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'actionpack'
s.version = version
s.summary = 'Web-flow and rendering framework putting the VC in MVC (part of Rails).'
s.description = 'Web apps on Rails. Simple, battle-tested conventions for building and testing MVC web applications. Works with any Rack-compatible server.'
s.required_ruby_version = '>= 1.9.3'
s.license = 'MIT'
s.author = 'David Heinemeier Hansson'
s.email = 'david@loudthinking.com'
s.homepage = 'http://www.rubyonrails.org'
s.files = Dir['CHANGELOG.md', 'README.rdoc', 'MIT-LICENSE', 'lib/**/*']
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'activesupport', version
s.add_dependency 'rack', '~> 1.5.2'
s.add_dependency 'rack-test', '~> 0.6.2'
s.add_development_dependency 'actionview', version
s.add_development_dependency 'activemodel', version
s.add_development_dependency 'tzinfo', '~> 0.3.37'
end
| version = File.read(File.expand_path('../../RAILS_VERSION', __FILE__)).strip
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'actionpack'
s.version = version
s.summary = 'Web-flow and rendering framework putting the VC in MVC (part of Rails).'
s.description = 'Web apps on Rails. Simple, battle-tested conventions for building and testing MVC web applications. Works with any Rack-compatible server.'
s.required_ruby_version = '>= 1.9.3'
s.license = 'MIT'
s.author = 'David Heinemeier Hansson'
s.email = 'david@loudthinking.com'
s.homepage = 'http://www.rubyonrails.org'
s.files = Dir['CHANGELOG.md', 'README.rdoc', 'MIT-LICENSE', 'lib/**/*']
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'activesupport', version
s.add_dependency 'rack', '~> 1.5.2'
s.add_dependency 'rack-test', '~> 0.6.2'
s.add_development_dependency 'actionview', version
s.add_development_dependency 'activemodel', version
end
|
Package version is increased from 0.6.0.0 to 0.6.0.1 | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'schema'
s.summary = "Primitives for schema and structure"
s.version = '0.6.0.0'
s.description = ' '
s.authors = ['The Eventide Project']
s.email = 'opensource@eventide-project.org'
s.homepage = 'https://github.com/eventide-project/schema'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.add_runtime_dependency 'attribute'
s.add_runtime_dependency 'set_attributes'
s.add_runtime_dependency 'validate'
s.add_runtime_dependency 'virtual'
s.add_development_dependency 'test_bench'
end
| # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'schema'
s.summary = "Primitives for schema and structure"
s.version = '0.6.0.1'
s.description = ' '
s.authors = ['The Eventide Project']
s.email = 'opensource@eventide-project.org'
s.homepage = 'https://github.com/eventide-project/schema'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.add_runtime_dependency 'attribute'
s.add_runtime_dependency 'set_attributes'
s.add_runtime_dependency 'validate'
s.add_runtime_dependency 'virtual'
s.add_development_dependency 'test_bench'
end
|
Add rake gem as dependency | # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'skooby/version'
Gem::Specification.new do |gem|
gem.name = "skooby"
gem.version = Skooby::VERSION
gem.authors = ["Irio Irineu Musskopf Junior"]
gem.email = ["irio.musskopf@caixadeideias.com.br"]
gem.description = "API like interface to provide information about books available at Skoob."
gem.summary = "Gives you some API like's methods to access Skoob data."
gem.homepage = "https://github.com/Irio/skooby"
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_development_dependency "minitest"
gem.add_development_dependency "mocha"
gem.add_development_dependency "vcr"
gem.add_dependency "httparty"
gem.add_dependency "nokogiri"
end
| # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'skooby/version'
Gem::Specification.new do |gem|
gem.name = "skooby"
gem.version = Skooby::VERSION
gem.authors = ["Irio Irineu Musskopf Junior"]
gem.email = ["irio.musskopf@caixadeideias.com.br"]
gem.description = "API like interface to provide information about books available at Skoob."
gem.summary = "Gives you some API like's methods to access Skoob data."
gem.homepage = "https://github.com/Irio/skooby"
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_dependency "rake"
gem.add_dependency "httparty"
gem.add_dependency "nokogiri"
gem.add_development_dependency "minitest"
gem.add_development_dependency "mocha"
gem.add_development_dependency "vcr"
end
|
Modify secure headers' CSP values to permit use of Fastly CDN | SecureHeaders::Configuration.default do |config|
config.hsts = "max-age=#{20.years.to_i}"
config.x_frame_options = 'DENY'
config.x_content_type_options = 'nosniff'
config.x_xss_protection = '1; mode=block'
config.x_download_options = 'noopen'
config.x_permitted_cross_domain_policies = 'none'
# Configure CSP
config.csp = {
default_src: %w('self'),
img_src: %w('self'),
object_src: %w('self'),
# Unfortunately, we can't be as strong as we want to be.
# If we make this just 'self' then the auto-size of vertical textareas
# doesn't work, and Firefox reports
# "Content Security Policy: The page's settings blocked the loading
# of a resource at self ('default-src http://localhost:3000')
# There are probably other functions that also don't work.
script_src: %w('self' 'unsafe-eval' 'unsafe-inline'),
style_src: %w('self' 'unsafe-inline')
}
# Not using Public Key Pinning Extension for HTTP (HPKP).
# Yes, it can counter some attacks, but it can also cause a lot of problems;
# one wrong move can render the site useless, and it makes it hard to
# switch CAs if the CA behaves badly.
end
| SecureHeaders::Configuration.default do |config|
normal_src = %w('self')
if ENV['PUBLIC_HOSTNAME']
fastly_alternate = 'https://' + ENV['PUBLIC_HOSTNAME'] +
'.global.ssl.fastly.net'
normal_src += [fastly_alternate]
end
config.hsts = "max-age=#{20.years.to_i}"
config.x_frame_options = 'DENY'
config.x_content_type_options = 'nosniff'
config.x_xss_protection = '1; mode=block'
config.x_download_options = 'noopen'
config.x_permitted_cross_domain_policies = 'none'
# Configure CSP
config.csp = {
default_src: normal_src,
img_src: normal_src,
object_src: normal_src,
# Unfortunately, we can't be as strong as we want to be.
# If we make this just 'self' then the auto-size of vertical textareas
# doesn't work, and Firefox reports
# "Content Security Policy: The page's settings blocked the loading
# of a resource at self ('default-src http://localhost:3000')
# There are probably other functions that also don't work.
script_src: normal_src + %w('unsafe-eval' 'unsafe-inline'),
style_src: normal_src + %w('unsafe-inline')
}
# Not using Public Key Pinning Extension for HTTP (HPKP).
# Yes, it can counter some attacks, but it can also cause a lot of problems;
# one wrong move can render the site useless, and it makes it hard to
# switch CAs if the CA behaves badly.
end
|
Change from tab to two spaces | # VttUploader class
class VttUploader < Shrine
plugin :pretty_location
plugin :determine_mime_type
end | # VttUploader class
class VttUploader < Shrine
plugin :pretty_location
plugin :determine_mime_type
end |
Revert "remove (markdown) parsing for questions in tweets" | class Services::Twitter < Service
include Rails.application.routes.url_helpers
include MarkdownHelper
def provider
"twitter"
end
def post(answer)
Rails.logger.debug "posting to Twitter {'answer' => #{answer.id}, 'user' => #{self.user_id}}"
post_tweet answer
end
private
def client
@client ||= Twitter::REST::Client.new(
consumer_key: APP_CONFIG['sharing']['twitter']['consumer_key'],
consumer_secret: APP_CONFIG['sharing']['twitter']['consumer_secret'],
access_token: self.access_token,
access_token_secret: self.access_secret
)
end
def post_tweet(answer)
client.update! prepare_tweet(answer)
end
def prepare_tweet(answer)
# TODO: improve this.
question_content = answer.question.content
answer_content = twitter_markdown answer.content
answer_url = show_user_answer_url(
id: answer.id,
username: answer.user.screen_name,
host: APP_CONFIG['hostname'],
protocol: (APP_CONFIG['https'] ? :https : :http)
)
"#{question_content[0..54]}#{'โฆ' if question_content.length > 55}" \
" โ #{answer_content[0..55]}#{'โฆ' if answer_content.length > 56} #{answer_url}"
end
end
| class Services::Twitter < Service
include Rails.application.routes.url_helpers
include MarkdownHelper
def provider
"twitter"
end
def post(answer)
Rails.logger.debug "posting to Twitter {'answer' => #{answer.id}, 'user' => #{self.user_id}}"
post_tweet answer
end
private
def client
@client ||= Twitter::REST::Client.new(
consumer_key: APP_CONFIG['sharing']['twitter']['consumer_key'],
consumer_secret: APP_CONFIG['sharing']['twitter']['consumer_secret'],
access_token: self.access_token,
access_token_secret: self.access_secret
)
end
def post_tweet(answer)
client.update! prepare_tweet(answer)
end
def prepare_tweet(answer)
# TODO: improve this.
question_content = twitter_markdown answer.question.content
answer_content = twitter_markdown answer.content
answer_url = show_user_answer_url(
id: answer.id,
username: answer.user.screen_name,
host: APP_CONFIG['hostname'],
protocol: (APP_CONFIG['https'] ? :https : :http)
)
"#{question_content[0..54]}#{'โฆ' if question_content.length > 55}" \
" โ #{answer_content[0..55]}#{'โฆ' if answer_content.length > 56} #{answer_url}"
end
end |
Check that we have results before returning a value | # Make python versions available as facts
def get_python_version(executable)
if Facter::Util::Resolution.which(executable)
Facter::Util::Resolution.exec("#{executable} -V 2>&1").match(/^.*(\d+\.\d+\.\d+)$/)[1]
end
end
Facter.add("python_version") do
setcode do
get_python_version 'python'
end
end
Facter.add("python2_version") do
setcode do
default_version = get_python_version 'python'
if default_version.nil? or !default_version.start_with?('2')
get_python_version 'python2'
else
default_version
end
end
end
Facter.add("python3_version") do
setcode do
get_python_version 'python3'
end
end
| # Make python versions available as facts
def get_python_version(executable)
if Facter::Util::Resolution.which(executable)
results = Facter::Util::Resolution.exec("#{executable} -V 2>&1").match(/^.*(\d+\.\d+\.\d+)$/)
if results
results[1]
end
end
end
Facter.add("python_version") do
setcode do
get_python_version 'python'
end
end
Facter.add("python2_version") do
setcode do
default_version = get_python_version 'python'
if default_version.nil? or !default_version.start_with?('2')
get_python_version 'python2'
else
default_version
end
end
end
Facter.add("python3_version") do
setcode do
get_python_version 'python3'
end
end
|
Allow GW_ prefixed env variables to override the sudo env. | module GitWit
module Commands
module Util
def exec_with_sudo!(user = app_user)
return if running_as?(user)
Dir.chdir rails_root
ENV["TERM"] = "dumb"
cmd = ["sudo", "-u", "##{user}", $PROGRAM_NAME, *ARGV]
exec *cmd
end
def running_as?(user)
Process.uid == user
end
def app_user
File.stat(rails_root).uid
end
def rails_root
return File.expand_path(ENV["RAILS_ROOT"]) if ENV["RAILS_ROOT"]
return Dir.pwd if File.exist? File.join(Dir.pwd, "config/environment.rb")
return File.expand_path("..", ENV["BUNDLE_GEMFILE"]) if ENV["BUNDLE_GEMFILE"]
Dir.pwd
end
def boot_app
require File.expand_path File.join(rails_root, "config/environment") unless booted?
require "git_wit"
end
def booted?
defined?(Rails)
end
end
end
end | module GitWit
module Commands
module Util
def exec_with_sudo!(user = app_user)
return if running_as?(user)
Dir.chdir rails_root
ENV["TERM"] = "dumb"
load_gw_env
cmd = ["sudo", "-u", "##{user}", $PROGRAM_NAME, *ARGV]
exec *cmd
end
def load_gw_env
ENV.keys.each { |k| ENV[k.gsub /^GW_/, ""] = ENV[k] if k.start_with? "GW_" }
end
def running_as?(user)
Process.uid == user
end
def app_user
File.stat(rails_root).uid
end
def rails_root
return File.expand_path(ENV["RAILS_ROOT"]) if ENV["RAILS_ROOT"]
return Dir.pwd if File.exist? File.join(Dir.pwd, "config/environment.rb")
return File.expand_path("..", ENV["BUNDLE_GEMFILE"]) if ENV["BUNDLE_GEMFILE"]
Dir.pwd
end
def boot_app
require File.expand_path File.join(rails_root, "config/environment") unless booted?
require "git_wit"
end
def booted?
defined?(Rails)
end
end
end
end |
Fix hutch broker handler errors | require 'bunny'
module Hutch
module BrokerHandlers
def with_authentication_error_handler
yield
rescue Net::HTTPServerException => ex
logger.error "HTTP API connection error: #{ex.message.downcase}"
if ex.response.code == '401'
raise AuthenticationError, 'invalid HTTP API credentials'
else
raise
end
end
def with_connection_error_handler
yield
rescue Errno::ECONNREFUSED => ex
logger.error "HTTP API connection error: #{ex.message.downcase}"
raise ConnectionError, "couldn't connect to HTTP API at #{api_config.sanitized_uri}"
end
def with_bunny_precondition_handler(item)
yield
rescue Bunny::PreconditionFailed => ex
logger.error ex.message
s = "RabbitMQ responded with 406 Precondition Failed when creating this #{item}. " \
'Perhaps it is being redeclared with non-matching attributes'
raise WorkerSetupError, s
end
def with_bunny_connection_handler(uri)
yield
rescue Bunny::TCPConnectionFailed => ex
logger.error "amqp connection error: #{ex.message.downcase}"
raise ConnectionError, "couldn't connect to rabbitmq at #{uri}. Check your configuration, network connectivity and RabbitMQ logs."
end
end
end
| require 'bunny'
module Hutch
module BrokerHandlers
def with_authentication_error_handler
yield
rescue Net::HTTPServerException => ex
logger.error "HTTP API connection error: #{ex.message.downcase}"
if ex.response.code == '401'
raise AuthenticationError, 'invalid HTTP API credentials'
else
raise
end
end
def with_connection_error_handler
yield
rescue Errno::ECONNREFUSED => ex
logger.error "HTTP API connection error: #{ex.message.downcase}"
raise ConnectionError, "couldn't connect to HTTP API at #{api_config.sanitized_uri}"
end
def with_bunny_precondition_handler(item)
yield
rescue Hutch::Adapter::PreconditionFailed => ex
logger.error ex.message
s = "RabbitMQ responded with 406 Precondition Failed when creating this #{item}. " \
'Perhaps it is being redeclared with non-matching attributes'
raise WorkerSetupError, s
end
def with_bunny_connection_handler(uri)
yield
rescue Hutch::Adapter::ConnectionRefused => ex
logger.error "amqp connection error: #{ex.message.downcase}"
raise ConnectionError, "couldn't connect to rabbitmq at #{uri}. Check your configuration, network connectivity and RabbitMQ logs."
end
end
end
|
Clarify that API token is being requested | module TypeKitCli
class AuthToken < Thor
CACHE_FILE = "#{Dir.home}/.typekit"
no_commands{
def get_token
auth_token = nil
if File.exist?(CACHE_FILE)
File.open(CACHE_FILE, 'r') { |file| auth_token = file.gets }
else
auth_token = prompt_for_token
end
auth_token
end
}
private
def prompt_for_token
auth_token = ask("Typekit Auth Token:")
if yes?("Would you like to cache this token? [y/N]:")
say("Token will be cached to in #{CACHE_FILE} file")
File.open(CACHE_FILE, 'w') { |file| file.write(auth_token) }
end
auth_token
end
end
end
| module TypeKitCli
class AuthToken < Thor
CACHE_FILE = "#{Dir.home}/.typekit"
no_commands{
def get_token
auth_token = nil
if File.exist?(CACHE_FILE)
File.open(CACHE_FILE, 'r') { |file| auth_token = file.gets }
else
auth_token = prompt_for_token
end
auth_token
end
}
private
def prompt_for_token
auth_token = ask("Typekit API Token:")
if yes?("Would you like to cache this token? [y/N]:")
say("Token will be cached to in #{CACHE_FILE} file")
File.open(CACHE_FILE, 'w') { |file| file.write(auth_token) }
end
auth_token
end
end
end
|
Use new hash syntax in presence validation test | require 'test_helper'
module Allowing
module Validations
class PresenceValidationTest < Minitest::Test
def setup
@rule = true
@validation = PresenceValidation.new(@rule)
@errors = []
end
def test_type_returns_presence
assert_equal :presence, @validation.type
end
def test_validate_returns_no_errors_if_value_is_present
errors = @validation.validate('Gregory House')
assert errors.empty?
end
def test_validate_returns_error_if_value_is_empty
value = OpenStruct.new(:empty? => true)
errors = @validation.validate(value)
assert_equal 1, errors.size
end
def test_validate_returns_error_if_value_is_empty_string
errors = @validation.validate('')
assert_equal 1, errors.size
end
def test_validate_returns_error_if_value_is_nil
errors = @validation.validate(nil)
assert_equal 1, errors.size
end
def test_validate_returns_correct_error
error = @validation.validate(nil).first
assert_equal :presence, error.name
assert_equal @validation, error.validation
assert_equal nil, error.value
end
end
end
end
| require 'test_helper'
module Allowing
module Validations
class PresenceValidationTest < Minitest::Test
def setup
@rule = true
@validation = PresenceValidation.new(@rule)
@errors = []
end
def test_type_returns_presence
assert_equal :presence, @validation.type
end
def test_validate_returns_no_errors_if_value_is_present
errors = @validation.validate('Gregory House')
assert errors.empty?
end
def test_validate_returns_error_if_value_is_empty
value = OpenStruct.new(empty?: true)
errors = @validation.validate(value)
assert_equal 1, errors.size
end
def test_validate_returns_error_if_value_is_empty_string
errors = @validation.validate('')
assert_equal 1, errors.size
end
def test_validate_returns_error_if_value_is_nil
errors = @validation.validate(nil)
assert_equal 1, errors.size
end
def test_validate_returns_correct_error
error = @validation.validate(nil).first
assert_equal :presence, error.name
assert_equal @validation, error.validation
assert_equal nil, error.value
end
end
end
end
|
Add Asset to list of booking reference types | module BookingHelper
def reference_types_as_collection
types = [CreditInvoice, DebitInvoice]
types.inject({}) do |result, type|
result[t_model(type)] = type.base_class
result
end
end
end
| module BookingHelper
def reference_types_as_collection
types = [CreditInvoice, DebitInvoice, Asset]
types.inject({}) do |result, type|
result[t_model(type)] = type.base_class
result
end
end
end
|
Revert "Removed devise oauth in migration" | class DeviseCreateUsers < ActiveRecord::Migration
def self.up
create_table(:users) do |t|
t.string :name
t.string :login
t.string :email
t.timestamps
end
add_index :users, :login, :unique => true
end
def self.down
drop_table :users
end
end
| class DeviseCreateUsers < ActiveRecord::Migration
def self.up
create_table(:users) do |t|
t.string :name
t.string :login
t.string :email
t.oauth2_authenticatable
t.timestamps
end
add_index :users, :login, :unique => true
add_index :users, :oauth2_uid, :unique => true
end
def self.down
drop_table :users
end
end
|
Handle unset or unknown variables better | module Puppet::Parser::Functions
newfunction(:fail_unconfigured, :doc => "Fail with a canned 'not_configured' message."
) do |args|
node = lookupvar('hostname')
modulename = self.source.module_name || 'unknown'
puppet_class = self.source.name || 'unknown'
if args.length == 0
args = ['operatingsystem', 'operatingsystemrelease', 'osfamily' ]
end
argpairs = [
"error=not_configured",
"node=#{node}",
"module=#{modulename}",
"class=#{puppet_class}"
]
args.each do |arg|
val = lookupvar(arg).downcase || 'unknown'
argpairs.push("#{arg}=#{val}")
end
raise Puppet::ParseError, argpairs.join(" ")
end
end
| module Puppet::Parser::Functions
newfunction(:fail_unconfigured, :doc => "Fail with a canned 'not_configured' message."
) do |args|
if args.length == 0
args = ['operatingsystem', 'operatingsystemrelease', 'osfamily' ]
end
args = ['node'] + args
argpairs = [ "error=not_configured" ]
argpairs << "module=#{self.source.module_name}" if self.source.module_name
argpairs << "class=#{self.source.name}" if self.source.name
args.each do |arg|
val = lookupvar(arg) || :undefined
next if val == :undefined
val.downcase!
argpairs.push("#{arg}=#{val}")
end
raise Puppet::ParseError, argpairs.join(" ")
end
end
|
Include table name in the `accessible_by' scope to prevent conflicts in joins | module Eaco
module Adapters
module ActiveRecord
##
# Authorized collection extractor on PostgreSQL >= 9.4 and a +jsonb+
# column named +acl+.
#
# TODO negative authorizations (using a separate column?)
#
# @see ACL
# @see Actor
# @see Resource
#
module PostgresJSONb
##
# Uses the json key existance operator +?|+ to check whether one of the
# +Actor+'s +Designator+ instances exist as keys in the +ACL+ objects.
#
# @param actor [Actor]
#
# @return [ActiveRecord::Relation] the authorized collection scope.
#
def accessible_by(actor)
return scoped if actor.is_admin?
designators = actor.designators.map {|d| quote_value(d, nil) }
where("acl ?| array[#{designators.join(',')}]::varchar[]")
end
end
end
end
end
| module Eaco
module Adapters
module ActiveRecord
##
# Authorized collection extractor on PostgreSQL >= 9.4 and a +jsonb+
# column named +acl+.
#
# TODO negative authorizations (using a separate column?)
#
# @see ACL
# @see Actor
# @see Resource
#
module PostgresJSONb
##
# Uses the json key existance operator +?|+ to check whether one of the
# +Actor+'s +Designator+ instances exist as keys in the +ACL+ objects.
#
# @param actor [Actor]
#
# @return [ActiveRecord::Relation] the authorized collection scope.
#
def accessible_by(actor)
return scoped if actor.is_admin?
designators = actor.designators.map {|d| quote_value(d, nil) }
column = "#{connection.quote_table_name(table_name)}.acl"
where("#{column} ?| array[#{designators.join(',')}]::varchar[]")
end
end
end
end
end
|
Update homebrew recipe for version 0.2.3 | require 'formula'
class Trousseau < Formula
homepage 'https://github.com/oleiade/trousseau'
url 'https://github.com/oleiade/trousseau/archive/0.2.0.tar.gz'
sha1 ''
depends_on 'go' => :build
depends_on 'mercurial' => :build
depends_on 'bzr' => :build
def install
system 'make', 'all'
bin.install('bin/trousseau')
end
end
| require 'formula'
class Trousseau < Formula
homepage 'https://github.com/oleiade/trousseau'
url 'https://github.com/oleiade/trousseau/archive/0.2.3.tar.gz'
sha1 '66d0b79525c5bed3e1d6b791c90ee77b0a43c487'
depends_on 'go' => :build
depends_on 'mercurial' => :build
depends_on 'bzr' => :build
def install
system 'make', 'all'
bin.install('bin/trousseau')
end
end
|
Document why the podspec is on the root of the repo | Pod::Spec.new do |s|
s.name = 'Protobuf'
s.version = '3.0.0'
s.summary = 'Protocol Buffers v.3 runtime library for Objective-C.'
s.homepage = 'https://github.com/google/protobuf'
s.license = 'New BSD'
s.authors = { 'The Protocol Buffers contributors' => 'protobuf@googlegroups.com' }
s.source_files = 'objectivec/*.{h,m}', 'objectivec/google/protobuf/*.pbobjc.h', 'objectivec/google/protobuf/Descriptor.pbobjc.m'
# The following is a .m umbrella file, and would cause duplicate symbol
# definitions:
s.exclude_files = 'objectivec/GPBProtocolBuffers.m'
# The .m's of the proto Well-Known-Types under google/protobuf are #imported
# by GPBWellKnownTypes.m. So we can't compile them (duplicate symbols), but we
# need them available for the importing:
s.preserve_paths = 'objectivec/google/protobuf/*.pbobjc.m'
s.header_mappings_dir = 'objectivec'
s.ios.deployment_target = '6.0'
s.osx.deployment_target = '10.8'
s.requires_arc = false
end
| # This file describes to Cocoapods how to integrate the Objective-C runtime into a dependent
# project.
# Despite this file being specific to Objective-C, it needs to be on the root of the repository.
# Otherwise, Cocoapods gives trouble like not picking up the license file correctly, or not letting
# dependent projects use the :git notation to refer to the library.
Pod::Spec.new do |s|
s.name = 'Protobuf'
s.version = '3.0.0'
s.summary = 'Protocol Buffers v.3 runtime library for Objective-C.'
s.homepage = 'https://github.com/google/protobuf'
s.license = 'New BSD'
s.authors = { 'The Protocol Buffers contributors' => 'protobuf@googlegroups.com' }
s.source_files = 'objectivec/*.{h,m}', 'objectivec/google/protobuf/*.pbobjc.h', 'objectivec/google/protobuf/Descriptor.pbobjc.m'
# The following is a .m umbrella file, and would cause duplicate symbol
# definitions:
s.exclude_files = 'objectivec/GPBProtocolBuffers.m'
# The .m's of the proto Well-Known-Types under google/protobuf are #imported
# by GPBWellKnownTypes.m. So we can't compile them (duplicate symbols), but we
# need them available for the importing:
s.preserve_paths = 'objectivec/google/protobuf/*.pbobjc.m'
s.header_mappings_dir = 'objectivec'
s.ios.deployment_target = '6.0'
s.osx.deployment_target = '10.8'
s.requires_arc = false
end
|
Allow array of symbols to be passed for GitHub::User.get. | module GitHub
class User < Base
attr_accessor :login, :token
def get(login)
if login == :self
login = self.login
end
return GitHub::Browser.get "/user/show/#{login}"
end
end
end
| module GitHub
class User < Base
attr_accessor :login, :token
def get(login)
if [:self, :me].include? login
login = self.login
end
return GitHub::Browser.get "/user/show/#{login}"
end
end
end
|
Add cask for ReadyTalk, an audio and web conferencing app. | class Readytalk < Cask
url 'https://core.readytalk.com/ql/bins/QuickLauncherInstall.dmg'
homepage 'https://www.readytalk.com/'
version 'latest'
no_checksum
link 'ReadyTalk Quick Launcher.app'
end
| |
Undo magic standards restrictions for specific armies | class MagicStandard < ActiveRecord::Base
belongs_to :army
has_many :army_list_unit_magic_standards, dependent: :destroy
has_many :army_list_units, through: :army_list_unit_magic_standards
has_one :override, class_name: 'MagicStandard', foreign_key: 'override_id'
validates :value_points, numericality: { greater_than_or_equal_to: 0 }
scope :available_for, lambda { |army, value_points_limit|
if army.id == 5
if value_points_limit.nil?
where('army_id = :army_id', army_id: army).order('value_points DESC', 'name')
else
where('army_id = :army_id', army_id: army).where('value_points <= ?', value_points_limit).order('value_points DESC', 'name')
end
else
if value_points_limit.nil?
where('army_id = :army_id OR (army_id IS NULL AND id NOT IN (SELECT override_id FROM magic_standards WHERE army_id = :army_id AND override_id IS NOT NULL))', army_id: army).order('value_points DESC', 'name')
else
where('army_id = :army_id OR (army_id IS NULL AND id NOT IN (SELECT override_id FROM magic_standards WHERE army_id = :army_id AND override_id IS NOT NULL))', army_id: army).where('value_points <= ?', value_points_limit).order('value_points DESC', 'name')
end
end
}
end
| class MagicStandard < ActiveRecord::Base
belongs_to :army
has_many :army_list_unit_magic_standards, dependent: :destroy
has_many :army_list_units, through: :army_list_unit_magic_standards
has_one :override, class_name: 'MagicStandard', foreign_key: 'override_id'
validates :value_points, numericality: { greater_than_or_equal_to: 0 }
scope :available_for, lambda { |army, value_points_limit|
if value_points_limit.nil?
where('army_id = :army_id OR (army_id IS NULL AND id NOT IN (SELECT override_id FROM magic_standards WHERE army_id = :army_id AND override_id IS NOT NULL))', army_id: army).order('value_points DESC', 'name')
else
where('army_id = :army_id OR (army_id IS NULL AND id NOT IN (SELECT override_id FROM magic_standards WHERE army_id = :army_id AND override_id IS NOT NULL))', army_id: army).where('value_points <= ?', value_points_limit).order('value_points DESC', 'name')
end
}
end
|
Update travel advice to use core_layout | class TravelAdviceController < ApplicationController
FOREIGN_TRAVEL_ADVICE_SLUG = "foreign-travel-advice".freeze
slimmer_template "wrapper"
def index
set_expiry
setup_content_item("/" + FOREIGN_TRAVEL_ADVICE_SLUG)
@presenter = TravelAdviceIndexPresenter.new(@content_item)
respond_to do |format|
format.html { render locals: { full_width: true } }
format.atom do
set_expiry(5.minutes)
headers["Access-Control-Allow-Origin"] = "*"
end
end
end
end
| class TravelAdviceController < ApplicationController
FOREIGN_TRAVEL_ADVICE_SLUG = "foreign-travel-advice".freeze
slimmer_template "core_layout"
def index
set_expiry
setup_content_item("/" + FOREIGN_TRAVEL_ADVICE_SLUG)
@presenter = TravelAdviceIndexPresenter.new(@content_item)
respond_to do |format|
format.html { render locals: { full_width: true } }
format.atom do
set_expiry(5.minutes)
headers["Access-Control-Allow-Origin"] = "*"
end
end
end
end
|
Fix TypeError when symbol is given as argument | module S3Direct
module Model
extend ActiveSupport::Concern
FORWARDABLE_METHODS = [:url]
DEFAULT_OPTIONS = {
bucket: S3Direct.default_bucket,
policy: { # @see http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/S3/PresignedPost.html
secure: true,
expires: 1800, # seconds
success_action_status: 201
}
}.freeze
module ClassMethods
# @param name
def has_s3_file(name = :file, options = {})
S3Direct.options.set(self, name, options.merge(name: name).reverse_merge(DEFAULT_OPTIONS))
instance_accessor = name
instance_variable = "@s3_direct_" + instance_accessor
define_method instance_accessor do
options = S3Direct.options.get(self.class, name)
instance_variable_get(instance_variable) || instance_variable_set(
instance_variable, S3Direct::Object.new(self, "#{name}_key", options)
)
end
delegate *FORWARDABLE_METHODS, to: instance_accessor, prefix: name
end
end
end
end
| module S3Direct
module Model
extend ActiveSupport::Concern
FORWARDABLE_METHODS = [:url]
DEFAULT_OPTIONS = {
bucket: S3Direct.default_bucket,
policy: { # @see http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/S3/PresignedPost.html
secure: true,
expires: 1800, # seconds
success_action_status: 201
}
}.freeze
module ClassMethods
# @param name
def has_s3_file(name = :file, options = {})
S3Direct.options.set(self, name, options.merge(name: name).reverse_merge(DEFAULT_OPTIONS))
instance_variable = "@s3_direct_#{name}"
define_method name do
options = S3Direct.options.get(self.class, name)
instance_variable_get(instance_variable) || instance_variable_set(
instance_variable, S3Direct::Object.new(self, "#{name}_key", options)
)
end
delegate *FORWARDABLE_METHODS, to: name, prefix: name
end
end
end
end
|
Set the OT tracer to our own OT compatible tracer. | require "instana/opentracing/tracer"
require "instana/opentracing/carrier"
| require "instana/opentracing/tracer"
require "instana/opentracing/carrier"
# Set the global tracer to our OT tracer
# which supports the OT specificiation
OpenTracing.global_tracer = ::Instana.tracer
|
Add NameWithObservationsInSet ** Please review initialize_flavor ** | class Query::NameWithObservationsInSet < Query::Name
include Query::Initializers::InSet
def parameter_declarations
super.merge(
ids: [Observation],
old_title?: :string,
old_by?: :string,
has_specimen?: :boolean,
has_images?: :boolean,
has_obs_tag?: [:string],
has_name_tag?: [:string]
)
end
def initialize_flavor
initialize_in_set_flavor("observations")
add_join("observations")
initialize_observation_filters
super
end
def default_order
"name"
end
end
| |
Fix webhooks controller keywords for ruby 3 | # frozen_string_literal: true
module ShopifyApp
class MissingWebhookJobError < StandardError; end
class WebhooksController < ActionController::Base
include ShopifyApp::WebhookVerification
def receive
params.permit!
job_args = { shop_domain: shop_domain, webhook: webhook_params.to_h }
webhook_job_klass.perform_later(job_args)
head(:ok)
end
private
def webhook_params
params.except(:controller, :action, :type)
end
def webhook_job_klass
webhook_job_klass_name.safe_constantize || raise(ShopifyApp::MissingWebhookJobError)
end
def webhook_job_klass_name(type = webhook_type)
[webhook_namespace, "#{type}_job"].compact.join('/').classify
end
def webhook_type
params[:type]
end
def webhook_namespace
ShopifyApp.configuration.webhook_jobs_namespace
end
end
end
| # frozen_string_literal: true
module ShopifyApp
class MissingWebhookJobError < StandardError; end
class WebhooksController < ActionController::Base
include ShopifyApp::WebhookVerification
def receive
params.permit!
webhook_job_klass.perform_later(shop_domain: shop_domain, webhook: webhook_params.to_h)
head(:ok)
end
private
def webhook_params
params.except(:controller, :action, :type)
end
def webhook_job_klass
webhook_job_klass_name.safe_constantize || raise(ShopifyApp::MissingWebhookJobError)
end
def webhook_job_klass_name(type = webhook_type)
[webhook_namespace, "#{type}_job"].compact.join('/').classify
end
def webhook_type
params[:type]
end
def webhook_namespace
ShopifyApp.configuration.webhook_jobs_namespace
end
end
end
|
Add summary and description to gemspec. | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "melt"
spec.version = "0.1"
spec.authors = ["Josef ล imรกnek"]
spec.email = ["josef.simanek@gmail.com"]
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "https://rubygems.org"
end
spec.summary = %q{}
spec.description = %q{}
spec.homepage = "https://github.com/zizkovrb/melt"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.extensions = ["ext/melt/extconf.rb"]
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rake-compiler"
spec.add_development_dependency "minitest"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "melt"
spec.version = "0.1"
spec.authors = ["Josef ล imรกnek"]
spec.email = ["josef.simanek@gmail.com"]
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "https://rubygems.org"
end
spec.summary = %q{There is no way to unfreeze a frozen object. Really?}
spec.description = %q{Have you ever heard about icebergs or icicles? What about melting?}
spec.homepage = "https://github.com/zizkovrb/melt"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.extensions = ["ext/melt/extconf.rb"]
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rake-compiler"
spec.add_development_dependency "minitest"
end
|
Change namespace from user to api | Rails.application.routes.draw do
devise_for :users, only: []
namespace :user, defaults: { format: :json } do
resource :login, only: [:create], controller: :sessions
resource :register, only: [:create], controller: :users
end
end
| Rails.application.routes.draw do
devise_for :users, only: []
namespace :api, defaults: { format: :json } do
resource :login, only: [:create], controller: :sessions
resource :register, only: [:create], controller: :users
end
resource :user, only: [:new]
end
|
Use a double instead of a fake implemenation | # -*- encoding : utf-8 -*-
require 'spec_helper'
require 'guacamole/collection'
class TestCollection
include Guacamole::Collection
end
describe Guacamole::Collection do
class FakeMapper
def document_to_model(document)
document
end
end
subject { TestCollection }
describe 'Configuration' do
it 'should set the connection to ArangoDB' do
mock_db_connection = double('ConnectionToCollection')
subject.connection = mock_db_connection
expect(subject.connection).to eq mock_db_connection
end
it 'should set the Mapper instance to map documents to models and vice versa' do
mock_mapper = double('Mapper')
subject.mapper = mock_mapper
expect(subject.mapper).to eq mock_mapper
end
end
let(:connection) { double('Connection') }
let(:mapper) { FakeMapper.new }
it 'should provide a method to get mapped documents by key from the database' do
subject.connection = connection
subject.mapper = mapper
document = { data: 'foo' }
expect(connection).to receive(:fetch).with('some_key').and_return(document)
expect(mapper).to receive(:document_to_model).with(document).and_call_original
model = subject.by_key 'some_key'
expect(model[:data]).to eq 'foo'
end
end
| # -*- encoding : utf-8 -*-
require 'spec_helper'
require 'guacamole/collection'
class TestCollection
include Guacamole::Collection
end
describe Guacamole::Collection do
subject { TestCollection }
describe 'Configuration' do
it 'should set the connection to ArangoDB' do
mock_db_connection = double('ConnectionToCollection')
subject.connection = mock_db_connection
expect(subject.connection).to eq mock_db_connection
end
it 'should set the Mapper instance to map documents to models and vice versa' do
mock_mapper = double('Mapper')
subject.mapper = mock_mapper
expect(subject.mapper).to eq mock_mapper
end
end
let(:connection) { double('Connection') }
let(:mapper) { double('Mapper') }
it 'should provide a method to get mapped documents by key from the database' do
subject.connection = connection
subject.mapper = mapper
document = { data: 'foo' }
model = double('Model')
expect(connection).to receive(:fetch).with('some_key').and_return(document)
expect(mapper).to receive(:document_to_model).with(document).and_return(model)
expect(subject.by_key('some_key')).to eq model
end
end
|
Remove MESSAGE constant on password expired error | module Identity::Errors
class NoSession < StandardError
end
class PasswordExpired < StandardError
# Override this message so that the user doesn't see a URL that they're
# supposed to visit. Instead, just take them directly to the write place.
MESSAGE = <<-eos.strip
Your password has expired. Please reset it.
eos
attr_accessor :message
def initialize(_)
@message = <<-eos.strip
Your password has expired. Please reset it.
eos
end
end
class UnauthorizedClient < StandardError
attr_accessor :client
def initialize(client)
@client = client
end
end
class SuspendedAccount < StandardError
attr_accessor :message
def initialize(msg)
@message = msg
end
end
end
| module Identity::Errors
class NoSession < StandardError
end
class PasswordExpired < StandardError
attr_accessor :message
def initialize(_)
# Override this message so that the user doesn't see a URL that they're
# supposed to visit. Instead, just take them directly to the write place.
@message = <<-eos.strip
Your password has expired. Please reset it.
eos
end
end
class UnauthorizedClient < StandardError
attr_accessor :client
def initialize(client)
@client = client
end
end
class SuspendedAccount < StandardError
attr_accessor :message
def initialize(msg)
@message = msg
end
end
end
|
Add shortcut to check if actor is dead | module Celluloid
# A proxy which controls the Actor lifecycle
class ActorProxy < AbstractProxy
attr_reader :thread, :mailbox
# Used for reflecting on proxy objects themselves
def __class__; ActorProxy; end
def initialize(thread, mailbox)
@thread = thread
@mailbox = mailbox
end
def inspect
# TODO: use a system event to fetch actor state: tasks?
"#<Celluloid::ActorProxy(#{@mailbox.address}) alive>"
rescue DeadActorError
"#<Celluloid::ActorProxy(#{@mailbox.address}) dead>"
end
def alive?
@mailbox.alive?
end
# Terminate the associated actor
def terminate
terminate!
Actor.join(self)
nil
end
# Terminate the associated actor asynchronously
def terminate!
::Kernel.raise DeadActorError, "actor already terminated" unless alive?
@mailbox << TerminationRequest.new
end
end
end
| module Celluloid
# A proxy which controls the Actor lifecycle
class ActorProxy < AbstractProxy
attr_reader :thread, :mailbox
# Used for reflecting on proxy objects themselves
def __class__; ActorProxy; end
def initialize(thread, mailbox)
@thread = thread
@mailbox = mailbox
end
def inspect
# TODO: use a system event to fetch actor state: tasks?
"#<Celluloid::ActorProxy(#{@mailbox.address}) alive>"
rescue DeadActorError
"#<Celluloid::ActorProxy(#{@mailbox.address}) dead>"
end
def alive?
@mailbox.alive?
end
def dead?
!alive?
end
# Terminate the associated actor
def terminate
terminate!
Actor.join(self)
nil
end
# Terminate the associated actor asynchronously
def terminate!
::Kernel.raise DeadActorError, "actor already terminated" unless alive?
@mailbox << TerminationRequest.new
end
end
end
|
Prepare for the new coming tag 0.1.7 | Pod::Spec.new do |s|
s.name = "CUtil"
s.version = "0.1.6"
s.summary = "CUtil is a common utilities collection. It is designed as a tool-box for iOS development."
s.author = { "Acttos" => "acttosma@gmail.com", "Jason" => "majinshou@gmail.com" }
s.social_media_url = "https://twitter.com/hulu0319"
s.homepage = "https://github.com/acttos/CommonUtilities"
s.license = { :type => "MIT", :file => "LICENSE" }
s.platform = :ios
s.ios.deployment_target = "8.0"
s.source = { :git => "https://github.com/acttos/CommonUtilities.git", :tag => s.version }
s.public_header_files = "CUtil/*.h", "CUtil/**/*.h"
s.source_files = "CUtil/*.h", "CUtil/**/*.{h,m}"
s.ios.framework = "UIKit"
end
| Pod::Spec.new do |s|
s.name = "CUtil"
s.version = "0.1.7"
s.summary = "CUtil is a common utilities collection. It is designed as a tool-box for iOS development."
s.author = { "Acttos" => "acttosma@gmail.com", "Jason" => "majinshou@gmail.com" }
s.social_media_url = "https://twitter.com/hulu0319"
s.homepage = "https://github.com/acttos/CommonUtilities"
s.license = { :type => "MIT", :file => "LICENSE" }
s.platform = :ios
s.ios.deployment_target = "8.0"
s.source = { :git => "https://github.com/acttos/CommonUtilities.git", :tag => s.version }
s.public_header_files = "CUtil/*.h", "CUtil/**/*.h"
s.source_files = "CUtil/*.h", "CUtil/**/*.{h,m}"
s.ios.framework = "UIKit"
end
|
Use RubyParser to determine validity of string. | module Sourcify
module Proc
module Scanner #:nodoc:all
class DString < Struct.new(:tag)
# To suppress 'warning: Object#type is deprecated; use Object#class' when
# evaluating string
attr_reader :type
def <<(content)
(@contents ||= []) << content
end
def to_s
@contents.join
end
def closed?
# NOTE: The only real error is SyntaxError, other errors are due
# to undefined variable or watever, which are perfectly ok when
# testing for validity of the string.
begin
instance_eval(safe_contents) if evaluable?
rescue SyntaxError
false
rescue Exception
true
end
end
private
CLOSING_TAGS = {'(' => ')', '[' => ']', '<' => '>', '{' => '}'}
def evaluable?
@contents[-1][-1].chr == end_tag
end
def safe_contents
# NOTE: %x & ` strings are dangerous to eval cos they execute shell commands,
# thus we convert them to normal strings 1st
@contents.join.gsub(/(%x)(\W|\_)/, '%Q\2').gsub(/.{0,2}(`)/) do |s|
s =~ /^(%Q|%W|%r|%x|.?%|.?\\)/ ? s : s.sub(/`$/,'%Q`')
end
end
def start_tag
@start_tag ||= tag[-1].chr
end
def end_tag
@end_tag ||= (CLOSING_TAGS[start_tag] || start_tag)
end
end
end
end
end
| module Sourcify
module Proc
module Scanner #:nodoc:all
class DString < Struct.new(:tag)
# To suppress 'warning: Object#type is deprecated; use Object#class' when
# evaluating string
attr_reader :type
def <<(content)
(@contents ||= []) << content
end
def to_s
@contents.join
end
def closed?
evaluable? && parsable?
end
private
CLOSING_TAGS = {'(' => ')', '[' => ']', '<' => '>', '{' => '}'}
def evaluable?
@contents[-1][-1].chr == end_tag
end
def parsable?
begin
RubyParser.new.parse(<<-SOURCIFIED_HEREDOKIE
#{safe_contents}
SOURCIFIED_HEREDOKIE
) && true
rescue Racc::ParseError, SyntaxError
false
rescue Exception
true
end
end
def safe_contents
# NOTE: %x & ` strings are dangerous to eval cos they execute shell commands,
# thus we convert them to normal strings 1st
to_s.gsub(/(%x)(\W|\_)/, '%Q\2').gsub(/.{0,2}(`)/) do |s|
s =~ /^(%Q|%W|%r|%x|.?%|.?\\)/ ? s : s.sub(/`$/,'%Q`')
end
end
def start_tag
@start_tag ||= tag[-1].chr
end
def end_tag
@end_tag ||= (CLOSING_TAGS[start_tag] || start_tag)
end
end
end
end
end
|
Fix boolean symbol :true => true | class AddUsernameToUsers < ActiveRecord::Migration
def change
add_column :users, :username, :string, null: false, after: :name
add_index :users, :username, unique: :true
end
end
| class AddUsernameToUsers < ActiveRecord::Migration
def change
add_column :users, :username, :string, null: false, after: :name
add_index :users, :username, unique: true
end
end
|
Remove trailing ? from Github avatar URL in the hopes that this fixes the seg faults on Heroku. | class User < ActiveRecord::Base
mount_uploader :photo, PhotoUploader
devise :rememberable, :trackable, :omniauthable, :omniauth_providers => [:github]
scope :instructors, ->{ where(instructor: true) }
scope :students, ->{ where("instructor = false or instructor is null") }
has_many :enrollments
has_many :courses, through: :enrollments
has_many :self_reports
has_many :quiz_submissions
has_many :quizzes, through: :quiz_submissions
validates_format_of :email, with: /\A[^@]+@[^@]+\z/, message: "must be an email address"
validates_presence_of :github_access_token
default_scope { order(name: :asc) }
def student?
!instructor?
end
def has_confirmed_photo?
self.photo? && self.photo_confirmed?
end
def self.find_or_create_for_github_oauth(auth)
where(github_uid: auth.uid).first_or_create do |user|
user.github_access_token = auth.credentials.token
user.github_uid = auth.uid
user.github_username = auth.info.nickname
user.name = auth.info.name
user.email = auth.info.email
user.remote_photo_url = auth.info.image
end
end
def octoclient
@octoclient ||= Octokit::Client.new(:access_token => github_access_token)
end
end
| class User < ActiveRecord::Base
mount_uploader :photo, PhotoUploader
devise :rememberable, :trackable, :omniauthable, :omniauth_providers => [:github]
scope :instructors, ->{ where(instructor: true) }
scope :students, ->{ where("instructor = false or instructor is null") }
has_many :enrollments
has_many :courses, through: :enrollments
has_many :self_reports
has_many :quiz_submissions
has_many :quizzes, through: :quiz_submissions
validates_format_of :email, with: /\A[^@]+@[^@]+\z/, message: "must be an email address"
validates_presence_of :github_access_token
default_scope { order(name: :asc) }
def student?
!instructor?
end
def has_confirmed_photo?
self.photo? && self.photo_confirmed?
end
def self.find_or_create_for_github_oauth(auth)
auth.info.image.gsub!("?","")
where(github_uid: auth.uid).first_or_create do |user|
user.github_access_token = auth.credentials.token
user.github_uid = auth.uid
user.github_username = auth.info.nickname
user.name = auth.info.name
user.email = auth.info.email
user.remote_photo_url = auth.info.image.gsub("?","")
end
end
def octoclient
@octoclient ||= Octokit::Client.new(:access_token => github_access_token)
end
end
|
Remove references to watcher and test w/ loader instead | require_relative 'helper'
if ActiveRecord::VERSION::STRING >= "4.1.0"
describe "PredictiveLoad::Watcher" do
it "does not work" do
skip "does not work"
end
end
else
require 'predictive_load/watcher'
describe PredictiveLoad::ActiveRecordCollectionObservation do
describe "Relation#to_a" do
before do
user1 = User.create!(:name => "Rudolph")
user2 = User.create!(:name => "Santa")
end
after do
User.delete_all
end
describe "when a collection observer is specified" do
before do
ActiveRecord::Relation.collection_observer = PredictiveLoad::Watcher
end
it "observes the members of that collection" do
users = User.all
assert_equal 2, users.size
assert users.all? { |user| user.collection_observer }
end
end
describe "when a collection observer is not specified" do
before do
ActiveRecord::Relation.collection_observer = nil
end
it "does not observe the members of that collection" do
users = User.all
assert_equal 2, users.size, users.inspect
assert users.none? { |user| user.collection_observer }
end
end
end
end
end
| require_relative 'helper'
require 'predictive_load/loader'
describe PredictiveLoad::ActiveRecordCollectionObservation do
describe "Relation#to_a" do
before do
User.create!(name: "Rudolph")
User.create!(name: "Santa")
end
after do
User.delete_all
end
describe "when a collection observer is specified" do
before do
ActiveRecord::Relation.collection_observer = PredictiveLoad::Loader
end
it "observes the members of that collection" do
users = User.all
assert_equal 2, users.size
assert users.all? { |user| user.collection_observer }
end
end
describe "when a collection observer is not specified" do
before do
ActiveRecord::Relation.collection_observer = nil
end
it "does not observe the members of that collection" do
users = User.all
assert_equal 2, users.size, users.inspect
assert users.none? { |user| user.collection_observer }
end
end
end
end
|
Add new migration for change wants table with correct class name | class ChangeWants < ActiveRecord::Migration
def change
add_column :wants, :notified, :boolean
change_column_default :wants, :notified, false
change_column_default :wants, :fulfilled, false
end
end
| class AddColumnsToWants < ActiveRecord::Migration
def change
add_column :wants, :notified, :boolean
change_column_default :wants, :notified, false
change_column_default :wants, :fulfilled, false
end
end
|
Include each test case at most once in the LocationsFilter. | require 'cucumber/core/filter'
module Cucumber
module Core
module Test
# Sorts and filters scenarios based on a list of locations
class LocationsFilter < Filter.new(:filter_locations)
def test_case(test_case)
test_cases[test_case.location.file] << test_case
self
end
def done
sorted_test_cases.each do |test_case|
test_case.describe_to receiver
end
receiver.done
self
end
private
def sorted_test_cases
filter_locations.map { |filter_location|
test_cases[filter_location.file].select { |test_case|
test_case.all_locations.any? { |location| filter_location.match?(location) }
}
}.flatten
end
def test_cases
@test_cases ||= Hash.new { |hash, key| hash[key] = [] }
end
end
end
end
end
| require 'cucumber/core/filter'
module Cucumber
module Core
module Test
# Sorts and filters scenarios based on a list of locations
class LocationsFilter < Filter.new(:filter_locations)
def test_case(test_case)
test_cases[test_case.location.file] << test_case
self
end
def done
sorted_test_cases.each do |test_case|
test_case.describe_to receiver
end
receiver.done
self
end
private
def sorted_test_cases
filter_locations.map { |filter_location|
test_cases[filter_location.file].select { |test_case|
test_case.all_locations.any? { |location| filter_location.match?(location) }
}
}.flatten.uniq
end
def test_cases
@test_cases ||= Hash.new { |hash, key| hash[key] = [] }
end
end
end
end
end
|
Fix the case where ThreadedConsumerStrategy with a SingleWorkerStrategy with a large batch does not properly shut down when the Chore::Manager shuts down | module Chore
module Strategy
class SingleWorkerStrategy
def initialize(manager)
@manager = manager
@worker = nil
end
def start;end
def stop!;end
def assign(work)
if workers_available?
@worker = Worker.new(work)
@worker.start
@worker = nil
true
end
end
def workers_available?
@worker.nil?
end
end
end
end
| module Chore
module Strategy
class SingleWorkerStrategy
attr_reader :worker
def initialize(manager)
@manager = manager
@worker = nil
end
def start;end
def stop!
worker.stop! if worker
end
def assign(work)
if workers_available?
@worker = Worker.new(work)
@worker.start
@worker = nil
true
end
end
def workers_available?
@worker.nil?
end
end
end
end
|
Set swagger host via dotenv | module Api
class DocsController < ActionController::Base
include Swagger::Blocks
# :nocov:
swagger_root do
key :swagger, '2.0'
info do
key :version, '0.1.0'
key :title, 'EveMonk back-end API'
end
key :schemes, ['http']
key :host, 'evemonk.com'
key :basePath, '/api'
key :consumes, ['application/json']
key :produces, ['application/json']
tag do
key :name, 'signups'
key :description, 'Signups operations'
end
tag do
key :name, 'session'
key :description, 'Session operation'
end
end
# A list of all classes that have swagger_* declarations.
SWAGGERED_CLASSES = [
Api::Docs::Signups,
Api::Docs::Models::User,
self,
].freeze
# :nocov:
def index
render json: Swagger::Blocks.build_root_json(SWAGGERED_CLASSES)
end
end
end
| module Api
class DocsController < ActionController::Base
include Swagger::Blocks
# :nocov:
swagger_root do
key :swagger, '2.0'
info do
key :version, '0.1.0'
key :title, 'EveMonk back-end API'
end
key :schemes, ['http']
key :host, (ENV['API_BACKEND_HOST'] || 'localhost:3000')
key :basePath, '/api'
key :consumes, ['application/json']
key :produces, ['application/json']
tag do
key :name, 'signups'
key :description, 'Signups operations'
end
tag do
key :name, 'session'
key :description, 'Session operation'
end
end
# A list of all classes that have swagger_* declarations.
SWAGGERED_CLASSES = [
Api::Docs::Signups,
Api::Docs::Models::User,
self,
].freeze
# :nocov:
def index
render json: Swagger::Blocks.build_root_json(SWAGGERED_CLASSES)
end
end
end
|
Change variable name for clarity | module GovukContentSchemaTestHelpers
class Examples
def initialize
Util.check_govuk_content_schemas_path!
end
def get(schema_name, example_name)
path = example_path(schema_name, example_name)
check_example_file_exists!(path)
File.read(path)
end
def check_example_file_exists!(path)
if !File.exists?(path)
raise ImproperlyConfiguredError, "Example file not found: #{path}."
end
end
private
def example_path(schema_name, example_name)
schema_type = GovukContentSchemaTestHelpers.configuration.schema_type
File.join(Util.govuk_content_schemas_path, "/formats/#{schema_name}/#{schema_type}/examples/#{example_name}.json").to_s
end
end
end
| module GovukContentSchemaTestHelpers
class Examples
def initialize
Util.check_govuk_content_schemas_path!
end
def get(format, example_name)
path = example_path(format, example_name)
check_example_file_exists!(path)
File.read(path)
end
def check_example_file_exists!(path)
if !File.exists?(path)
raise ImproperlyConfiguredError, "Example file not found: #{path}."
end
end
private
def example_path(format, example_name)
schema_type = GovukContentSchemaTestHelpers.configuration.schema_type
File.join(Util.govuk_content_schemas_path, "/formats/#{format}/#{schema_type}/examples/#{example_name}.json").to_s
end
end
end
|
Update spec to version 2.1.16 |
Pod::Spec.new do |s|
s.name = "LightRoute"
s.version = "2.1.15"
s.summary = "LightRoute is easy transition between view controllers and support many popylar arhitectures"
s.description = <<-DESC
LightRoute is easy transition between view controllers and support many popylar arhitectures. This framework very flow for settings your transition and have userfriendly API.
DESC
s.homepage = "https://github.com/SpectralDragon/LightRoute"
s.documentation_url = "https://github.com/SpectralDragon/LightRoute"
s.license = "MIT"
s.author = { "Vladislav Prusakov" => "hipsterknights@gmail.com" }
s.source = { :git => "https://github.com/SpectralDragon/LightRoute.git", :tag => "#{s.version}", :submodules => false }
s.ios.deployment_target = "8.0"
s.source_files = "Sources/*.swift", "Sources/TransitionNodes/*.swift", "Sources/Protocols/*.swift"
end
|
Pod::Spec.new do |s|
s.name = "LightRoute"
s.version = "2.1.16"
s.summary = "LightRoute is easy transition between view controllers and support many popylar arhitectures"
s.description = <<-DESC
LightRoute is easy transition between view controllers and support many popylar arhitectures. This framework very flow for settings your transition and have userfriendly API.
DESC
s.homepage = "https://github.com/SpectralDragon/LightRoute"
s.documentation_url = "https://github.com/SpectralDragon/LightRoute"
s.license = "MIT"
s.author = { "Vladislav Prusakov" => "hipsterknights@gmail.com" }
s.source = { :git => "https://github.com/SpectralDragon/LightRoute.git", :tag => "#{s.version}", :submodules => false }
s.ios.deployment_target = "8.0"
s.source_files = "Sources/*.swift", "Sources/TransitionNodes/*.swift", "Sources/Protocols/*.swift"
end
|
Add CocoaPods podspec for a future version. | Pod::Spec.new do |s|
s.name = 'MTLocation'
s.version = '0.9.1'
s.platform = :ios
s.summary = 'Convenience-stuff for CoreLocation/MapKit on iOS. Includes a UIBarButtonItem mimicing the ' \
'Locate-Me-Button of the built-in Google Maps App.'
s.homepage = 'https://github.com/myell0w/MTLocation'
s.author = { 'Matthias Tretter' => 'myell0w@me.com' }
s.source = { :git => 'https://github.com/myell0w/MTLocation.git', :tag => '0.9' }
s.description = 'These classes aim to mimic some of the functions of the built-in Google Maps App ' \
'on iOS for you. Currently the library contains a simple Location Manager-Singleton ' \
'that sends out notifications when CLLocationManager-Delegate-Methods are called and a ' \
'UIBarButtonItem/UIButton that acts as a Locate-Me Button that behaves similar to the ' \
'one in the Google Maps App. The switch from one mode to another is animated, just like ' \
'in the Google Maps App. It can also be customized to support Heading-Updates or not, ' \
'by setting property headingEnabled.'
s.requires_arc = true
s.source_files = '*.{h,m}'
s.frameworks = 'MapKit', 'CoreLocation'
end
| |
Remove include of Acceptance module | require "integration_helper"
feature "adding evidence to a fact", type: :request do
include Acceptance
include Acceptance::FactHelper
background do
@user = sign_in_user FactoryGirl.create :approved_confirmed_user
end
let(:factlink) { create :fact, created_by: @user.graph_user }
scenario "initially the evidence list should be empty" do
go_to_discussion_page_of factlink
within(:css, ".relation-tabs-view") do
page.should have_content "This Factlink is not supported by other Factlinks."
end
end
scenario "after adding a piece of evidence, evidence list should contain that item" do
go_to_discussion_page_of factlink
supporting_factlink = backend_create_fact
within(".relation-tabs-view") do
add_evidence supporting_factlink
within("li.evidence-item") do
page.should have_content supporting_factlink.to_s
end
end
end
scenario "we can click on evidence to go to the page of that factlink" do
go_to_discussion_page_of factlink
supporting_factlink = backend_create_fact
within(".relation-tabs-view") do
add_evidence supporting_factlink
within("li.evidence-item") do
page.find('span', text: supporting_factlink.to_s).click
end
end
within(".fact-view") do
page.should have_content(supporting_factlink.to_s)
end
end
end
| require "integration_helper"
feature "adding evidence to a fact", type: :request do
include Acceptance::FactHelper
background do
@user = sign_in_user FactoryGirl.create :approved_confirmed_user
end
let(:factlink) { create :fact, created_by: @user.graph_user }
scenario "initially the evidence list should be empty" do
go_to_discussion_page_of factlink
within(:css, ".relation-tabs-view") do
page.should have_content "This Factlink is not supported by other Factlinks."
end
end
scenario "after adding a piece of evidence, evidence list should contain that item" do
go_to_discussion_page_of factlink
supporting_factlink = backend_create_fact
within(".relation-tabs-view") do
add_evidence supporting_factlink
within("li.evidence-item") do
page.should have_content supporting_factlink.to_s
end
end
end
scenario "we can click on evidence to go to the page of that factlink" do
go_to_discussion_page_of factlink
supporting_factlink = backend_create_fact
within(".relation-tabs-view") do
add_evidence supporting_factlink
within("li.evidence-item") do
page.find('span', text: supporting_factlink.to_s).click
end
end
within(".fact-view") do
page.should have_content(supporting_factlink.to_s)
end
end
end
|
Use `:format => false` for the other catchall route | Konacha::Engine.routes.draw do
get '/iframe/*name' => 'specs#iframe', :format => false, :as => :iframe
root :to => 'specs#parent'
get '*path' => 'specs#parent'
end
| Konacha::Engine.routes.draw do
get '/iframe/*name' => 'specs#iframe', :format => false, :as => :iframe
root :to => 'specs#parent'
get '*path' => 'specs#parent', :format => false
end
|
Switch back over to the standard def for plywood | class WikiHouse::Config
def self.machine
WikiHouse::Laser
#WikiHouse::Cnc
end
def self.sheet
# WikiHouse::ImperialPlywood1521Sheet
# WikiHouse::ImperialPlywood34Sheet
WikiHouse::ImperialFiberboardSheet
end
end | class WikiHouse::Config
def self.machine
WikiHouse::Laser
#WikiHouse::Cnc
end
def self.sheet
WikiHouse::ImperialPlywood1521Sheet
# WikiHouse::ImperialPlywood34Sheet
# WikiHouse::ImperialFiberboardSheet
end
end |
Return platform names alongside tags | class Api::V1::TagsController < ApplicationController
def index
@tags = Tag.where("name ILIKE :search", search: "#{params['q']}%").limit(5).all
render json: @tags.map(&:name)
end
end
| class Api::V1::TagsController < ApplicationController
def index
@tags = Tag.where("name ILIKE :search", search: "#{params['q']}%").limit(5).all
@platforms = SupportedPlatform.where("name ILIKE :search", search: "#{params['q']}%").limit(5).all
render json: @tags.map(&:name) + @platforms.map(&:name)
end
end
|
Allow features to be cached throughout run call | require 'cucumber'
module Flatware
module Cucumber
class Runtime < ::Cucumber::Runtime
attr_accessor :configuration, :loader
attr_reader :out, :err
attr_reader :visitor
def initialize(out=StringIO.new, err=out)
@out, @err = out, err
super(default_configuration)
load_step_definitions
@results = Results.new(configuration)
end
def default_configuration
config = ::Cucumber::Cli::Configuration.new
config.parse! []
config
end
def run(feature_files=[])
options = Array(feature_files) + %w[--format Flatware::Cucumber::Formatter]
configure(::Cucumber::Cli::Main.new(options, out, err).configuration)
self.visitor = configuration.build_tree_walker(self)
visitor.visit_features(features)
results
end
private
def features
@loader = nil
super
end
end
end
end
| require 'cucumber'
module Flatware
module Cucumber
class Runtime < ::Cucumber::Runtime
attr_accessor :configuration, :loader
attr_reader :out, :err
attr_reader :visitor
def initialize(out=StringIO.new, err=out)
@out, @err = out, err
super(default_configuration)
load_step_definitions
@results = Results.new(configuration)
end
def default_configuration
config = ::Cucumber::Cli::Configuration.new
config.parse! []
config
end
def run(feature_files=[])
@loader = nil
options = Array(feature_files) + %w[--format Flatware::Cucumber::Formatter]
configure(::Cucumber::Cli::Main.new(options, out, err).configuration)
self.visitor = configuration.build_tree_walker(self)
visitor.visit_features(features)
results
end
end
end
end
|
Use localhost in a few tests again to ensure coverage. | Shindo.tests('Excon request methods') do
with_rackup('request_methods.ru') do
tests 'one-offs' do
tests('Excon.get').returns('GET') do
Excon.get('http://127.0.0.1:9292').body
end
tests('Excon.post').returns('POST') do
Excon.post('http://127.0.0.1:9292').body
end
end
tests 'with a connection object' do
connection = Excon.new('http://127.0.0.1:9292')
tests('connection.get').returns('GET') do
connection.get.body
end
tests('connection.post').returns('POST') do
connection.post.body
end
end
end
end
| Shindo.tests('Excon request methods') do
with_rackup('request_methods.ru') do
tests 'one-offs' do
tests('Excon.get').returns('GET') do
Excon.get('http://localhost:9292').body
end
tests('Excon.post').returns('POST') do
Excon.post('http://localhost:9292').body
end
end
tests 'with a connection object' do
connection = Excon.new('http://localhost:9292')
tests('connection.get').returns('GET') do
connection.get.body
end
tests('connection.post').returns('POST') do
connection.post.body
end
end
end
end
|
Add integration test for layout behaviour when signed out | require 'integration_test_helper'
class UnauthenticatedRequestsTest < ActionDispatch::IntegrationTest
should "not display the signed in user details when not present" do
visit "/auth/failure"
assert page.has_no_content?("Signed in as")
end
end
| |
Correct domain check when determining release version | require 'sinatra'
require 'uri'
require 'net/http'
require 'json'
class Travis::Web::SentryDeployHook < Sinatra::Base
set sentry_api_key: ENV['SENTRY_API_KEY']
set sentry_org: 'travis-ci'
set sentry_project: 'travis-web-h4'
set sentry_releases_endpoint: "https://app.getsentry.com/api/0/projects/#{settings.sentry_org}/#{settings.sentry_project}/releases/"
set github_commit_url: "https://github.com/travis-web/travis-ci/commit"
post '/deploy/hooks/sentry' do
version = determine_version(params["url"], params["head"])
request_body = {
version: version,
ref: params["head_long"],
url: "#{settings.github_commit_url}/#{params["head_long"]}"
}.to_json
url = URI(settings.sentry_releases_endpoint)
request = Net::HTTP::Post.new(url.request_uri, initheader = {'Content-Type' => 'application/json'})
request.basic_auth settings.sentry_api_key, ''
request.body = request_body
Net::HTTP.start(url.host, url.port, use_ssl: true) do |http|
http.request(request)
end
end
def determine_version(url, sha)
return sha unless url
domain = url.include?(".org") ? "org" : "com"
"#{domain}-#{sha}"
end
end
| require 'sinatra'
require 'uri'
require 'net/http'
require 'json'
class Travis::Web::SentryDeployHook < Sinatra::Base
set sentry_api_key: ENV['SENTRY_API_KEY']
set sentry_org: 'travis-ci'
set sentry_project: 'travis-web-h4'
set sentry_releases_endpoint: "https://app.getsentry.com/api/0/projects/#{settings.sentry_org}/#{settings.sentry_project}/releases/"
set github_commit_url: "https://github.com/travis-web/travis-ci/commit"
post '/deploy/hooks/sentry' do
version = determine_version(params["url"], params["head"])
request_body = {
version: version,
ref: params["head_long"],
url: "#{settings.github_commit_url}/#{params["head_long"]}"
}.to_json
url = URI(settings.sentry_releases_endpoint)
request = Net::HTTP::Post.new(url.request_uri, initheader = {'Content-Type' => 'application/json'})
request.basic_auth settings.sentry_api_key, ''
request.body = request_body
Net::HTTP.start(url.host, url.port, use_ssl: true) do |http|
http.request(request)
end
end
def determine_version(url, sha)
return sha unless url
domain = url.include?("travis-web-production") ? "org" : "com"
"#{domain}-#{sha}"
end
end
|
Remove deprecation warning for ActiveRecord 3 | require "active_record"
module PgSearch
def self.included(base)
base.send(:extend, ClassMethods)
end
module ClassMethods
def pg_search_scope(name)
named_scope(name)
end
end
end
| require "active_record"
module PgSearch
def self.included(base)
base.send(:extend, ClassMethods)
end
module ClassMethods
def pg_search_scope(name)
scope_method = if self.respond_to?(:scope) && !protected_methods.include?('scope')
:scope
else
:named_scope
end
send(scope_method, name)
end
end
end
|
Add prev_event, find_prev_event helper methods | module Lydown::Rendering
class Base
def initialize(event, context, stream, idx)
@event = event
@context = context
@stream = stream
@idx = idx
end
def translate
# do nothing by default
end
def next_event
idx = @idx + 1
while idx < @stream.size
e = @stream[idx]
return e if e && e[:type] != :comment
idx += 1
end
nil
end
end
end
| module Lydown::Rendering
class Base
def initialize(event, context, stream, idx)
@event = event
@context = context
@stream = stream
@idx = idx
end
def translate
# do nothing by default
end
def prev_event
idx = @idx - 1
while idx >= 0
e = @stream[idx]
return e if e && e[:type] != :comment
idx -= 1
end
nil
end
def find_prev_event(filter)
prev = prev_event
return nil unless prev
filter.each do |k, v|
return nil unless prev[k] == v
end
prev
end
def next_event
idx = @idx + 1
while idx < @stream.size
e = @stream[idx]
return e if e && e[:type] != :comment
idx += 1
end
nil
end
end
end
|
Fix compatibility with Rails < 3.2 | module RequestStore
class Railtie < ::Rails::Railtie
initializer "request_store.insert_middleware" do |app|
app.config.middleware.insert_after ActionDispatch::RequestId, RequestStore::Middleware
end
end
end
| module RequestStore
class Railtie < ::Rails::Railtie
initializer "request_store.insert_middleware" do |app|
if ActionDispatch.const_defined? :RequestId
app.config.middleware.insert_after ActionDispatch::RequestId, RequestStore::Middleware
else
app.config.middleware.insert_after Rack::MethodOverride, RequestStore::Middleware
end
end
end
end
|
Put card setup stuff into its own before_filter instead of overriding | require 'card_reuse'
module Spree
CheckoutController.class_eval do
include CardReuse
private
def before_payment
current_order.payments.destroy_all if request.put?
@cards = all_cards_for_user(@order.user)
end
# we are overriding this method in order to substitue in the exisiting card information
def object_params
# For payment step, filter order parameters to produce the expected nested attributes for a single payment and its source, discarding attributes for payment methods other than the one selected
if @order.payment?
if params[:payment_source].present? && source_params = params.delete(:payment_source)[params[:order][:payments_attributes].first[:payment_method_id].underscore]
if params[:existing_card]
credit_card = Spree::CreditCard.find(params[:existing_card])
authorize! :manage, credit_card
params[:order][:payments_attributes].first[:source] = credit_card
else
params[:order][:payments_attributes].first[:source_attributes] = source_params
end
end
if (params[:order][:payments_attributes])
params[:order][:payments_attributes].first[:amount] = @order.total
end
end
params[:order]
end
end
end
| require 'card_reuse'
module Spree
CheckoutController.class_eval do
include CardReuse
before_filter :setup_cards
private
def setup_cards
if @order.state == 'payment'
current_order.payments.destroy_all if request.put?
@cards = all_cards_for_user(@order.user)
end
end
# we are overriding this method in order to substitue in the exisiting card information
def object_params
# For payment step, filter order parameters to produce the expected nested attributes for a single payment and its source, discarding attributes for payment methods other than the one selected
if @order.payment?
if params[:payment_source].present? && source_params = params.delete(:payment_source)[params[:order][:payments_attributes].first[:payment_method_id].underscore]
if params[:existing_card]
credit_card = Spree::CreditCard.find(params[:existing_card])
authorize! :manage, credit_card
params[:order][:payments_attributes].first[:source] = credit_card
else
params[:order][:payments_attributes].first[:source_attributes] = source_params
end
end
if (params[:order][:payments_attributes])
params[:order][:payments_attributes].first[:amount] = @order.total
end
end
params[:order]
end
end
end
|
Test out unconfigured mail sending | require 'test_helper'
class SGMailerTest < Minitest::Test
def test_configuration_setups_a_client_with_api_key
api_key = 'xxx'
SGMailer.configure(api_key: api_key)
assert_equal api_key, SGMailer.client.api_key
end
def test_configuration_for_testing_client
SGMailer.configure(test_client: true)
assert SGMailer.client.is_a?(SGMailer::TestClient)
end
end
| require 'test_helper'
class SGMailerTest < Minitest::Test
def setup
SGMailer.client = nil
end
def test_configuration_setups_a_client_with_api_key
api_key = 'xxx'
SGMailer.configure(api_key: api_key)
assert_equal api_key, SGMailer.client.api_key
end
def test_configuration_for_testing_client
SGMailer.configure(test_client: true)
assert SGMailer.client.is_a?(SGMailer::TestClient)
end
def test_sending_without_configuration
assert_raises SGMailer::ConfigurationError do
SGMailer.send({})
end
end
end
|
Use correct path to the CSS/JS. | module SpreeGiftCard
module Generators
class InstallGenerator < Rails::Generators::Base
def add_javascripts
append_file "vendor/assets/javascripts/spree/frontend/all.js", "//= require store/spree_gift_card\n"
append_file "vendor/assets/javascripts/spree/backend/all.js", "//= require admin/spree_gift_card\n"
end
def add_stylesheets
inject_into_file "vendor/assets/stylesheets/spree/frontend/all.css", " *= require store/spree_gift_card\n", :before => /\*\//, :verbose => true
inject_into_file "vendor/assets/stylesheets/spree/backend/all.css", " *= require admin/spree_gift_card\n", :before => /\*\//, :verbose => true
end
def add_migrations
run 'rake railties:install:migrations FROM=spree_gift_card'
end
def run_migrations
res = ask "Would you like to run the migrations now? [Y/n]"
if res == "" || res.downcase == "y"
run 'rake db:migrate'
else
puts "Skipping rake db:migrate, don't forget to run it!"
end
end
end
end
end
| module SpreeGiftCard
module Generators
class InstallGenerator < Rails::Generators::Base
def add_javascripts
append_file "vendor/assets/javascripts/spree/frontend/all.js", "//= require spree/frontend/spree_gift_card\n"
append_file "vendor/assets/javascripts/spree/backend/all.js", "//= require spree/backend/spree_gift_card\n"
end
def add_stylesheets
inject_into_file "vendor/assets/stylesheets/spree/frontend/all.css", " *= require spree/frontend/spree_gift_card\n", :before => /\*\//, :verbose => true
inject_into_file "vendor/assets/stylesheets/spree/backend/all.css", " *= require spree/backend/spree_gift_card\n", :before => /\*\//, :verbose => true
end
def add_migrations
run 'rake railties:install:migrations FROM=spree_gift_card'
end
def run_migrations
res = ask "Would you like to run the migrations now? [Y/n]"
if res == "" || res.downcase == "y"
run 'rake db:migrate'
else
puts "Skipping rake db:migrate, don't forget to run it!"
end
end
end
end
end
|
Add a guard around checking if response is Hashie | module Tugboat
class AuthenticationMiddleware < Faraday::Middleware
extend Forwardable
def_delegators :'Faraday::Utils', :parse_query, :build_query
RED = "\e[31m"
CLEAR = "\e[0m"
def initialize(app, client_id, api_key)
@client_id = client_id
@api_key = api_key
super(app)
end
def call(env)
params = { 'client_id' => @client_id, 'api_key' => @api_key }.update query_params(env[:url])
env[:url].query = build_query params
begin
@app.call(env)
rescue Faraday::Error::ClientError => e
puts "#{RED}#{e}!#{CLEAR}\n"
if env[:body].status == "ERROR"
puts "\n#{RED}#{env[:body].error_message}#{CLEAR}\n\n"
end
puts "Double-check your parameters and configuration (in your ~/.tugboat file)"
exit 1
end
end
def query_params(url)
if url.query.nil? or url.query.empty?
{}
else
parse_query url.query
end
end
end
end
| module Tugboat
class AuthenticationMiddleware < Faraday::Middleware
extend Forwardable
def_delegators :'Faraday::Utils', :parse_query, :build_query
RED = "\e[31m"
CLEAR = "\e[0m"
def initialize(app, client_id, api_key)
@client_id = client_id
@api_key = api_key
super(app)
end
def call(env)
params = { 'client_id' => @client_id, 'api_key' => @api_key }.update query_params(env[:url])
env[:url].query = build_query params
begin
@app.call(env)
rescue Faraday::Error::ClientError => e
puts "#{RED}#{e}!#{CLEAR}\n"
if env[:body].is_a?(Hashie::Rash)
puts "\n#{RED}#{env[:body].error_message}#{CLEAR}\n\n"
end
puts "Double-check your parameters and configuration (in your ~/.tugboat file)"
exit 1
end
end
def query_params(url)
if url.query.nil? or url.query.empty?
{}
else
parse_query url.query
end
end
end
end
|
Add migration to fix bungled earlier custom rate limit migration. | class FixCustomRateLimits < Mongoid::Migration
def self.up
ApiUser.where(:settings.ne => nil).all.each do |user|
print "."
rate_limits = user.settings.rate_limits
if(rate_limits.present?)
puts "\n#{user.id}: #{user.email}"
# Force before_validation callbacks to be called even though we're
# saving with validations disabled. This ensures the automatic accuracy
# and distributed calculations happen for rate limits.
user.valid?
# Assign one of the limits to be primary if that hadn't gotten set.
if(rate_limits.none? { |limit| limit.response_headers })
primary = rate_limits.sort_by { |limit| limit.duration }.first
primary.response_headers = true
end
user.save!(:validate => false)
end
end
puts ""
end
def self.down
end
end
| |
Fix bug where the internal connections has was always being reset | module PivotalTracker
class Client
class NoToken < StandardError; end
class << self
attr_writer :use_ssl, :token
def use_ssl
@use_ssl || false
end
def token(username, password, method='post')
return @token if @token
response = if method == 'post'
RestClient.post 'https://www.pivotaltracker.com/services/v3/tokens/active', :username => username, :password => password
else
RestClient.get "https://#{username}:#{password}@www.pivotaltracker.com/services/v3/tokens/active"
end
@token= Nokogiri::XML(response.body).search('guid').inner_html
end
# this is your connection for the entire module
def connection(options={})
raise NoToken unless @token.present?
@connections = {}
@connections[@token] ||= RestClient::Resource.new("#{protocol}://www.pivotaltracker.com/services/v3", :headers => {'X-TrackerToken' => @token, 'Content-Type' => 'application/xml'})
end
protected
def protocol
use_ssl ? 'https' : 'http'
end
end
end
end
| module PivotalTracker
class Client
class NoToken < StandardError; end
class << self
attr_writer :use_ssl, :token
def use_ssl
@use_ssl || false
end
def token(username, password, method='post')
return @token if @token
response = if method == 'post'
RestClient.post 'https://www.pivotaltracker.com/services/v3/tokens/active', :username => username, :password => password
else
RestClient.get "https://#{username}:#{password}@www.pivotaltracker.com/services/v3/tokens/active"
end
@token= Nokogiri::XML(response.body).search('guid').inner_html
end
# this is your connection for the entire module
def connection(options={})
raise NoToken unless @token.present?
@connections ||= {}
@connections[@token] ||= RestClient::Resource.new("#{protocol}://www.pivotaltracker.com/services/v3", :headers => {'X-TrackerToken' => @token, 'Content-Type' => 'application/xml'})
end
protected
def protocol
use_ssl ? 'https' : 'http'
end
end
end
end
|
Remove the Chef 11 compatibility check in chef_gem | #
# Cookbook Name:: xml
# Recipe:: ruby
#
# Author:: Joseph Holsten (<joseph@josephholsten.com>)
#
# Copyright 2008-2016, Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
execute 'apt-get update' do
ignore_failure true
action :nothing
end.run_action(:run) if 'debian' == node['platform_family']
node.default['xml']['compiletime'] = true
include_recipe 'build-essential::default'
include_recipe 'xml::default'
if node['xml']['nokogiri']['use_system_libraries']
ENV['NOKOGIRI_USE_SYSTEM_LIBRARIES'] = node['xml']['nokogiri']['use_system_libraries'].to_s
end
chef_gem 'nokogiri' do
version node['xml']['nokogiri']['version'] if node['xml']['nokogiri']['version']
action :install
compile_time true if Chef::Resource::ChefGem.method_defined?(:compile_time)
end
| #
# Cookbook Name:: xml
# Recipe:: ruby
#
# Author:: Joseph Holsten (<joseph@josephholsten.com>)
#
# Copyright 2008-2016, Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
execute 'apt-get update' do
ignore_failure true
action :nothing
end.run_action(:run) if 'debian' == node['platform_family']
node.default['xml']['compiletime'] = true
include_recipe 'build-essential::default'
include_recipe 'xml::default'
if node['xml']['nokogiri']['use_system_libraries']
ENV['NOKOGIRI_USE_SYSTEM_LIBRARIES'] = node['xml']['nokogiri']['use_system_libraries'].to_s
end
chef_gem 'nokogiri' do
version node['xml']['nokogiri']['version'] if node['xml']['nokogiri']['version']
action :install
compile_time true
end
|
Fix required_ruby_version 1.9.3 => 2.2.0 in gemspec | $:.push File.expand_path("../lib", __FILE__)
require "webpacker/version"
Gem::Specification.new do |s|
s.name = "webpacker"
s.version = Webpacker::VERSION
s.authors = [ "David Heinemeier Hansson", "Gaurav Tiwari" ]
s.email = [ "david@basecamp.com", "gaurav@gauravtiwari.co.uk" ]
s.summary = "Use Webpack to manage app-like JavaScript modules in Rails"
s.homepage = "https://github.com/rails/webpacker"
s.license = "MIT"
s.bindir = "exe"
s.executables = `git ls-files -- exe/*`.split("\n").map { |f| File.basename(f) }
s.required_ruby_version = ">= 1.9.3"
s.add_dependency "activesupport", ">= 4.2"
s.add_dependency "railties", ">= 4.2"
s.add_dependency "rack-proxy", ">= 0.6.1"
s.add_development_dependency "bundler", "~> 1.12"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- test/*`.split("\n")
end
| $:.push File.expand_path("../lib", __FILE__)
require "webpacker/version"
Gem::Specification.new do |s|
s.name = "webpacker"
s.version = Webpacker::VERSION
s.authors = [ "David Heinemeier Hansson", "Gaurav Tiwari" ]
s.email = [ "david@basecamp.com", "gaurav@gauravtiwari.co.uk" ]
s.summary = "Use Webpack to manage app-like JavaScript modules in Rails"
s.homepage = "https://github.com/rails/webpacker"
s.license = "MIT"
s.bindir = "exe"
s.executables = `git ls-files -- exe/*`.split("\n").map { |f| File.basename(f) }
s.required_ruby_version = ">= 2.2.0"
s.add_dependency "activesupport", ">= 4.2"
s.add_dependency "railties", ">= 4.2"
s.add_dependency "rack-proxy", ">= 0.6.1"
s.add_development_dependency "bundler", "~> 1.12"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- test/*`.split("\n")
end
|
Update podspec to version 1.6.2 | Pod::Spec.new do | s |
s.name = 'ActionSheetPicker-3.0'
s.version = '1.6.1'
s.summary = 'Better version of ActionSheetPicker with support iOS7 and other improvements.'
s.homepage = 'http://skywinder.github.io/ActionSheetPicker-3.0'
s.license = 'BSD'
s.authors = {
'Petr Korolev' => 'https://github.com/skywinder',
'Tim Cinel' => 'email@timcinel.com',
}
s.source = { :git => 'https://github.com/skywinder/ActionSheetPicker-3.0.git', :tag => "#{s.version}" }
s.screenshots = [ "http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/date.png",
"http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/distance.png",
"http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/ipad.png",
"http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/string.png"]
s.requires_arc = true
s.ios.deployment_target = '6.1'
s.platform = :ios
s.public_header_files = 'ActionSheetPicker.h', 'Pickers/*.h'
s.source_files = 'ActionSheetPicker.h', 'Pickers/*.{h,m}'
s.framework = 'UIKit'
end
| Pod::Spec.new do | s |
s.name = 'ActionSheetPicker-3.0'
s.version = '1.6.2'
s.summary = 'Better version of ActionSheetPicker with support iOS7 and other improvements.'
s.homepage = 'http://skywinder.github.io/ActionSheetPicker-3.0'
s.license = 'BSD'
s.authors = {
'Petr Korolev' => 'https://github.com/skywinder',
'Tim Cinel' => 'email@timcinel.com',
}
s.source = { :git => 'https://github.com/skywinder/ActionSheetPicker-3.0.git', :tag => "#{s.version}" }
s.screenshots = [ "http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/date.png",
"http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/distance.png",
"http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/ipad.png",
"http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/string.png"]
s.requires_arc = true
s.ios.deployment_target = '6.1'
s.platform = :ios
s.public_header_files = 'ActionSheetPicker.h', 'Pickers/*.h'
s.source_files = 'ActionSheetPicker.h', 'Pickers/*.{h,m}'
s.framework = 'UIKit'
end
|
Check to make sure the loan is in a requested state before sending out the notification | class LoanObserver < ActiveRecord::Observer
def after_create(loan)
LoanNotifier.deliver_request_notification(loan)
end
def after_lent(loan)
LoanNotifier.deliver_approved_notification(loan)
end
def before_destroy(loan)
LoanNotifier.deliver_rejected_notification(loan)
end
end
| class LoanObserver < ActiveRecord::Observer
def after_create(loan)
if loan.status == 'Requested'
LoanNotifier.deliver_request_notification(loan)
end
end
def after_lent(loan)
LoanNotifier.deliver_approved_notification(loan)
end
def before_destroy(loan)
LoanNotifier.deliver_rejected_notification(loan)
end
end
|
Add day 01: Count Parens | puts ARGF.each_char.with_index.with_object([0]) { |(char, idx), answer|
next if char == "\n"
answer[0] += char == ?( ? 1 : -1
answer[1] ||= idx + 1 if answer[0] == -1
}
| |
Allow guests to look up order with their email | Spree::OrdersController.class_eval do
def check_authorization
session[:access_token] = params[:token] if params[:token]
order = Spree::Order.find_by_number(params[:id]) || current_order
#if url has ship_address_id we don't need token because it comes from the link in order confirm E-mail
if order != nil and params[:ship_address_id] == order.ship_address_id.to_s
session[:access_token] = order.token
end
if order
authorize! :edit, order, session[:access_token]
else
authorize! :create, Spree::Order.new
end
end
end
| Spree::OrdersController.class_eval do
def check_authorization
session[:access_token] = params[:token] if params[:token]
order = Spree::Order.find_by_number(params[:id]) || current_order
#if url has ship_address_id we don't need token because it comes from the link in order confirm E-mail
if order != nil and (params[:email] == order.email or params[:ship_address_id] == order.ship_address_id.to_s)
session[:access_token] = order.token
else
flash[:error] = "์
๋ ฅํ์ ์ ๋ณด๊ฐ ์ ํํ์ง ์์ต๋๋ค"
redirect_to login_path and return
end
if order
authorize! :edit, order, session[:access_token]
else
authorize! :create, Spree::Order.new
end
end
end
|
Change logger.debug to logger.info for see in the production.log the response of fb | module Facebook
class OpenGraph
FB_URL = 'https://graph.facebook.com/me/oigameapp:sign'
ACTIONS = {
:fax => :send,
:mailing => :send,
:petition => :sign
}
def initialize(access_token,app_id)
@graph = Koala::Facebook::API.new(access_token)
@app = @graph.get_object(app_id)
@access_token = access_token
end
def can_send_action? action
end
def send_action(class_name,fb_url)
fb_post ACTIONS[class_name.to_sym] , fb_url
end
protected
def fb_post(action, fb_url)
data = {}
data[:access_token] = @access_token
data[:campaign] = fb_url
data["fb:explicitly_shared"] = true
response = HTTParty.post("#{FB_URL}",:body => data)
Rails.logger.debug("FB RESPONSE: #{response.inspect}")
end
end
end
| module Facebook
class OpenGraph
FB_URL = 'https://graph.facebook.com/me/oigameapp:sign'
ACTIONS = {
:fax => :send,
:mailing => :send,
:petition => :sign
}
def initialize(access_token,app_id)
@graph = Koala::Facebook::API.new(access_token)
@app = @graph.get_object(app_id)
@access_token = access_token
end
def can_send_action? action
end
def send_action(class_name,fb_url)
fb_post ACTIONS[class_name.to_sym] , fb_url
end
protected
def fb_post(action, fb_url)
data = {}
data[:access_token] = @access_token
data[:campaign] = fb_url
data["fb:explicitly_shared"] = true
response = HTTParty.post("#{FB_URL}",:body => data)
Rails.logger.info("FB RESPONSE: #{response.inspect}")
end
end
end
|
Fix positional parameters in `phar_wrapper` | require 'formula'
require File.join(File.dirname(__FILE__), "../Requirements/php-meta-requirement")
require File.join(File.dirname(__FILE__), "../Requirements/phar-requirement")
class AbstractPhpPhar < Formula
def initialize(*)
super
end
def self.init
depends_on PhpMetaRequirement
depends_on PharRequirement
end
def phar_file
class_name = self.class.name.split("::").last
class_name.downcase + ".phar"
end
def phar_bin
class_name = self.class.name.split("::").last
class_name.downcase
end
def phar_wrapper
<<-EOS.undent
#!/usr/bin/env bash
/usr/bin/env php -d allow_url_fopen=On -d detect_unicode=Off #{libexec}/#{@real_phar_file} $*
EOS
end
def install
if phar_file == phar_bin
@real_phar_file = phar_file + ".phar"
File.rename(phar_file, @real_phar_file)
else
@real_phar_file = phar_file
end
libexec.install @real_phar_file
(libexec/phar_bin).write phar_wrapper
chmod 0755, (libexec/phar_bin)
bin.install_symlink (libexec/phar_bin)
end
test do
which phar_bin
end
end | require 'formula'
require File.join(File.dirname(__FILE__), "../Requirements/php-meta-requirement")
require File.join(File.dirname(__FILE__), "../Requirements/phar-requirement")
class AbstractPhpPhar < Formula
def initialize(*)
super
end
def self.init
depends_on PhpMetaRequirement
depends_on PharRequirement
end
def phar_file
class_name = self.class.name.split("::").last
class_name.downcase + ".phar"
end
def phar_bin
class_name = self.class.name.split("::").last
class_name.downcase
end
def phar_wrapper
<<-EOS.undent
#!/usr/bin/env bash
/usr/bin/env php -d allow_url_fopen=On -d detect_unicode=Off #{libexec}/#{@real_phar_file} "$@"
EOS
end
def install
if phar_file == phar_bin
@real_phar_file = phar_file + ".phar"
File.rename(phar_file, @real_phar_file)
else
@real_phar_file = phar_file
end
libexec.install @real_phar_file
(libexec/phar_bin).write phar_wrapper
chmod 0755, (libexec/phar_bin)
bin.install_symlink (libexec/phar_bin)
end
test do
which phar_bin
end
end
|
Fix odd behavior on sqlite 3.7.17 | # frozen_string_literal: true
tables = [:dynflow_actions, :dynflow_delayed_plans, :dynflow_steps, :dynflow_output_chunks]
Sequel.migration do
up do
if database_type == :sqlite && Gem::Version.new(SQLite3::SQLITE_VERSION) <= Gem::Version.new('3.7.17')
tables.each do |table|
alter_table(table) { drop_foreign_key [:execution_plan_uuid] }
end
end
end
down do
if database_type == :sqlite && Gem::Version.new(SQLite3::SQLITE_VERSION) <= Gem::Version.new('3.7.17')
tables.each do |table|
alter_table(table) { add_foreign_key [:execution_plan_uuid], :dynflow_execution_plans }
end
end
end
end
| |
Fix length of text fields | class FixLengthOfTextFields < ActiveRecord::Migration
def change
change_column :casino_proxy_tickets, :service, :text, :limit => nil
change_column :casino_service_tickets, :service, :text, :limit => nil
change_column :casino_ticket_granting_tickets, :user_agent, :text, :limit => nil
end
end
| |
Align submit buttons with other form inputs | module ButtonComponents
def submit_button(*args, &block)
options = args.extract_options!
if object.new_record?
loading = I18n.t('simple_form.creating')
else
loading = I18n.t('simple_form.updating')
end
options[:"data-loading-text"] =
[loading, options[:"data-loading-text"]].compact
options[:class] = ['btn-primary', options[:class]].compact
args << options
# rubocop:disable AssignmentInCondition
if cancel = options.delete(:cancel)
submit(*args, &block) + ' ' + template.link_to(
template.button_tag(I18n.t('simple_form.buttons.cancel'),
type: 'button', class: 'btn btn-default'), cancel)
else
submit(*args, &block)
end
# rubocop:enable AssignmentInCondition
end
end
SimpleForm::FormBuilder.send :include, ButtonComponents
| module ButtonComponents
def submit_button(*args, &block)
options = args.extract_options!
if object.new_record?
loading = I18n.t('simple_form.creating')
else
loading = I18n.t('simple_form.updating')
end
options[:"data-loading-text"] =
[loading, options[:"data-loading-text"]].compact
options[:class] = ['btn-primary', options[:class]].compact
args << options
# rubocop:disable AssignmentInCondition
if cancel = options.delete(:cancel)
template.content_tag :div, class: 'col-sm-offset-2' do
submit(*args, &block) + ' ' + template.link_to(
template.button_tag(I18n.t('simple_form.buttons.cancel'),
type: 'button', class: 'btn btn-default'), cancel)
end
else
submit(*args, &block)
end
# rubocop:enable AssignmentInCondition
end
end
SimpleForm::FormBuilder.send :include, ButtonComponents
|
Fix repository access in CollectionMemberService | # frozen_string_literal: true
module Hyrax
##
# Returns a list of solr documents for collections the item is a part of
class CollectionMemberService
include Blacklight::Configurable
attr_reader :item, :current_ability
copy_blacklight_config_from(CatalogController)
##
# @param [SolrDocument] item represents a work
# @param [Hyrax::Ability] ability
def self.run(item, ability)
new(item, ability).list_collections
end
def initialize(item, ability)
@item = item
@current_ability = ability
end
def list_collections
query = collection_search_builder.rows(1000)
resp = repository.search(query)
resp.documents
end
def collection_search_builder
@collection_search_builder ||= ParentCollectionSearchBuilder.new([:include_item_ids, :add_paging_to_solr, :add_access_controls_to_solr_params], self)
end
end
end
| # frozen_string_literal: true
module Hyrax
##
# Returns a list of solr documents for collections the item is a part of
class CollectionMemberService
include Blacklight::Configurable
attr_reader :item, :current_ability
copy_blacklight_config_from(CatalogController)
##
# @param [SolrDocument] item represents a work
# @param [Hyrax::Ability] ability
def self.run(item, ability)
new(item, ability).list_collections
end
def initialize(item, ability)
@item = item
@current_ability = ability
end
def list_collections
query = collection_search_builder.rows(1000)
resp = blacklight_config.repository.search(query)
resp.documents
end
def collection_search_builder
@collection_search_builder ||= ParentCollectionSearchBuilder.new([:include_item_ids, :add_paging_to_solr, :add_access_controls_to_solr_params], self)
end
end
end
|
Remove bundler version in gemspec | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'turnip/dry_run/version'
Gem::Specification.new do |spec|
spec.name = "turnip-dry_run"
spec.version = Turnip::DryRun::VERSION
spec.authors = ["Seiei Higa"]
spec.email = ["hanachin@gmail.com"]
spec.summary = %q{Do dry run for turnip feature specs to get some step metadata.}
spec.homepage = "https://github.com/hanachin/turnip-dry_run"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "https://rubygems.org"
end
spec.add_dependency "turnip", "~> 1.2.4"
spec.add_development_dependency "bundler", "~> 1.9"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'turnip/dry_run/version'
Gem::Specification.new do |spec|
spec.name = "turnip-dry_run"
spec.version = Turnip::DryRun::VERSION
spec.authors = ["Seiei Higa"]
spec.email = ["hanachin@gmail.com"]
spec.summary = %q{Do dry run for turnip feature specs to get some step metadata.}
spec.homepage = "https://github.com/hanachin/turnip-dry_run"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "https://rubygems.org"
end
spec.add_dependency "turnip", "~> 1.2.4"
spec.add_development_dependency "bundler"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec"
end
|
Fix adding of top topic to site, use slug_title instead of id | module Interactors
module Channels
class AddFact
include Pavlov::Interactor
arguments :fact, :channel
def execute
command :"channels/add_fact", @fact, @channel
if @fact.site
command :'site/add_top_topic', @fact.site.id.to_i, @channel.topic.id.to_s
end
command :create_activity, @channel.created_by, :added_fact_to_channel, @fact, @channel
end
def authorized?
@options[:no_current_user] == true or @options[:current_user]
end
end
end
end
| module Interactors
module Channels
class AddFact
include Pavlov::Interactor
arguments :fact, :channel
def execute
command :"channels/add_fact", @fact, @channel
if @fact.site
command :'site/add_top_topic', @fact.site.id.to_i, @channel.topic.slug_title
end
command :create_activity, @channel.created_by, :added_fact_to_channel, @fact, @channel
end
def authorized?
@options[:no_current_user] == true or @options[:current_user]
end
end
end
end
|
Configure bind and dhcp for Dublin | name "fafnir"
description "Master role applied to fafnir"
default_attributes(
:networking => {
:interfaces => {
:internal_ipv4 => {
:interface => "bond0",
:role => :internal,
:family => :inet,
:address => "10.0.64.2",
:bond => {
:mode => "802.3ad",
:lacprate => "fast",
:slaves => %w[eno1 eno2]
}
},
:external_ipv4 => {
:interface => "bond0.101",
:role => :external,
:family => :inet,
:address => "184.104.226.98"
},
:external_ipv6 => {
:interface => "bond0.101",
:role => :external,
:family => :inet6,
:address => "2001:470:1:b3b::2"
}
}
}
)
run_list(
"role[equinix-dub]",
"role[hp-g9]",
"role[gateway]",
"role[web-storage]"
)
| name "fafnir"
description "Master role applied to fafnir"
default_attributes(
:bind => {
:clients => "equinix-dub"
},
:dhcpd => {
:first_address => "10.0.79.1",
:last_address => "10.0.79.254"
},
:networking => {
:interfaces => {
:internal_ipv4 => {
:interface => "bond0",
:role => :internal,
:family => :inet,
:address => "10.0.64.2",
:bond => {
:mode => "802.3ad",
:lacprate => "fast",
:slaves => %w[eno1 eno2]
}
},
:external_ipv4 => {
:interface => "bond0.101",
:role => :external,
:family => :inet,
:address => "184.104.226.98"
},
:external_ipv6 => {
:interface => "bond0.101",
:role => :external,
:family => :inet6,
:address => "2001:470:1:b3b::2"
}
}
}
)
run_list(
"role[equinix-dub]",
"role[hp-g9]",
"role[gateway]",
"role[web-storage]"
)
|
Use the route of the engine | require 'spec_helper'
module EmberCart
describe CartsController do
describe 'GET index' do
before(:each) do
get :index, format: :json, use_route: :ember_cart
end
it { should respond_with :ok }
it { should respond_with_content_type /json/ }
end
describe 'PUT clear' do
let(:cart) { create(:cart_with_items) }
before do
put :clear, id: cart.id, format: :json#, use_route: :ember_cart
end
it { should respond_with :ok }
it { should respond_with_content_type /json/ }
end
end
end
| require 'spec_helper'
module EmberCart
describe CartsController do
describe 'GET index' do
before(:each) do
get :index, format: :json, use_route: :ember_cart
end
it { should respond_with :ok }
it { should respond_with_content_type /json/ }
end
describe 'PUT clear' do
let(:cart) { create(:cart_with_items) }
before do
put :clear, id: cart.id, format: :json, use_route: :ember_cart
end
it { should respond_with :ok }
it { should respond_with_content_type /json/ }
end
end
end
|
Fix sha256 checksum for iTerm2-2_9_20160403-nightly.zip | cask 'iterm2-nightly' do
version '2.9.20160403'
sha256 'b1992760bd943256d568cd2648a09b46b422489254984fc35aeb3a163f0ef7f9'
url "https://iterm2.com/downloads/nightly/iTerm2-#{version.dots_to_underscores}-nightly.zip"
appcast 'https://iterm2.com/appcasts/nightly.xml',
checkpoint: '401635318f2b6950c6c7791376828ae7511bad7932b79935871ba8bb39c01348'
name 'iTerm2'
homepage 'https://www.iterm2.com/'
license :gpl
app 'iTerm.app'
zap delete: '~/Library/Preferences/com.googlecode.iterm2.plist'
end
| cask 'iterm2-nightly' do
version '2.9.20160403'
sha256 '7aeb775f7e23b7ae07e0cac621cddf5bbce147fdadbbbad88e27ff96b7480d1c'
url "https://iterm2.com/downloads/nightly/iTerm2-#{version.dots_to_underscores}-nightly.zip"
appcast 'https://iterm2.com/appcasts/nightly.xml',
checkpoint: '401635318f2b6950c6c7791376828ae7511bad7932b79935871ba8bb39c01348'
name 'iTerm2'
homepage 'https://www.iterm2.com/'
license :gpl
app 'iTerm.app'
zap delete: '~/Library/Preferences/com.googlecode.iterm2.plist'
end
|
Use Ruby commands in preference to UNIX commands | require 'formula'
SOLR_START_SCRIPT = <<-end_script
#!/bin/sh
if [ -z "$1" ]; then
echo "Usage: $ solr path/to/config/dir"
else
cd %s/example && java -Dsolr.solr.home=$1 -jar start.jar
fi
end_script
class Solr <Formula
url 'http://apache.deathculture.net/lucene/solr/1.3.0/apache-solr-1.3.0.tgz'
homepage 'http://lucene.apache.org/solr/'
md5 '23774b077598c6440d69016fed5cc810'
def install
system "mkdir -p #{prefix}"
system "mv * #{prefix}"
(bin+'solr').write(SOLR_START_SCRIPT % prefix)
end
def caveats
<<-END_CAVEATS
To start solr:
$ solr path/to/solr/config/dir
See the solr homepage for more setup information:
$ brew home solr
END_CAVEATS
end
end
| require 'formula'
SOLR_START_SCRIPT = <<-end_script
#!/bin/sh
if [ -z "$1" ]; then
echo "Usage: $ solr path/to/config/dir"
else
cd %s/example && java -Dsolr.solr.home=$1 -jar start.jar
fi
end_script
class Solr <Formula
url 'http://apache.deathculture.net/lucene/solr/1.3.0/apache-solr-1.3.0.tgz'
homepage 'http://lucene.apache.org/solr/'
md5 '23774b077598c6440d69016fed5cc810'
def install
prefix.mkpath
prefix.install Dir['*']
(bin+'solr').write(SOLR_START_SCRIPT % prefix)
end
def caveats
<<-END_CAVEATS
To start solr:
$ solr path/to/solr/config/dir
See the solr homepage for more setup information:
$ brew home solr
END_CAVEATS
end
end
|
Mark behavior with the reported upstream bug | require File.expand_path('../../../spec_helper', __FILE__)
ruby_version_is "2.4" do
describe "Complex#finite?" do
it "returns true if magnitude is finite" do
(1+1i).finite?.should == true
end
it "returns false for positive infinity" do
value = Complex(Float::INFINITY, 42)
value.finite?.should == false
end
it "returns false for positive complex with infinite imaginary" do
value = Complex(1, Float::INFINITY)
value.finite?.should == false
end
it "returns false for negative infinity" do
value = -Complex(Float::INFINITY, 42)
value.finite?.should == false
end
it "returns false for negative complex with infinite imaginary" do
value = -Complex(1, Float::INFINITY)
value.finite?.should == false
end
it "returns true for NaN" do
value = Complex(Float::NAN, Float::NAN)
value.finite?.should == true
end
end
end
| require File.expand_path('../../../spec_helper', __FILE__)
ruby_version_is "2.4" do
describe "Complex#finite?" do
it "returns true if magnitude is finite" do
(1+1i).finite?.should == true
end
it "returns false for positive infinity" do
value = Complex(Float::INFINITY, 42)
value.finite?.should == false
end
it "returns false for positive complex with infinite imaginary" do
value = Complex(1, Float::INFINITY)
value.finite?.should == false
end
it "returns false for negative infinity" do
value = -Complex(Float::INFINITY, 42)
value.finite?.should == false
end
it "returns false for negative complex with infinite imaginary" do
value = -Complex(1, Float::INFINITY)
value.finite?.should == false
end
ruby_bug "#14014", "2.4"..."2.5" do
it "returns false for NaN" do
value = Complex(Float::NAN, Float::NAN)
value.finite?.should == false
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.