Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add a spec for $! inside at_exit{ } | require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/classes', __FILE__)
describe "Kernel.at_exit" do
it "is a private method" do
Kernel.should have_private_instance_method(:at_exit)
end
it "runs after all other code" do
ruby_exe("at_exit {print 5}; print 6").should == "65"
end
it "runs in reverse order of registration" do
code = "at_exit {print 4};at_exit {print 5}; print 6; at_exit {print 7}"
ruby_exe(code).should == "6754"
end
it "allows calling exit inside at_exit handler" do
code = "at_exit {print 3}; at_exit {print 4; exit; print 5}; at_exit {print 6}"
ruby_exe(code).should == "643"
end
end
describe "Kernel#at_exit" do
it "needs to be reviewed for spec completeness"
end
| require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/classes', __FILE__)
describe "Kernel.at_exit" do
it "is a private method" do
Kernel.should have_private_instance_method(:at_exit)
end
it "runs after all other code" do
ruby_exe("at_exit {print 5}; print 6").should == "65"
end
it "runs in reverse order of registration" do
code = "at_exit {print 4};at_exit {print 5}; print 6; at_exit {print 7}"
ruby_exe(code).should == "6754"
end
it "allows calling exit inside at_exit handler" do
code = "at_exit {print 3}; at_exit {print 4; exit; print 5}; at_exit {print 6}"
ruby_exe(code).should == "643"
end
it "gives access to the last raised exception" do
code = 'at_exit{ puts $! == $exception }; begin; raise "foo"; rescue => e; $exception = e; raise; end'
# The true is embedded in the stack trace of the uncaught exception
ruby_exe("STDERR=STDOUT; #{code}", :escape => true).should =~ /true/
end
end
describe "Kernel#at_exit" do
it "needs to be reviewed for spec completeness"
end
|
Add spec for 80chars template() exception | # encoding: utf-8
require 'spec_helper'
describe '80chars' do
let(:msg) { 'line has more than 80 characters' }
context 'file resource with a source line > 80c' do
let(:code) { "
file {
source => 'puppet:///modules/certificates/etc/ssl/private/wildcard.example.com.crt',
}"
}
it 'should not detect any problems' do
expect(problems).to have(0).problems
end
end
context 'length of lines with UTF-8 characters' do
let(:code) { "
# ββββββββββββββββββββββββββββββββββββ
# β Configuration β
# ββββββββββββββββββββββββββββββββββββ"
}
it 'should not detect any problems' do
expect(problems).to have(0).problems
end
end
context '81 character line' do
let(:code) { 'a' * 81 }
it 'should only detect a single problem' do
expect(problems).to have(1).problem
end
it 'should create a warning' do
expect(problems).to contain_warning(msg).on_line(1).in_column(80)
end
end
end
| # encoding: utf-8
require 'spec_helper'
describe '80chars' do
let(:msg) { 'line has more than 80 characters' }
context 'file resource with a source line > 80c' do
let(:code) { "
file {
source => 'puppet:///modules/certificates/etc/ssl/private/wildcard.example.com.crt',
}"
}
it 'should not detect any problems' do
expect(problems).to have(0).problems
end
end
context 'file resource with a template line > 80c' do
let(:code) { "
file {
content => template('mymodule/this/is/a/truely/absurdly/long/path/that/should/make/you/feel/bad'),
}"
}
it 'should not detect any problems' do
expect(problems).to have(0).problems
end
end
context 'length of lines with UTF-8 characters' do
let(:code) { "
# ββββββββββββββββββββββββββββββββββββ
# β Configuration β
# ββββββββββββββββββββββββββββββββββββ"
}
it 'should not detect any problems' do
expect(problems).to have(0).problems
end
end
context '81 character line' do
let(:code) { 'a' * 81 }
it 'should only detect a single problem' do
expect(problems).to have(1).problem
end
it 'should create a warning' do
expect(problems).to contain_warning(msg).on_line(1).in_column(80)
end
end
end
|
Send notification emails to eds@ | # encoding: utf-8
class NoisyWorkflow < ActionMailer::Base
default :from => "winston@alphagov.co.uk"
def make_noise(guide,action)
@guide = guide
@action = action
mail(:to => "dev@alphagov.co.uk",
:subject => "[GUIDES/ANSWERS] " + @action.friendly_description)
end
end
| # encoding: utf-8
class NoisyWorkflow < ActionMailer::Base
default :from => "winston@alphagov.co.uk"
def make_noise(guide,action)
@guide = guide
@action = action
mail(:to => "eds@alphagov.co.uk",
:subject => "[GUIDES/ANSWERS] " + @action.friendly_description)
end
end
|
Add team add and delete member feature spec | require 'spec_helper.rb'
feature 'Adding and removing member of a team', js: true do
let(:team1) { FactoryGirl::create(:team_with_players, {players_count: 2, required_size: 4})}
let(:user) { FactoryGirl::create(:user) }
let(:players) {
FactoryGirl::create_list(:tournament_participation, 5, tournament: team1.tournament)
team1.tournament.players - team1.players
}
before do
visit "#/home"
visit "#/login"
fill_in "email", with: user.email
fill_in "password", with: user.password
click_on "log-in-button"
visit "#/home/"
TournamentAdmin.create(user_id: user.id, tournament_id: team1.tournament_id, status: :main)
players
visit "#/teams/" + team1.id.to_s
click_on "edit-team"
end
scenario "Add member to a team when user exists and is a tournament admin", :raceable do
p1 = players[0]
within('h1', text: "#{p1.name} #{p1.surname}") do
click_on "add-member"
end
within('h1', text: "#{p1.name} #{p1.surname}") do
expect(page).to have_button("delete-member")
end
expect(TeamMembership.exists?(team_id: team1.id, player_id: p1.id)).to be true
end
scenario "Delete member from a team when user exists and is a tournament admin", :raceable do
p1 = team1.players.first
within('h1', text: "#{p1.name} #{p1.surname}") do
click_on "delete-member"
end
within('h1', text: "#{p1.name} #{p1.surname}") do
expect(page).to have_button("add-member")
end
expect(TeamMembership.exists?(team_id: team1.id, player_id: p1.id)).to be false
end
end
| |
Add comment on factory call | require 'rails_helper'
RSpec.describe SignaturesReport, type: :report do
let(:end_date_string) { '2016-05-09' }
let(:end_date) { Date.parse(end_date_string) }
let(:begin_date) { end_date - 6 }
let(:report) { SignaturesReport.for_week(ending: end_date) }
it 'instantiates a report based on the end of the week' do
expect(report.begin).to eq(begin_date)
expect(report.end).to eq(end_date)
expect(report.end - report.begin).to eq(6)
end
it 'generates CSV' do
FactoryGirl.create(:shift, :full, day: begin_date + 1)
round_trip = CSV.parse(report.to_csv)
expect(round_trip.size).to be > 1
expect(round_trip.first.size)
.to eq SignaturesReport::JOINED_HEADERS.size
end
end
| require 'rails_helper'
RSpec.describe SignaturesReport, type: :report do
let(:end_date_string) { '2016-05-09' }
let(:end_date) { Date.parse(end_date_string) }
let(:begin_date) { end_date - 6 }
let(:report) { SignaturesReport.for_week(ending: end_date) }
it 'instantiates a report based on the end of the week' do
expect(report.begin).to eq(begin_date)
expect(report.end).to eq(end_date)
expect(report.end - report.begin).to eq(6)
end
it 'generates CSV' do
# Create a shift inside our weekly report period
FactoryGirl.create(:shift, :full, day: begin_date + 1)
round_trip = CSV.parse(report.to_csv)
expect(round_trip.size).to be > 1
expect(round_trip.first.size)
.to eq SignaturesReport::JOINED_HEADERS.size
end
end
|
Remove comments in the podspec | #
# Be sure to run `pod spec lint MNTPullToReact.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
s.name = "MNTPullToReact"
s.version = "1.0.0"
s.summary = "One gesture, many actions. An evolution of Pull to Refresh."
s.homepage = "https://www.mention.com"
s.license = { :type => "Apache License, Version 2.0", :file => "LICENSE" }
s.author = { "Guillaume Sempe" => "guillaume@mention.com" }
s.social_media_url = "http://twitter.com/tx"
s.platform = :ios, "5.0"
s.source = { :git => "https://github.com/mentionapp/mntpulltoreact.git", :tag => "#{s.version}" }
s.source_files = "PullToReact/PullToReact/**/*.{h,m}"
s.public_header_files = "PullToReact/PullToReact/PullToReact.h, PullToReact/PullToReact/UITableView+MNTPullToReact.h, PullToReact/PullToReact/MNTPullToReactView.h"
s.requires_arc = true
end
| Pod::Spec.new do |s|
s.name = "MNTPullToReact"
s.version = "1.0.0"
s.summary = "One gesture, many actions. An evolution of Pull to Refresh."
s.homepage = "https://www.mention.com"
s.license = { :type => "Apache License, Version 2.0", :file => "LICENSE" }
s.author = { "Guillaume Sempe" => "guillaume@mention.com" }
s.social_media_url = "http://twitter.com/tx"
s.platform = :ios, "5.0"
s.source = { :git => "https://github.com/mentionapp/mntpulltoreact.git", :tag => "#{s.version}" }
s.source_files = "PullToReact/PullToReact/**/*.{h,m}"
s.public_header_files = "PullToReact/PullToReact/PullToReact.h, PullToReact/PullToReact/UITableView+MNTPullToReact.h, PullToReact/PullToReact/MNTPullToReactView.h"
s.requires_arc = true
end
|
Fix unit test for ironic::client class | #
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# Author: Emilien Macchi <emilien.macchi@enovance.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# Unit tests for ironic::client
#
require 'spec_helper'
describe 'ironic::client' do
on_supported_os({
:supported_os => OSDefaults.get_supported_os
}).each do |os,facts|
context "on #{os}" do
let (:facts) do
facts.merge!(OSDefaults.get_facts())
end
it { is_expected.to contain_class('ironic::client') }
end
end
end
| #
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# Author: Emilien Macchi <emilien.macchi@enovance.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# Unit tests for ironic::client
#
require 'spec_helper'
describe 'ironic::client' do
shared_examples_for 'ironic client' do
it { is_expected.to contain_class('ironic::deps') }
it { is_expected.to contain_class('ironic::params') }
it 'installs ironic client package' do
is_expected.to contain_package('python-ironicclient').with(
:ensure => 'present',
:name => platform_params[:client_package],
:tag => ['openstack', 'ironic-support-package']
)
end
end
on_supported_os({
:supported_os => OSDefaults.get_supported_os
}).each do |os,facts|
context "on #{os}" do
let (:facts) do
facts.merge!(OSDefaults.get_facts())
end
let :platform_params do
{ :client_package => 'python-ironicclient' }
end
it_behaves_like 'ironic client'
end
end
end
|
Test using parenthesis in dependency tables spec | require 'minitest_helper'
describe 'NQL::DepedencyTables' do
let(:parser) { Rasti::DB::NQL::SyntaxParser.new }
def parse(expression)
parser.parse expression
end
it 'must have no dependency tables' do
tree = parse 'column = 1'
tree.dependency_tables.must_be_empty
end
it 'must have one dependency table' do
tree = parse 'relation_table_one.relation_table_two.column = 1'
tree.dependency_tables.must_equal ['relation_table_one.relation_table_two']
end
it 'must have multiple dependency tables' do
tree = parse 'a.b.c = 1 & d.e: 2 | f.g.h = 1 | i = 4'
tree.dependency_tables.must_equal ['a.b', 'd', 'f.g']
end
it 'must have repeated sub-dependency' do
tree = parse 'a.b.c = 1 & a.d: 2'
tree.dependency_tables.must_equal ['a.b', 'a']
end
end | require 'minitest_helper'
describe 'NQL::DepedencyTables' do
let(:parser) { Rasti::DB::NQL::SyntaxParser.new }
def parse(expression)
parser.parse expression
end
it 'must have no dependency tables' do
tree = parse 'column = 1'
tree.dependency_tables.must_be_empty
end
it 'must have one dependency table' do
tree = parse 'relation_table_one.relation_table_two.column = 1'
tree.dependency_tables.must_equal ['relation_table_one.relation_table_two']
end
it 'must have multiple dependency tables' do
tree = parse 'a.b.c = 1 & (d.e: 2 | f.g.h = 1) | i = 4'
tree.dependency_tables.must_equal ['a.b', 'd', 'f.g']
end
it 'must have repeated sub-dependency' do
tree = parse 'a.b.c = 1 & a.d: 2'
tree.dependency_tables.must_equal ['a.b', 'a']
end
end |
Fix for csv options being present | module RenderAsCSV
def self.included(base)
base.alias_method_chain :render, :csv
end
def render_with_csv(options = nil, extra_options = {}, &block)
return render_without_csv(options, extra_options, &block) unless options.is_a?(Hash) and [:csv].present?
data = options.delete(:csv)
style = options.delete(:style) || :default
send_data Array(data).to_comma(style), options.merge(:type => :csv)
end
end
| module RenderAsCSV
def self.included(base)
base.alias_method_chain :render, :csv
end
def render_with_csv(options = nil, extra_options = {}, &block)
return render_without_csv(options, extra_options, &block) unless options.is_a?(Hash) and options[:csv].present?
data = options.delete(:csv)
style = options.delete(:style) || :default
send_data Array(data).to_comma(style), options.merge(:type => :csv)
end
end
|
Update Gemspec, so it can be built | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'bower2gem/version'
Gem::Specification.new do |spec|
spec.name = "bower2gem"
spec.version = Bower2Gem::VERSION
spec.authors = ["Sean Collins"]
spec.email = ["sean@cllns.com"]
spec.summary = %q{TODO: Write a short summary, because Rubygems requires one.}
spec.description = %q{TODO: Write a longer description or delete this line.}
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
# delete this section to allow pushing this gem to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
end
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.add_development_dependency "bundler", "~> 1.10"
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 'bower2gem/version'
Gem::Specification.new do |spec|
spec.name = "bower2gem"
spec.version = Bower2Gem::VERSION
spec.authors = ["Sean Collins"]
spec.email = ["sean@cllns.com"]
spec.summary = %q{Install assets from bower, for gemified assets.}
spec.homepage = "https://github.com/cllns/"
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.add_development_dependency "bundler", "~> 1.10"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec"
end
|
Change UDPBackned to be compatible with jruby. | require 'socket'
module Statue
class UDPBackend
attr_reader :address
def initialize(host = nil, port = nil)
@address = Addrinfo.udp(host || "127.0.0.1", port || 8125)
end
def collect_metric(metric)
if metric.sample_rate == 1 || rand < metric.sample_rate
send_to_socket metric.to_s
end
end
alias :<< :collect_metric
private
def socket
Thread.current[:statue_socket] ||= address.connect
end
def send_to_socket(message)
Statue.debug(message)
socket.send(message, 0)
rescue => e
Statue.error("#{e.class} #{e}")
nil
end
end
end
| require 'socket'
module Statue
class UDPBackend
attr_reader :host, :port
def initialize(host = nil, port = nil)
@host = host
@port = port
end
def collect_metric(metric)
if metric.sample_rate == 1 || rand < metric.sample_rate
send_to_socket metric.to_s
end
end
alias :<< :collect_metric
private
def socket
Thread.current[:statue_socket] ||= begin
socket = UDPSocket.new(Addrinfo.ip(host).afamily)
socket.connect(host, port)
end
end
def send_to_socket(message)
Statue.debug(message)
socket.send(message, 0)
rescue => e
Statue.error("#{e.class} #{e}")
nil
end
end
end
|
Add basic spec coverage for Term Recap Emails | # frozen_string_literal: true
require 'rails_helper'
describe 'term recap emails page', type: :feature do
let(:admin) { create(:admin, email: 'admin@wikiedu.org') }
let(:course) { create(:course, article_count: 2) }
before do
course.campaigns << Campaign.first
JoinCourse.new(course: course, user: admin, role: CoursesUsers::Roles::INSTRUCTOR_ROLE)
login_as admin
end
it 'lets admins send term recap emails' do
visit '/mass_email/term_recap'
select(Campaign.first.title, from: 'campaign')
click_button 'Send recap emails'
expect(page).to have_content('Emails are going out')
end
end
| |
Use size functions instead of constants. | require File.dirname(__FILE__) + '/../../spec_helper'
require 'matrix'
describe "Matrix#clone" do
it "needs to be reviewed for spec completeness" do
end
before(:each) do
@a = Matrix[[1, 2], [3, 4], [5, 6]]
end
it "returns a copy of the matrix, but with all the references different" do
b = @a.clone
b.class.should == Matrix
b.should == @a
b.should_not === @a
0.upto(2) do |i|
0.upto(1) do |j|
b[i, j].should == @a[i, j]
b[i, j].should_not === @a[i, j]
end
end
end
end
| require File.dirname(__FILE__) + '/../../spec_helper'
require 'matrix'
describe "Matrix#clone" do
it "needs to be reviewed for spec completeness" do
end
before(:each) do
@a = Matrix[[1, 2], [3, 4], [5, 6]]
end
it "returns a copy of the matrix, but with all the references different" do
b = @a.clone
b.class.should == Matrix
b.should == @a
b.should_not === @a
0.upto(@a.row_size - 1) do |i|
0.upto(@a.column_size - 1) do |j|
b[i, j].should == @a[i, j]
b[i, j].should_not === @a[i, j]
end
end
end
end
|
Clean up empty field test | require 'rails_helper'
describe Study do
context 'when patient data section exists' do
it 'should have expected sharing ipd value' do
xml=Nokogiri::XML(File.read('spec/support/xml_data/NCT02830269.xml'))
study=Study.new({xml: xml, nct_id: 'NCT02830269'}).create
expect(study.plan_to_share_ipd).to eq('Undecided')
end
end
context 'when patient data section does not exist' do
it 'should return nil' do
xml=Nokogiri::XML(File.read('spec/support/xml_data/example_study.xml'))
study=Study.new({xml: xml, nct_id: 'NCT02260193'}).create
#binding.pry
expect(study.plan_to_share_ipd).to eq('')
end
end
end
| require 'rails_helper'
describe Study do
context 'when patient data section exists' do
it 'should have expected sharing ipd value' do
xml=Nokogiri::XML(File.read('spec/support/xml_data/NCT02830269.xml'))
study=Study.new({xml: xml, nct_id: 'NCT02830269'}).create
expect(study.plan_to_share_ipd).to eq('Undecided')
end
end
context 'when patient data section does not exist' do
it 'should return empty string for sharing ipd value' do
xml=Nokogiri::XML(File.read('spec/support/xml_data/example_study.xml'))
study=Study.new({xml: xml, nct_id: 'NCT02260193'}).create
expect(study.plan_to_share_ipd).to eq('')
end
end
end
|
Fix api sign ups controller | module Api
class SignUpsController < BaseController
skip_before_action :authenticate!
private
def build_resource
@sign_up = Api::SignUp.new(resource_params)
end
def resource
@sign_up
end
def resource_params
params.permit(:email, :password, :password_confirmation)
end
end
end
| module Api
class SignUpsController < BaseController
skip_before_action :authenticate!
def create
build_resource
resource.save!
end
private
def build_resource
@sign_up = Api::SignUp.new(resource_params)
end
def resource
@sign_up
end
def resource_params
params.permit(:email, :password, :password_confirmation)
end
end
end
|
Migrate locations to Mapit areas. | class MigrateBsfLocationsToAreas < Mongoid::Migration
def self.up
BusinessSupportLocationMigrator.run
end
def self.down
BusinessSupportEdition.excludes(state: 'archived').each do |bs|
bs.update_attribute(:areas, [])
end
end
end
| |
Use code as message for non JSON responses | module Dnsimple
class Error < StandardError
end
# RequestError is raised when an API request fails for an client, a server error or invalid request information.
class RequestError < Error
attr_reader :http_response
def initialize(http_response)
@http_response = http_response
super(http_response.parsed_response["message"])
end
end
class NotFoundError < RequestError
end
class AuthenticationError < Error
end
class AuthenticationFailed < AuthenticationError
end
end
| module Dnsimple
class Error < StandardError
end
# RequestError is raised when an API request fails for an client, a server error or invalid request information.
class RequestError < Error
attr_reader :http_response
def initialize(http_response)
@http_response = http_response
super(message_from(http_response))
end
private
def message_from(http_response)
if http_response.headers["Content-Type"] == "application/json"
http_response.parsed_response["message"]
else
http_response.code
end
end
end
class NotFoundError < RequestError
end
class AuthenticationError < Error
end
class AuthenticationFailed < AuthenticationError
end
end
|
Add new actions to toggle user status (offline or online) | class Users::SessionsController < Devise::SessionsController
# before_action :configure_sign_in_params, only: [:create]
# GET /resource/sign_in
# def new
# super
# end
# POST /resource/sign_in
# def create
# super
# end
# DELETE /resource/sign_out
# def destroy
# super
# end
# protected
# If you have extra params to permit, append them to the sanitizer.
# def configure_sign_in_params
# devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute])
# end
end
| class Users::SessionsController < Devise::SessionsController
# before_action :configure_sign_in_params, only: [:create]
# GET /resource/sign_in
# def new
# super
# end
# POST /resource/sign_in
def create
user = User.find_by_email(params[:user][:email])
user.update(status: true)
super
end
# DELETE /resource/sign_out
def destroy
current_user.update(status: false)
super
end
# protected
# If you have extra params to permit, append them to the sanitizer.
# def configure_sign_in_params
# devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute])
# end
end
|
Bump to 0.3.2 to test CI/CD | # frozen_string_literal: true
module StoryBranch
VERSION = '0.3.1'
end
| # frozen_string_literal: true
module StoryBranch
VERSION = '0.3.2'
end
|
Remove route for new bing form page because added modal | Rails.application.routes.draw do
devise_for :users
resources :comments do
resources :comments
end
get '/languages/:language_id/queries/bing/new' => "queries#bing_new"
post '/languages/:language_id/queries/bing' => "queries#bing_create"
# namespace :queries do
# resources :comments, path: '/:query_id'
# end
shallow do
resources :languages do
resources :queries do
# 'lang/:lang_id/queries', 'lang/:lang_id/queries/new', 'queries/:id', 'queries/:id/edit' =>
# language_queries_path(@language), new_language_queries_path(@language), query_path(@query), edit_query_path(@query)
resources :comments
# 'queries/:query_id/comments', 'queries/:query_id/comments/new', 'comments/:id', 'comments/:id/edit' =>
# query_comments_path(@query), new_query_comments_path(@query), comment_path(@comment), edit_comment_path(@comment)
end
end
end
root :to => 'languages#index'
end
| Rails.application.routes.draw do
devise_for :users
resources :comments do
resources :comments
end
post '/languages/:language_id/queries/bing' => "queries#bing_create"
# namespace :queries do
# resources :comments, path: '/:query_id'
# end
shallow do
resources :languages do
resources :queries do
# 'lang/:lang_id/queries', 'lang/:lang_id/queries/new', 'queries/:id', 'queries/:id/edit' =>
# language_queries_path(@language), new_language_queries_path(@language), query_path(@query), edit_query_path(@query)
resources :comments
# 'queries/:query_id/comments', 'queries/:query_id/comments/new', 'comments/:id', 'comments/:id/edit' =>
# query_comments_path(@query), new_query_comments_path(@query), comment_path(@comment), edit_comment_path(@comment)
end
end
end
root :to => 'languages#index'
end
|
Add a routing test for the workflows controller. | #------------------------------------------------------------------------------
# Copyright (c) 2013, 2014 The University of Manchester, UK.
#
# BSD Licenced. See LICENCE.rdoc for details.
#
# Taverna Player was developed in the BioVeL project, funded by the European
# Commission 7th Framework Programme (FP7), through grant agreement
# number 283359.
#
# Author: Robert Haines
#------------------------------------------------------------------------------
require 'test_helper'
module TavernaPlayer
class WorkflowsControllerTest < ActionController::TestCase
setup do
@routes = TavernaPlayer::Engine.routes
end
test "should get index html" do
get :index
assert_response :success
end
test "should get index json" do
get :index, :format => :json
assert_response :success
end
end
end
| #------------------------------------------------------------------------------
# Copyright (c) 2013, 2014 The University of Manchester, UK.
#
# BSD Licenced. See LICENCE.rdoc for details.
#
# Taverna Player was developed in the BioVeL project, funded by the European
# Commission 7th Framework Programme (FP7), through grant agreement
# number 283359.
#
# Author: Robert Haines
#------------------------------------------------------------------------------
require 'test_helper'
module TavernaPlayer
class WorkflowsControllerTest < ActionController::TestCase
setup do
@routes = TavernaPlayer::Engine.routes
end
test "should route to workflows" do
assert_routing "/workflows",
{ :controller => "taverna_player/workflows", :action => "index" }, {},
{}, "Did not route correctly"
end
test "should get index html" do
get :index
assert_response :success
end
test "should get index json" do
get :index, :format => :json
assert_response :success
end
end
end
|
Update step definitions to support new 'user@sever' feature | Before do
FileUtils.mkdir(TEST_DIR)
Dir.chdir(TEST_DIR)
end
After do
Dir.chdir(TEST_DIR)
FileUtils.rm_rf(TEST_DIR)
end
class Output
def messages
@messages ||= []
end
def puts(message)
messages << message
end
end
#
# Start SCP steps
#
def output
@output ||= Output.new
end
Given /^I have an available server "([^"]*)"$/ do |remote_host|
@remote = []
@remote << remote_host
end
When /^"([^"]*)" as the file name$/ do |remote_path|
@remote << remote_path
end
When /^I run "([^"]*)"$/ do |arg1|
gd_scp = GrowlTransfer::GTScp.new(output)
gd_scp.download(@remote.join(':'), TEST_DIR)
end
Then /^I should see "([^"]*)"$/ do |status|
output.messages.should include(status)
end
Then /^TEST_DIR should contains "([^"]*)" file$/ do |arg1|
File.file?([TEST_DIR, arg1].join('/'))
end | Before do
FileUtils.mkdir(TEST_DIR)
Dir.chdir(TEST_DIR)
end
After do
Dir.chdir(TEST_DIR)
FileUtils.rm_rf(TEST_DIR)
end
class Output
def messages
@messages ||= []
end
def puts(message)
messages << message
end
end
#
# Start SCP steps
#
def output
@output ||= Output.new
end
Given /^I have ssh keyless auth setup on "([^"]*)"$/ do |remote_host|
@remote = []
@remote << remote_host
end
Given /^specify "([^"]*)" as the file name$/ do |remote_path|
@remote << remote_path
end
Given /^I specify "([^"]*)" as the username before the url$/ do |arg1|
@remote[0] = 'clint' + '@' + @remote[0]
end
When /^I run "([^"]*)"$/ do |arg1|
gd_scp = GrowlTransfer::GTScp.new(output)
gd_scp.download(@remote.join(':'), TEST_DIR)
end
Then /^I should see "([^"]*)"$/ do |status|
output.messages.should include(status)
end
Then /^TEST_DIR should contains "([^"]*)" file$/ do |arg1|
File.file?([TEST_DIR, arg1].join('/'))
end |
Load admin orgs from correct host | class Admin::RepositoryOrganisationsController < Admin::ApplicationController
def show
@org = RepositoryOrganisation.find_by_login(params[:login])
@top_repos = @org.repositories.open_source.source.order('status ASC NULLS FIRST, rank DESC NULLS LAST').limit(10)
@total_commits = @org.repositories.map{|r| r.contributions.sum(:count) }.sum
end
end
| class Admin::RepositoryOrganisationsController < Admin::ApplicationController
def show
@org = RepositoryOrganisation.host(current_host).find_by_login(params[:login])
@top_repos = @org.repositories.open_source.source.order('status ASC NULLS FIRST, rank DESC NULLS LAST').limit(10)
@total_commits = @org.repositories.map{|r| r.contributions.sum(:count) }.sum
end
end
|
Fix anomaly in the spirit world | module CrystalGaze
class EmailSpirit
attr_reader :name, :email, :local_part, :domain, :manifestation
def initialize(name, email)
@name = name
@email = email
@local_part, @domain = email.split("@")
@manifestation = EmailManifestation.of(local_part)
end
def manifest
manifest_as(name, domain = domain)
end
def manifest_as(name, domain = domain)
manifestation && manifestation.present(name, domain)
end
end
end
| module CrystalGaze
class EmailSpirit
attr_reader :name, :email, :local_part, :domain, :manifestation
def initialize(name, email)
@name = name
@email = email
@local_part, @domain = email.split("@")
@manifestation = EmailManifestation.of(local_part)
end
def manifest
manifest_as(name, domain)
end
def manifest_as(name, domain = domain)
manifestation && manifestation.present(name, domain)
end
end
end
|
Add checks to test about map data in response | require 'test_helper'
class MapsControllerTest < ActionDispatch::IntegrationTest
test "loads index JSON" do
get "/api/maps"
assert_response :success
end
end
| require 'test_helper'
class MapsControllerTest < ActionDispatch::IntegrationTest
setup do
@map = create(:map)
@map_segment = create(:map_segment, map: @map)
end
test "loads index JSON" do
get "/api/maps"
assert_response :success
assert_includes response.body, @map.name
assert_includes response.body, @map.map_type
assert_includes response.body, @map_segment.name
end
end
|
Use a cleaner context for Mockupfile evaluation | module HtmlMockup
# Loader for mockupfile
class Mockupfile
# @attr :path [Pathname] The path of the Mockupfile for this project
attr_accessor :path, :project
def initialize(project)
@project = project
@path = Pathname.new(project.path + "Mockupfile")
end
# Actually load the mockupfile
def load
if File.exist?(@path) && !self.loaded?
@source = File.read(@path)
eval @source, get_binding
@loaded = true
end
end
# Wether or not the Mockupfile has been loaded
def loaded?
@loaded
end
def release
if block_given?
yield(self.project.release)
end
self.project.release
end
def serve
if block_given?
yield(self.project.server)
end
self.project.server
end
alias :server :serve
protected
def get_binding
mockup = self
binding
end
end
end
| module HtmlMockup
# Loader for mockupfile
class Mockupfile
# This is the context for the mockupfile evaluation. It should be empty except for the
# #mockup method.
class Context
def initialize(mockupfile)
@_mockupfile = mockupfile
end
def mockup
@_mockupfile
end
def binding
::Kernel.binding
end
end
# @attr :path [Pathname] The path of the Mockupfile for this project
attr_accessor :path, :project
def initialize(project)
@project = project
@path = Pathname.new(project.path + "Mockupfile")
end
# Actually load the mockupfile
def load
if File.exist?(@path) && !self.loaded?
@source = File.read(@path)
context = Context.new(self)
eval @source, context.binding
@loaded = true
end
end
# Wether or not the Mockupfile has been loaded
def loaded?
@loaded
end
def release
if block_given?
yield(self.project.release)
end
self.project.release
end
def serve
if block_given?
yield(self.project.server)
end
self.project.server
end
alias :server :serve
end
end
|
Set this to use `base`, not `head` | require 'sinatra/base'
require 'json'
require 'octokit'
class CITutorial < Sinatra::Base
# !!! DO NOT EVER USE HARD-CODED VALUES IN A REAL APP !!!
# Instead, set and test environment variables, like below
ACCESS_TOKEN = ENV['MY_PERSONAL_TOKEN']
before do
@client ||= Octokit::Client.new(:access_token => ACCESS_TOKEN)
end
post '/event_handler' do
@payload = JSON.parse(params[:payload])
case request.env['HTTP_X_GITHUB_EVENT']
when "pull_request"
if @payload["action"] == "opened"
process_pull_request(@payload["pull_request"])
end
end
end
helpers do
def process_pull_request(pull_request)
puts "Processing pull request..."
@client.create_status(pull_request['head']['repo']['full_name'], pull_request['head']['sha'], 'pending')
sleep 2 # do busy work...
@client.create_status(pull_request['head']['repo']['full_name'], pull_request['head']['sha'], 'success')
puts "Pull request processed!"
end
end
end
| require 'sinatra/base'
require 'json'
require 'octokit'
class CITutorial < Sinatra::Base
# !!! DO NOT EVER USE HARD-CODED VALUES IN A REAL APP !!!
# Instead, set and test environment variables, like below
ACCESS_TOKEN = ENV['MY_PERSONAL_TOKEN']
before do
@client ||= Octokit::Client.new(:access_token => ACCESS_TOKEN)
end
post '/event_handler' do
@payload = JSON.parse(params[:payload])
case request.env['HTTP_X_GITHUB_EVENT']
when "pull_request"
if @payload["action"] == "opened"
process_pull_request(@payload["pull_request"])
end
end
end
helpers do
def process_pull_request(pull_request)
puts "Processing pull request..."
@client.create_status(pull_request['base']['repo']['full_name'], pull_request['head']['sha'], 'pending')
sleep 2 # do busy work...
@client.create_status(pull_request['base']['repo']['full_name'], pull_request['head']['sha'], 'success')
puts "Pull request processed!"
end
end
end
|
Write summary and homepage into gemspec | lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "ellen/syoboi_calendar/version"
Gem::Specification.new do |spec|
spec.name = "ellen-syoboi_calendar"
spec.version = Ellen::SyoboiCalendar::VERSION
spec.authors = ["Ryo Nakamura"]
spec.email = ["r7kamura@gmail.com"]
spec.summary = %q{TODO: Write a short summary. Required.}
spec.description = %q{TODO: Write a longer description. Optional.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake"
end
| lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "ellen/syoboi_calendar/version"
Gem::Specification.new do |spec|
spec.name = "ellen-syoboi_calendar"
spec.version = Ellen::SyoboiCalendar::VERSION
spec.authors = ["Ryo Nakamura"]
spec.email = ["r7kamura@gmail.com"]
spec.summary = "Ask today's Japanese anime line-up from cal.syoboi.jp."
spec.homepage = "https://github.com/r7kamura/ellen-syoboi_calendar"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake"
end
|
Add initial working method to return all contributor usernames from a repo | require 'rubygems'
require 'octokit'
require 'pp'
require 'json'
octo = Octokit.contribs('pengwynn/octokit')
pp octo | require 'rubygems'
require 'octokit'
require 'pp'
require 'json'
#returns an array of all usernames from a repo
def repo_contrib_locs(user_repo)
repo_contribs = Octokit.contribs(user_repo)
contrib_locs = repo_contribs.collect { |user| user.fetch("login") }
contrib_locs
end |
Make private_key and public_key raise exceptions if missing from config. | module RecaptchaMailhide
class Configuration
attr_accessor :private_key, :public_key
end
end
| module RecaptchaMailhide
class Configuration
attr_writer :private_key, :public_key
def private_key
raise "RecaptchaMailhide's private_key is not set. If you're using Rails add an initializer to config/initializers." unless @private_key
@private_key
end
def public_key
raise "RecaptchaMailhide's public_key is not set. If you're using Rails add an initializer to config/initializers." unless @public_key
@public_key
end
end
end
|
Remove Traceable module cuz doesnt work | module Embulk
module Input
class Googlespreadsheet < InputPlugin
module Traceable
def initialize(e)
message = "(#{e.class}) #{e}.\n\t#{e.backtrace.join("\t\n")}\n"
while e.respond_to?(:cause) and e.cause
# Java Exception cannot follow the JRuby causes.
message << "Caused by (#{e.cause.class}) #{e.cause}\n\t#{e.cause.backtrace.join("\t\n")}\n"
e = e.cause
end
super(message)
end
end
class ConfigError < ::Embulk::ConfigError
include Traceable
end
class DataError < ::Embulk::DataError
include Traceable
end
class CompatibilityError < DataError; end
class TypeCastError < DataError; end
class UnknownTypeError < DataError; end
end
end
end
| module Embulk
module Input
class Googlespreadsheet < InputPlugin
class ConfigError < ::Embulk::ConfigError
def initialize(e)
message = "(#{e.class}) #{e}.\n\t#{e.backtrace.join("\t\n")}\n"
while e.respond_to?(:cause) and e.cause
# Java Exception cannot follow the JRuby causes.
message << "Caused by (#{e.cause.class}) #{e.cause}\n\t#{e.cause.backtrace.join("\t\n")}\n"
e = e.cause
end
super(message)
end
end
class DataError < ::Embulk::DataError
def initialize(e)
message = "(#{e.class}) #{e}.\n\t#{e.backtrace.join("\t\n")}\n"
while e.respond_to?(:cause) and e.cause
# Java Exception cannot follow the JRuby causes.
message << "Caused by (#{e.cause.class}) #{e.cause}\n\t#{e.cause.backtrace.join("\t\n")}\n"
e = e.cause
end
super(message)
end
end
class CompatibilityError < DataError; end
class TypeCastError < DataError; end
class UnknownTypeError < DataError; end
end
end
end
|
Remove unnecessary and require 'rubygems' | require 'rubygems'
require 'test/unit'
if ENV['LEFTRIGHT']
begin
require 'leftright'
rescue LoadError
puts "Run `gem install leftright` to install leftright."
end
end
unless $LOAD_PATH.include? 'lib'
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join($LOAD_PATH.first, '..', 'lib'))
end
require 'faraday'
begin
require 'ruby-debug'
rescue LoadError
# ignore
else
Debugger.start
end
module Faraday
class TestCase < Test::Unit::TestCase
LIVE_SERVER = case ENV['LIVE']
when /^http/ then ENV['LIVE']
when nil then nil
else 'http://localhost:4567'
end
def test_default
assert true
end unless defined? ::MiniTest
end
end
require 'webmock/test_unit'
WebMock.disable_net_connect!(:allow => Faraday::TestCase::LIVE_SERVER)
| require 'test/unit'
if ENV['LEFTRIGHT']
begin
require 'leftright'
rescue LoadError
puts "Run `gem install leftright` to install leftright."
end
end
require 'faraday'
begin
require 'ruby-debug'
rescue LoadError
# ignore
else
Debugger.start
end
module Faraday
class TestCase < Test::Unit::TestCase
LIVE_SERVER = case ENV['LIVE']
when /^http/ then ENV['LIVE']
when nil then nil
else 'http://localhost:4567'
end
def test_default
assert true
end unless defined? ::MiniTest
end
end
require 'webmock/test_unit'
WebMock.disable_net_connect!(:allow => Faraday::TestCase::LIVE_SERVER)
|
Fix spec description to match the fact that it does not set the ivar | # encoding: utf-8
require 'spec_helper'
require File.expand_path('../fixtures/classes', __FILE__)
describe Immutable, '#freeze' do
subject { object.freeze }
let(:described_class) { Class.new(ImmutableSpecs::Object) }
before do
described_class.memoize(:test)
end
context 'with an unfrozen object' do
let(:object) { described_class.allocate }
it { should equal(object) }
it 'freezes the object' do
expect { subject }.to change(object, :frozen?).
from(false).
to(true)
end
it 'sets a memoization instance variable' do
object.should_not be_instance_variable_defined(:@__memory)
subject
object.instance_variable_get(:@__memory).should be_instance_of(Hash)
end
end
context 'with a frozen object' do
let(:object) { described_class.new }
it { should equal(object) }
it 'does not change the frozen state of the object' do
expect { subject }.to_not change(object, :frozen?)
end
it 'does not change the memoization instance variable' do
expect { subject }.to_not change { object.instance_variable_get(:@__memory) }
end
it 'sets an instance variable for memoization' do
subject.instance_variable_get(:@__memory).should be_instance_of(Hash)
end
end
end
| # encoding: utf-8
require 'spec_helper'
require File.expand_path('../fixtures/classes', __FILE__)
describe Immutable, '#freeze' do
subject { object.freeze }
let(:described_class) { Class.new(ImmutableSpecs::Object) }
before do
described_class.memoize(:test)
end
context 'with an unfrozen object' do
let(:object) { described_class.allocate }
it { should equal(object) }
it 'freezes the object' do
expect { subject }.to change(object, :frozen?).
from(false).
to(true)
end
it 'sets a memoization instance variable' do
object.should_not be_instance_variable_defined(:@__memory)
subject
object.instance_variable_get(:@__memory).should be_instance_of(Hash)
end
end
context 'with a frozen object' do
let(:object) { described_class.new }
it { should equal(object) }
it 'does not change the frozen state of the object' do
expect { subject }.to_not change(object, :frozen?)
end
it 'does not change the memoization instance variable' do
expect { subject }.to_not change { object.instance_variable_get(:@__memory) }
end
it 'does not set an instance variable for memoization' do
object.instance_variable_get(:@__memory).should be_instance_of(Hash)
subject
end
end
end
|
Add core spec for `break if a == 3` |
#
# specifying flor
#
# Tue Mar 22 06:44:32 JST 2016
#
require 'spec_helper'
describe 'Flor core' do
before :each do
@executor = Flor::TransientExecutor.new
end
describe 'a procedure on its own' do
it 'is returned' do
flon = %{
sequence
}
r = @executor.launch(flon)
expect(r['point']).to eq('terminated')
expect(r['payload']['ret']).to eq([ '_proc', 'sequence', -1 ])
end
end
describe 'a procedure with a least a child' do
it 'is executed' do
flon = %{
sequence _
}
r = @executor.launch(flon)
expect(r['point']).to eq('terminated')
expect(r['payload']['ret']).to eq(nil)
end
end
context 'common _att' do
describe 'vars' do
it 'does not set f.ret' do
flon = %{
sequence vars: { a: 1 }
}
r = @executor.launch(flon)
expect(r['point']).to eq('terminated')
expect(r['payload']['ret']).to eq(nil)
end
end
end
end
|
#
# specifying flor
#
# Tue Mar 22 06:44:32 JST 2016
#
require 'spec_helper'
describe 'Flor core' do
before :each do
@executor = Flor::TransientExecutor.new
end
describe 'a procedure on its own' do
it 'is returned' do
flon = %{
sequence
}
r = @executor.launch(flon)
expect(r['point']).to eq('terminated')
expect(r['payload']['ret']).to eq([ '_proc', 'sequence', -1 ])
end
end
describe 'a procedure with a least a child' do
it 'is executed' do
flon = %{
sequence _
}
r = @executor.launch(flon)
expect(r['point']).to eq('terminated')
expect(r['payload']['ret']).to eq(nil)
end
end
context 'a postfix conditional' do
it 'is a call wrapped' do
#
# `break if a == 3`
# is equivalent to
# ```
# ife a == 3
# break _
# ```
# (note the underscore)
flon = %{
set a 3
until true
break if a == 3
set a (+ a 1)
}
r = @executor.launch(flon)
expect(r['point']).to eq('terminated')
expect(r['payload']['ret']).to eq(nil)
end
end
context 'common _att' do
describe 'vars' do
it 'does not set f.ret' do
flon = %{
sequence vars: { a: 1 }
}
r = @executor.launch(flon)
expect(r['point']).to eq('terminated')
expect(r['payload']['ret']).to eq(nil)
end
end
end
end
|
Change to tenary operators for defaults | module Tugboat
module Middleware
class CreateDroplet < Base
def call(env)
ocean = env["ocean"]
say "Queueing creation of droplet '#{env["create_droplet_name"]}'...", nil, false
unless env["create_droplet_region_id"]
droplet_region_id = env["config"].default_region
else
droplet_region_id = env["create_droplet_region_id"]
end
unless env["create_droplet_image_id"]
droplet_image_id = env["config"].default_image
else
droplet_image_id = env["create_droplet_image_id"]
end
unless env["create_droplet_size_id"]
droplet_size_id = env["config"].default_size
else
droplet_size_id = env["create_droplet_size_id"]
end
req = ocean.droplets.create :name => env["create_droplet_name"],
:size_id => droplet_size_id,
:image_id => droplet_image_id,
:region_id => droplet_region_id,
:ssh_key_ids => env["create_droplet_ssh_key_ids"]
if req.status == "ERROR"
say req.error_message, :red
exit 1
end
say "done", :green
@app.call(env)
end
end
end
end
| module Tugboat
module Middleware
class CreateDroplet < Base
def call(env)
ocean = env["ocean"]
say "Queueing creation of droplet '#{env["create_droplet_name"]}'...", nil, false
env["create_droplet_region_id"] ?
droplet_region_id = env["create_droplet_region_id"] :
droplet_region_id = env["config"].default_region
env["create_droplet_image_id"] ?
droplet_image_id = env["create_droplet_image_id"] :
droplet_image_id = env["config"].default_image
env["create_droplet_size_id"] ?
droplet_size_id = env["create_droplet_size_id"] :
droplet_size_id = env["config"].default_size
req = ocean.droplets.create :name => env["create_droplet_name"],
:size_id => droplet_size_id,
:image_id => droplet_image_id,
:region_id => droplet_region_id,
:ssh_key_ids => env["create_droplet_ssh_key_ids"]
if req.status == "ERROR"
say req.error_message, :red
exit 1
end
say "done", :green
@app.call(env)
end
end
end
end
|
Remove gems we don't need and refactor gemspec dir lookups | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'walkon/version'
Gem::Specification.new do |spec|
spec.name = "walkon"
spec.version = Walkon::VERSION
spec.authors = ["Tom Scott"]
spec.email = ["tubbo@psychedeli.ca"]
spec.description = %q{Play your entrance music}
spec.summary = %q{Play your entrance music}
spec.homepage = "http://github.com/tubbo/walkon"
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{^(spec)/})
spec.require_paths = ["lib"]
spec.add_dependency 'resque'
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "pry"
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 'walkon/version'
Gem::Specification.new do |spec|
spec.name = "walkon"
spec.version = Walkon::VERSION
spec.authors = ["Tom Scott"]
spec.email = ["tubbo@psychedeli.ca"]
spec.description = %q{Play your entrance music}
spec.summary = %q{Play your entrance music}
spec.homepage = "http://github.com/tubbo/walkon"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.files = Dir["{bin,lib,spec}/**/*", "README.md", "Rakefile"]
spec.executables = Dir["bin/*"].map { |f| File.basename(f) }
spec.test_files = Dir["spec/**/*"]
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "pry"
spec.add_development_dependency "rspec"
end
|
Fix "idempotent method" shared example helper | # encoding: utf-8
shared_examples_for 'an idempotent method' do
it 'is idempotent' do
should equal(instance_eval(&self.class.subject))
end
end
| # encoding: utf-8
shared_examples_for 'an idempotent method' do
it 'is idempotent' do
first = subject
__memoized.delete(:subject)
should equal(first)
end
end
|
Join multiple rooms by running each room in a separate thread. | module Globot
class Bot
attr_accessor :id, :email, :name
def initialize(domain, token, opts = {})
Globot::Plugins.load!
connect(domain, token, opts)
end
def connect(domain, token, opts)
@campfire = Tinder::Campfire.new(domain, { :token => token })
me = @campfire.me
@id = me['id']
@email = me['email_address']
@name = me['name']
puts "Logged in as #{name} <#{email}> [ID##{id}]"
@rooms = @campfire.rooms
@rooms = @rooms.select { |r| opts[:rooms].include? r.name } if !opts[:rooms].nil?
end
def start
room = @rooms.first # just one room for now
room.listen do |msg|
begin
if !msg.nil? && msg['user']['id'] != id # ignore messages from myself
Globot::Plugins.handle Globot::Message.new(msg, room)
end
rescue Exception => e
trace = e.backtrace.join("\n")
puts "ERROR: #{e.message}\n#{trace}"
end
end
end
end
end
| module Globot
class Bot
attr_accessor :id, :email, :name
def initialize(domain, token, opts = {})
Globot::Plugins.load!
connect(domain, token, opts)
end
def connect(domain, token, opts)
@campfire = Tinder::Campfire.new(domain, { :token => token })
me = @campfire.me
@id = me['id']
@email = me['email_address']
@name = me['name']
puts "Logged in as #{name} <#{email}> [ID##{id}]"
@rooms = @campfire.rooms
@rooms = @rooms.select { |r| opts[:rooms].include? r.name } if !opts[:rooms].nil?
end
def start
# join each room
threads = []
@rooms.each do |room|
# `Room#listen` blocks, so run each one in a separate thread
threads << Thread.new do
begin
room.listen do |msg|
if !msg.nil? && msg['user']['id'] != id # ignore messages from myself
Globot::Plugins.handle Globot::Message.new(msg, room)
end
end
rescue Exception => e
trace = e.backtrace.join("\n")
puts "ERROR: #{e.message}\n#{trace}"
end
end
end
threads.each { |t| t.join }
end
end
end
|
Reconnect dead FreeSWITCH streams correctly | # encoding: utf-8
require 'ruby_fs'
module Punchblock
module Connection
class Freeswitch < GenericConnection
attr_reader :translator, :stream
attr_accessor :event_handler
def initialize(options = {})
@translator = Translator::Freeswitch.new self, options[:media_engine]
@stream = new_fs_stream(*options.values_at(:host, :port, :password))
super()
end
def run
pb_logger.debug "Starting the RubyFS stream"
@stream.run
raise DisconnectedError
end
def stop
stream.shutdown
translator.terminate
end
def write(command, options)
translator.execute_command! command, options
end
def handle_event(event)
event_handler.call event if event_handler.respond_to?(:call)
end
private
def new_fs_stream(*args)
RubyFS::Stream.new(*args, lambda { |e| translator.handle_es_event! e })
end
end
end
end
| # encoding: utf-8
require 'ruby_fs'
module Punchblock
module Connection
class Freeswitch < GenericConnection
attr_reader :translator, :stream
attr_accessor :event_handler
def initialize(options = {})
@translator = Translator::Freeswitch.new self, options[:media_engine]
@stream_options = options.values_at(:host, :port, :password)
@stream = new_fs_stream
super()
end
def run
pb_logger.debug "Starting the RubyFS stream"
start_stream
raise DisconnectedError
end
def stop
stream.shutdown
translator.terminate
end
def write(command, options)
translator.execute_command! command, options
end
def handle_event(event)
event_handler.call event if event_handler.respond_to?(:call)
end
private
def new_fs_stream
RubyFS::Stream.new(*@stream_options, lambda { |e| translator.handle_es_event! e })
end
def start_stream
@stream = new_fs_stream unless @stream.alive?
@stream.run
end
end
end
end
|
Use immersive organization in organization chooser | module OrganizationListHelper
def organizations_for(user)
# TODO use immersive contexts here
(user.student_granted_organizations + [Organization.central]).uniq.compact
end
end
| module OrganizationListHelper
def organizations_for(user)
user.immersive_organizations_at(nil)
end
end
|
Add test about refreshing size | require 'helper'
class TestRailsRelationFix< Test::Unit::TestCase
context "RailsRelationFix tests" do
setup do
@user = User.create(:name => "John Rambo")
@titanic = @user.movies.create(:name => "Titanic")
end
context "Models testing" do
should "User has movie" do
assert_equal(@titanic, @user.movies.first)
end
should "Movie belongs to user" do
assert_equal(@user, @titanic.subject)
end
end
context "Association bug tests" do
should "return empty collection after destroy its only movie" do
@user.movies.destroy(@titanic)
assert_equal([], @user.movies)
end
end
context "Counter_cache for polymorhpic association bug test" do
should "Update movies_count column after adding movie by <<" do
@user.movies << Movie.create(:name => "Matrix")
assert_equal(2, @user.reload.movies_count)
@titanic.destroy
assert_equal(1, @user.reload.movies_count)
end
end
end
end
| require 'helper'
class TestRailsRelationFix< Test::Unit::TestCase
context "RailsRelationFix tests" do
setup do
@user = User.create(:name => "John Rambo")
@titanic = @user.movies.create(:name => "Titanic")
end
context "Models testing" do
should "User has movie" do
assert_equal(@titanic, @user.movies.first)
end
should "Movie belongs to user" do
assert_equal(@user, @titanic.subject)
end
end
context "Association bug tests" do
should "return empty collection after destroy its only movie" do
@user.movies.destroy(@titanic)
assert_equal([], @user.movies)
end
end
context "Counter_cache for polymorhpic association bug test" do
should "Update movies_count column after adding movie by << or destroing" do
@user.movies << Movie.create(:name => "Matrix")
assert_equal(2, @user.reload.movies_count)
@titanic.destroy
assert_equal(1, @user.reload.movies_count)
end
should "Refresh size after adding movie by << or destroing" do
@user.movies << Movie.create(:name => "Matrix")
assert_equal(2, @user.movies.size)
@titanic.destroy
assert_equal(1, @user.movies.size)
end
end
end
end
|
Fix Pattern validator for rubinius | module JSchema
module Validator
class Pattern < SimpleValidator
private
self.keywords = ['pattern']
def validate_args(pattern)
Regexp.new(pattern)
true
rescue TypeError
invalid_schema 'pattern', pattern
end
def post_initialize(pattern)
@pattern = pattern
end
def valid_instance?(instance)
!!instance.match(@pattern)
end
def applicable_types
[String]
end
end
end
end
| module JSchema
module Validator
class Pattern < SimpleValidator
private
# Fix because of Rubinius
unless defined? PrimitiveFailure
class PrimitiveFailure < Exception
end
end
self.keywords = ['pattern']
def validate_args(pattern)
Regexp.new(pattern)
true
rescue TypeError, PrimitiveFailure
invalid_schema 'pattern', pattern
end
def post_initialize(pattern)
@pattern = pattern
end
def valid_instance?(instance)
!!instance.match(@pattern)
end
def applicable_types
[String]
end
end
end
end
|
Add expectations for help text output | gem "minitest"
require "minitest/autorun"
require "stringio"
require "yarrow"
class ConsoleRunnerTest < Minitest::Test
SUCCESS = 0
FAILURE = 1
def test_version_message_short
output_buffer = StringIO.new
app = Yarrow::ConsoleRunner.new ['yarrow', '-v'], output_buffer
assert_equal SUCCESS, app.run_application
assert_equal "Yarrow 0.1.0\n", output_buffer.string
end
def test_version_message_long
output_buffer = StringIO.new
app = Yarrow::ConsoleRunner.new ['yarrow', '--version'], output_buffer
assert_equal SUCCESS, app.run_application
assert_equal "Yarrow 0.1.0\n", output_buffer.string
end
def test_help_message_short
output_buffer = StringIO.new
app = Yarrow::ConsoleRunner.new ['yarrow', '-h'], output_buffer
assert_equal SUCCESS, app.run_application
assert_equal "Yarrow 0.1.0\n", output_buffer.string
end
def test_help_message_long
output_buffer = StringIO.new
app = Yarrow::ConsoleRunner.new ['yarrow', '--help'], output_buffer
assert_equal SUCCESS, app.run_application
assert_equal "Yarrow 0.1.0\n", output_buffer.string
end
end | gem "minitest"
require "minitest/autorun"
require "stringio"
require "yarrow"
class ConsoleRunnerTest < Minitest::Test
SUCCESS = 0
FAILURE = 1
def test_version_message_short
output_buffer = StringIO.new
app = Yarrow::ConsoleRunner.new ['yarrow', '-v'], output_buffer
assert_equal SUCCESS, app.run_application
assert_equal "Yarrow 0.1.0\n", output_buffer.string
end
def test_version_message_long
output_buffer = StringIO.new
app = Yarrow::ConsoleRunner.new ['yarrow', '--version'], output_buffer
assert_equal SUCCESS, app.run_application
assert_equal "Yarrow 0.1.0\n", output_buffer.string
end
def test_help_message_short
output_buffer = StringIO.new
app = Yarrow::ConsoleRunner.new ['yarrow', '-h'], output_buffer
assert_equal SUCCESS, app.run_application
assert_includes output_buffer.string, "Yarrow 0.1.0\n"
assert_includes output_buffer.string, "Path to the generated documentation"
end
def test_help_message_long
output_buffer = StringIO.new
app = Yarrow::ConsoleRunner.new ['yarrow', '--help'], output_buffer
assert_equal SUCCESS, app.run_application
assert_includes output_buffer.string, "Yarrow 0.1.0\n"
assert_includes output_buffer.string, "Path to the generated documentation"
end
end |
Disable instance monitoring in the suite as well | include_recipe 'aws::default'
aws_instance_monitoring 'enable detailed monitoring' do
aws_access_key node['aws_test']['key_id']
aws_secret_access_key node['aws_test']['access_key']
action :enable
end
| include_recipe 'aws::default'
aws_instance_monitoring 'enable detailed monitoring' do
aws_access_key node['aws_test']['key_id']
aws_secret_access_key node['aws_test']['access_key']
action :enable
end
aws_instance_monitoring 'disable detailed monitoring' do
aws_access_key node['aws_test']['key_id']
aws_secret_access_key node['aws_test']['access_key']
action :disable
end
|
Add git lessons fixture file | def git_lessons
{
'A Deeper Look at Git' => {
title: 'A Deeper Look at Git',
description: 'Beyond just `$ git add` and `$ git commit`...',
is_project: false,
url: '/git/lesson_a_deeper_look_at_git.md',
identifier_uuid: '52b17564-0e1d-4c4f-adfa-acba53bf9126',
},
'Using Git in the Real World' => {
title: 'Using Git in the Real World',
description: "We've just scratched the surface, so here's what to be aware of as you start developing more and more using Git.",
is_project: false,
url: '/git/lesson_using_git_in_the_real_world.md',
identifier_uuid: 'c8b7ccc1-8a16-4545-9d46-b9091d45c6b4',
},
}
end
| |
Update rake requirement from ~> 10.3.2 to ~> 12.3.1 | # coding: utf-8
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "railyard/version"
Gem::Specification.new do |spec|
spec.name = "railyard"
spec.version = Railyard::VERSION
spec.authors = ["Brandon Weiss"]
spec.email = ["brandon@anti-pattern.com"]
spec.summary = %q{Non-polluting Rails skeleton generator}
spec.description = %q{Generate Rails skeletons without having to globally install Rails and its bajillion dependencies.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "rake", "~> 10.3.2"
spec.add_dependency "bundler", "~> 1.16.4"
spec.add_dependency "thor", "~> 0.19.4"
end
| # coding: utf-8
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "railyard/version"
Gem::Specification.new do |spec|
spec.name = "railyard"
spec.version = Railyard::VERSION
spec.authors = ["Brandon Weiss"]
spec.email = ["brandon@anti-pattern.com"]
spec.summary = %q{Non-polluting Rails skeleton generator}
spec.description = %q{Generate Rails skeletons without having to globally install Rails and its bajillion dependencies.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "rake", "~> 12.3.1"
spec.add_dependency "bundler", "~> 1.16.4"
spec.add_dependency "thor", "~> 0.19.4"
end
|
Change into the filesystem dir before running engines | module CC
module CLI
class Analyze < Command
include CC::Analyzer
def initialize(_args = [])
super
process_args
end
def run
require_codeclimate_yml
runner = EnginesRunner.new(registry, formatter, source_dir, config)
runner.run
rescue EnginesRunner::InvalidEngineName => ex
fatal(ex.message)
rescue EnginesRunner::NoEnabledEngines
fatal("No enabled engines. Add some to your .codeclimate.yml file!")
end
private
def process_args
while arg = @args.shift
case arg
when '-f'
@formatter = Formatters.resolve(@args.shift)
when '--dev'
@dev_mode = true
end
end
rescue Formatters::Formatter::InvalidFormatterError => e
fatal(e.message)
end
def registry
EngineRegistry.new(@dev_mode)
end
def formatter
@formatter ||= Formatters::PlainTextFormatter.new
end
def source_dir
ENV["CODE_PATH"]
end
def config
CC::Yaml.parse(filesystem.read_path(CODECLIMATE_YAML))
end
end
end
end
| module CC
module CLI
class Analyze < Command
include CC::Analyzer
def initialize(_args = [])
super
process_args
end
def run
require_codeclimate_yml
Dir.chdir(ENV['FILESYSTEM_DIR']) do
runner = EnginesRunner.new(registry, formatter, source_dir, config)
runner.run
end
rescue EnginesRunner::InvalidEngineName => ex
fatal(ex.message)
rescue EnginesRunner::NoEnabledEngines
fatal("No enabled engines. Add some to your .codeclimate.yml file!")
end
private
def process_args
while arg = @args.shift
case arg
when '-f'
@formatter = Formatters.resolve(@args.shift)
when '--dev'
@dev_mode = true
end
end
rescue Formatters::Formatter::InvalidFormatterError => e
fatal(e.message)
end
def registry
EngineRegistry.new(@dev_mode)
end
def formatter
@formatter ||= Formatters::PlainTextFormatter.new
end
def source_dir
ENV["CODE_PATH"]
end
def config
CC::Yaml.parse(filesystem.read_path(CODECLIMATE_YAML))
end
end
end
end
|
Simplify the platform check logic | #
# Cookbook:: perl
# Recipe:: default
#
# Copyright:: 2009-2019, 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.
#
case node['platform']
when 'windows'
# https://chocolatey.org/packages/StrawberryPerl
chocolatey_package 'strawberryperl'
windows_path 'C:\\Strawberry\\perl\\bin' do
action :add
end
else
package node['perl']['packages']
cpanm = node['perl']['cpanm'].to_hash
directory File.dirname(cpanm['path']) do
recursive true
end
remote_file cpanm['path'] do
source cpanm['url']
checksum cpanm['checksum']
owner 'root'
group node['root_group']
mode '0755'
sensitive cpanm['suppress_diff']
end
end
| #
# Cookbook:: perl
# Recipe:: default
#
# Copyright:: 2009-2019, 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.
#
if platform?('windows')
# https://chocolatey.org/packages/StrawberryPerl
chocolatey_package 'strawberryperl'
windows_path 'C:\\Strawberry\\perl\\bin' do
action :add
end
else
package node['perl']['packages']
cpanm = node['perl']['cpanm'].to_hash
directory File.dirname(cpanm['path']) do
recursive true
end
remote_file cpanm['path'] do
source cpanm['url']
checksum cpanm['checksum']
owner 'root'
group node['root_group']
mode '0755'
sensitive cpanm['suppress_diff']
end
end
|
Update podspec for 0.0.2 release | Pod::Spec.new do |s|
s.name = 'CacheIsKing'
s.version = '0.0.1'
s.license = 'MIT'
s.summary = 'A simple cache that can hold Swift items'
s.homepage = 'https://github.com/nuudles/CacheIsKing'
s.authors = { 'Christopher Luu' => 'nuudles@gmail.com' }
s.source = { :git => 'https://github.com/nuudles/CacheIsKing.git', :tag => s.version }
s.ios.deployment_target = '8.0'
s.tvos.deployment_target = '9.0'
s.source_files = 'Source/*.swift'
s.requires_arc = true
end
| Pod::Spec.new do |s|
s.name = 'CacheIsKing'
s.version = '0.0.2'
s.license = 'MIT'
s.summary = 'A simple cache that can hold anything, including Swift items'
s.homepage = 'https://github.com/nuudles/CacheIsKing'
s.authors = { 'Christopher Luu' => 'nuudles@gmail.com' }
s.source = { :git => 'https://github.com/nuudles/CacheIsKing.git', :tag => s.version }
s.ios.deployment_target = '8.0'
s.tvos.deployment_target = '9.0'
s.source_files = 'Source/*.swift'
s.requires_arc = true
end
|
Add podspec to the repository | Pod::Spec.new do |s|
s.name = "MarvelAPIClient"
s.version = "0.0.1"
s.summary = "Marvel API Client implementation written in Swift."
s.author = "GoKarumi S.L."
s.homepage = "https://github.com/karumi/MarvelAPIClient"
s.license = "Apache License V2.0"
s.platform = :ios
s.platform = :ios, "8.0"
s.source = { :git => "git@github.com:Karumi/MarvelApiClient.git", :tag => s.version }
s.source_files = "Classes", "MarvelAPIClient/*.swift"
s.requires_arc = true
s.dependency "BothamNetworking"
end
| |
Clean up formatting in Windows recipe | #Make sure that this recipe only runs on Windows systems
if platform?("windows")
#This recipe needs providers included in the Windows cookbook
#Turn off hibernation
execute "powercfg-hibernation" do
command "powercfg.exe /h off"
action :run
end
#Set high performance power options
execute "powercfg-performance" do
command "powercfg -s 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c"
action :run
end
end
| #Make sure that this recipe only runs on Windows systems
if platform?("windows")
#Turn off hibernation
execute "powercfg-hibernation" do
command "powercfg.exe /h off"
action :run
end
#Set high performance power options
execute "powercfg-performance" do
command "powercfg -s 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c"
action :run
end
end
|
Clean up the gemspec and target v1.0.0 | # -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
require 'periscope/version'
Gem::Specification.new do |s|
s.name = 'periscope'
s.version = Periscope::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ['Steve Richert']
s.email = ['steve.richert@gmail.com']
s.homepage = 'https://github.com/laserlemon/periscope'
s.summary = %(Bring your models' scopes up above the surface.)
s.description = %(Periscope acts like attr_accessible or attr_protected, but for your models' scopes.)
s.rubyforge_project = 'periscope'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f) }
s.require_paths = ['lib']
s.add_dependency 'activesupport', '>= 3.0.0'
s.add_development_dependency 'rspec'
s.add_development_dependency 'sqlite3'
s.add_development_dependency 'activerecord', '>= 3.0.0'
end
| # encoding: utf-8
Gem::Specification.new do |gem|
gem.name = 'periscope'
gem.version = '1.0.0'
gem.authors = ['Steve Richert']
gem.email = ['steve.richert@gmail.com']
gem.description = %(Periscope: like attr_accessible, but for your models' scopes)
gem.summary = %(Bring your models' scopes up above the surface)
gem.homepage = 'https://github.com/laserlemon/periscope'
gem.add_dependency 'activesupport', '~> 3.0'
gem.add_development_dependency 'activerecord', '~> 3.0'
gem.add_development_dependency 'rspec', '~> 2.10'
gem.add_development_dependency 'sqlite3'
gem.files = `git ls-files`.split($\)
gem.test_files = gem.files.grep(/^spec/)
gem.require_paths = ['lib']
end
|
Add thor dependency to gemspec | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/allen/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Taylor Smith"]
gem.email = ["taylor.smith@imulus.com"]
gem.description = "Quickly build an Umbraco project"
gem.summary = "Quickly build an Umbraco project"
gem.homepage = ""
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "allen"
gem.require_paths = ["lib"]
gem.version = Allen::VERSION
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/allen/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Taylor Smith"]
gem.email = ["taylor.smith@imulus.com"]
gem.description = "Quickly build an Umbraco project"
gem.summary = "Quickly build an Umbraco project"
gem.homepage = ""
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "allen"
gem.require_paths = ["lib"]
gem.version = Allen::VERSION
gem.add_runtime_dependency(%q<thor>, [">= 0.16.0"])
end
|
Include bundler as a dev dependency. | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "boxer/version"
Gem::Specification.new do |s|
s.name = 'boxer'
s.version = Boxer::VERSION
s.authors = ['Brad Fults']
s.email = ['bfults@gmail.com']
s.homepage = 'http://github.com/h3h/boxer'
s.license = 'MIT'
s.summary = %q{
Easy custom-defined templates for JSON generation of objects in Ruby.
}
s.description = %q{
A composable templating system for generating JSON via Ruby hashes, with
different possible views on each object and runtime data passing.
}
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ['lib']
s.add_development_dependency 'rspec', '>= 2.0.0'
s.add_runtime_dependency 'activesupport', '>= 3.0.0'
end
| # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "boxer/version"
Gem::Specification.new do |s|
s.name = 'boxer'
s.version = Boxer::VERSION
s.authors = ['Brad Fults']
s.email = ['bfults@gmail.com']
s.homepage = 'http://github.com/h3h/boxer'
s.license = 'MIT'
s.summary = %q{
Easy custom-defined templates for JSON generation of objects in Ruby.
}
s.description = %q{
A composable templating system for generating JSON via Ruby hashes, with
different possible views on each object and runtime data passing.
}
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ['lib']
s.add_development_dependency 'bundler', '>= 1.0.10'
s.add_development_dependency 'rspec', '>= 2.0.0'
s.add_runtime_dependency 'activesupport', '>= 3.0.0'
end
|
Modify for no version or checksum since no specific version. | class Sqwiggle < Cask
url 'https://www.sqwiggle.com/download/mac'
homepage 'https://www.sqwiggle.com'
version '0.4.2'
sha1 '15c49c5443780749ca833605bd61f9ee0b4d8105'
link 'Sqwiggle.app'
end
| class Sqwiggle < Cask
url 'https://www.sqwiggle.com/download/mac'
homepage 'https://www.sqwiggle.com'
version 'latest'
no_checksum
link 'Sqwiggle.app'
end
|
Change Cask for proper use of version-less download URL | class Josm < Cask
url 'http://josm.openstreetmap.de/download/macosx/josm-macosx.zip'
homepage 'http://josm.openstreetmap.de'
version '6388'
sha1 'b7973548df871e7d7edd6f14bd0953f4786fae5a'
link 'JOSM.app'
end
| class Josm < Cask
url 'http://josm.openstreetmap.de/download/macosx/josm-macosx.zip'
homepage 'http://josm.openstreetmap.de'
version 'latest'
no_checksum
link 'JOSM.app'
end
|
Allow a percentage to be passed in for saving Bruce's configuration | require 'construct'
module Bruce
module ::ActionView
class Config
CONFIG_FILE = './config/bruce-output.yaml'
attr_reader :percent
def load
if File.exists?(CONFIG_FILE)
config = Construct.load File.read(CONFIG_FILE)
@percent = config[:percentage]
else
@percent = 0
end
end
def save
# Create new construct object
config = Construct.new
config.percentage = 80
# Produce output.yaml file
File.open(CONFIG_FILE, 'w') do |file|
file.puts config.to_yaml
end
end
end
end
end
| require 'construct'
module Bruce
module ::ActionView
class Config
CONFIG_FILE = './config/bruce-output.yaml'
attr_reader :percent
def load
if File.exists?(CONFIG_FILE)
config = Construct.load File.read(CONFIG_FILE)
@percent = config[:percentage]
else
@percent = 0
end
end
def save(percentage = 0)
# Create new construct object
config = Construct.new({percentage: percentage})
# Produce output.yaml file
File.open(CONFIG_FILE, 'w') do |file|
file.puts config.to_yaml
end
end
end
end
end
|
Add invitations path to blacklist stored paths | class ApplicationController < ActionController::Base
UNSTORED_LOCATIONS = ['/users/sign_up', '/users/sign_in', '/users/password', 'users/sign_out']
before_filter :store_location
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def store_location
if !UNSTORED_LOCATIONS.include?(request.fullpath) && !request.xhr?
session[:previous_url] = request.fullpath
end
end
def after_sign_in_path_for(resource)
session[:previous_url] || inbox_account_conversations_path(resource.accounts.first)
end
# private
def authorize!(policy)
policy.access? || raise(ActiveRecord::RecordNotFound)
end
end
| class ApplicationController < ActionController::Base
UNSTORED_LOCATIONS = ['/users/sign_up', '/users/sign_in', '/users/password', '/users/sign_out', '/users/invitation']
before_filter :store_location
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def store_location
if !UNSTORED_LOCATIONS.include?(request.fullpath) && !request.xhr?
session[:previous_url] = request.fullpath
end
end
def after_sign_in_path_for(resource)
session[:previous_url] || inbox_account_conversations_path(resource.accounts.first)
end
# private
def authorize!(policy)
policy.access? || raise(ActiveRecord::RecordNotFound)
end
end
|
Speed up Ability definition on person by not using scope. | class Ability
include CanCan::Ability
def initialize(person)
# person
can :update, person
can :update, Person.undeleted, family: person.family if person.adult?
can :manage, Person if person.admin?(:edit_profiles)
# family
can :update, person.family if person.adult?
can :manage, Family if person.admin?(:edit_profiles)
# group
can [:update, :destroy], Group, memberships: {person: person, admin: true}
can :manage, Group if person.admin?(:manage_groups)
# album
can [:update, :destroy], Album, person: person
can :manage, Album if person.admin?(:manage_pictures)
end
end
| class Ability
include CanCan::Ability
def initialize(person)
# person
can :update, person
can :update, Person, family: person.family, deleted: false if person.adult?
can :manage, Person if person.admin?(:edit_profiles)
# family
can :update, person.family if person.adult?
can :manage, Family if person.admin?(:edit_profiles)
# group
can [:update, :destroy], Group, memberships: {person: person, admin: true}
can :manage, Group if person.admin?(:manage_groups)
# album
can [:update, :destroy], Album, person: person
can :manage, Album if person.admin?(:manage_pictures)
end
end
|
Clear thumbnail if needed when picture updated | class IdentityFile < MyplaceonlineActiveRecord
include AllowExistingConcern
belongs_to :encrypted_password, class_name: EncryptedValue, dependent: :destroy
has_attached_file :file, :storage => :database
do_not_validate_attachment_file_type :file
belongs_to :folder, class_name: IdentityFileFolder
accepts_nested_attributes_for :folder
allow_existing :folder, IdentityFileFolder
def display
file_file_name
end
def get_password(session)
if !encrypted_password.nil?
Myp.decrypt_from_session(session, encrypted_password)
else
nil
end
end
def size
file_file_size
end
end
| class IdentityFile < MyplaceonlineActiveRecord
include AllowExistingConcern
before_update :do_before_update
belongs_to :encrypted_password, class_name: EncryptedValue, dependent: :destroy
has_attached_file :file, :storage => :database
do_not_validate_attachment_file_type :file
belongs_to :folder, class_name: IdentityFileFolder
accepts_nested_attributes_for :folder
allow_existing :folder, IdentityFileFolder
def display
file_file_name
end
def get_password(session)
if !encrypted_password.nil?
Myp.decrypt_from_session(session, encrypted_password)
else
nil
end
end
def size
file_file_size
end
def do_before_update
if self.file_file_size_changed?
# Make sure any thumbnail is cleared (if it's a picture)
self.thumbnail_contents = nil
self.thumbnail_bytes = nil
end
end
end
|
Fix rerunning sample specs without new dummy app. | require 'spec_helper'
describe "Load samples" do
it "doesn't raise any error" do
expect {
SpreeSample::Engine.load_samples
}.to_not raise_error
end
end
| require 'spec_helper'
describe "Load samples" do
before do
# Seeds are only run for rake test_app so to allow this spec to pass without
# rerunning rake test_app every time we must load them in if not already.
unless Spree::Zone.find_by_name("North America")
load Rails.root + 'Rakefile'
load Rails.root + 'db/seeds.rb'
end
end
it "doesn't raise any error" do
expect {
SpreeSample::Engine.load_samples
}.to_not raise_error
end
end
|
Revert "Does lazy work here?" | default[:teamcity][:version] = "9.0.1"
default[:teamcity][:host] = "localhost"
default[:teamcity][:port] = "8111"
default[:teamcity][:url] = lazy "http://#{node[:teamcity][:host]}:#{node[:teamcity][:port]}/"
default[:teamcity][:user] = "teamcity"
default[:teamcity][:path] = "/usr/local/teamcity"
default[:teamcity][:data_path] = "/var/teamcity"
default[:teamcity][:user_home] = lazy "/home/#{node[:teamcity][:user]}"
default[:teamcity][:file_name] = lazy "TeamCity-#{node[:teamcity][:version]}.tar.gz"
default[:teamcity][:download_url] = lazy "http://download.jetbrains.com/teamcity/#{node[:teamcity][:file_name]}"
default[:teamcity][:download_path] = Chef::Config[:file_cache_path]
default[:teamcity][:install_path] = lazy "#{node[:teamcity][:path]}-#{node[:teamcity][:version]}"
| default[:teamcity][:version] = "9.0.1"
default[:teamcity][:host] = "localhost"
default[:teamcity][:port] = "8111"
default[:teamcity][:url] = "http://#{node[:teamcity][:host]}:#{node[:teamcity][:port]}/"
default[:teamcity][:user] = "teamcity"
default[:teamcity][:path] = "/usr/local/teamcity"
default[:teamcity][:data_path] = "/var/teamcity"
default[:teamcity][:user_home] = "/home/#{node[:teamcity][:user]}"
default[:teamcity][:file_name] = "TeamCity-#{node[:teamcity][:version]}.tar.gz"
default[:teamcity][:download_url] = "http://download.jetbrains.com/teamcity/#{node[:teamcity][:file_name]}"
default[:teamcity][:download_path] = Chef::Config[:file_cache_path]
default[:teamcity][:install_path] = "#{node[:teamcity][:path]}-#{node[:teamcity][:version]}"
|
Fix gemspec for deployment in environments | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/eventbus/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Stephan Altmueller"]
gem.email = ["saltmueller@wgen.net"]
gem.description = %q{TODO: Write a gem description}
gem.summary = %q{TODO: Write a gem summary}
gem.homepage = ""
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "eventbus"
gem.require_paths = ["lib"]
gem.version = Eventbus::VERSION
end | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/eventbus/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Stephan Altmueller"]
gem.email = ["saltmueller@wgen.net"]
gem.description = %q{TODO: Write a gem description}
gem.summary = %q{TODO: Write a gem summary}
gem.homepage = ""
gem.files = Dir['conf/*yml', 'lib/**/*.rb', 'test/*.rb', 'test/data/*.json', '*rb'] + ['Gemfile','Rakefile', 'eventbus.gemspec']
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "eventbus"
gem.require_paths = ["lib"]
gem.version = Eventbus::VERSION
end |
Use alias_method instead of method define | # Copyright (C) 2015 Ruby-GNOME2 Project Team
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
module Gtk
class IconTheme
def icons(context=nil)
list_icons(context)
end
alias_method :choose_icon_raw, :choose_icon
def choose_icon(icon_name, size, flags=nil)
if flags.nil?
flags = :generic_fallback
end
choose_icon_raw(icon_name, size, flags)
end
def contexts
list_contexts
end
end
end
| # Copyright (C) 2015 Ruby-GNOME2 Project Team
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
module Gtk
class IconTheme
alias_method :icons, :list_icons
alias_method :contexts, :list_contexts
alias_method :choose_icon_raw, :choose_icon
def choose_icon(icon_name, size, flags=nil)
if flags.nil?
flags = :generic_fallback
end
choose_icon_raw(icon_name, size, flags)
end
end
end
|
Load courses for user dynamically in dashboard | class DashboardsController < ApplicationController
before_filter :login_required, :only => [:index]
layout "water"
def show
@student_courses = current_user.student.given_courses
@assistant_courses = current_user.assistant.given_courses
end
def index
end
def update
end
end
| class DashboardsController < ApplicationController
before_filter :login_required, :only => [:index]
layout "water"
def show
# Fetches all courses for all roles for the given user
["student", "assistant"].each do |r|
if role = current_user.send(r)
instance_variable_set("@#{r}_courses", role.given_courses)
end
end
end
def index
end
def update
end
end
|
Index filtered fields on Task | class IndexFilteredFieldsOnTask < ActiveRecord::Migration
def self.up
add_index :tasks, :requestor_id
add_index :tasks, :target_id
add_index :tasks, :target_type
add_index :tasks, [:target_id, :target_type]
add_index :tasks, :status
end
def self.down
remove_index :tasks, :requestor_id
remove_index :tasks, :target_id
remove_index :tasks, :target_type
remove_index :tasks, [:target_id, :target_type]
remove_index :tasks, :status
end
end
| |
Remove stupid dependancy to acts_as_state_machine | require 'acts_as_state_machine'
ActiveRecord::Base.class_eval do
include SimpleStateMachine
end
| require 'simple_state_machine'
ActiveRecord::Base.class_eval do
include SimpleStateMachine
end
|
Use env var for default from email | class ApplicationMailer < ActionMailer::Base
default from: "noreply@openhq.com"
layout 'mailer'
end | class ApplicationMailer < ActionMailer::Base
default from: ENV['MAILGUN_FROM_EMAIL']
layout 'mailer'
end
|
Fix the module name here as well | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'vagrant-free-memory/version'
Gem::Specification.new do |spec|
spec.name = "vagrant-free-memory"
spec.version = Vagrant::Free::Memory::VERSION
spec.authors = ["Robby Colvin"]
spec.email = ["geetarista@gmail.com"]
spec.description = %q{Vagrant plugin example from the book Vagrant: Up and Running}
spec.summary = %q{Functioning example for beginning with Vagrant plugin development.}
spec.homepage = "https://github.com/geetarista/vagrant-free-memory"
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 'vagrant-free-memory/version'
Gem::Specification.new do |spec|
spec.name = "vagrant-free-memory"
spec.version = VagrantFreeMemory::VERSION
spec.authors = ["Robby Colvin"]
spec.email = ["geetarista@gmail.com"]
spec.description = %q{Vagrant plugin example from the book Vagrant: Up and Running}
spec.summary = %q{Functioning example for beginning with Vagrant plugin development.}
spec.homepage = "https://github.com/geetarista/vagrant-free-memory"
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
|
Refactor env var test helpers | RSpec.configure do |config|
config.around(:each) do |example|
orig_auth_endpoint = ENV['G5_AUTH_ENDPOINT']
ENV['G5_AUTH_ENDPOINT'] = 'https://test.auth.host'
example.run
ENV['G5_AUTH_ENDPOINT'] = orig_auth_endpoint
end
end
| module G5Authenticatable
module Test
module EnvHelpers
def stub_env_var(name, value)
stub_const('ENV', ENV.to_hash.merge(name => value))
end
end
end
end
RSpec.configure do |config|
config.include G5Authenticatable::Test::EnvHelpers
config.before(:each) do
stub_env_var('G5_AUTH_ENDPOINT', 'https://test.auth.host')
end
end
|
Remove paperclip require; gem does that | require "paperclip"
require "paperclip-meta/version"
require 'paperclip-meta/railtie'
require 'paperclip-meta/attachment' | require 'paperclip-meta/version'
require 'paperclip-meta/railtie'
require 'paperclip-meta/attachment'
|
Complete solution and spec files for count between | # Count Between
# I worked on this challenge by myself.
# count_between is a method with three arguments:
# 1. An array of integers
# 2. An integer lower bound
# 3. An integer upper bound
#
# It returns the number of integers in the array between the lower and upper bounds,
# including (potentially) those bounds.
#
# If +array+ is empty the method should return 0
# Your Solution Below
def count_between(list_of_integers, lower_bound, upper_bound)
if
for num in count_between[1..2]
return count_between[0].count
end
end | # Count Between
# I worked on this challenge by myself.
# count_between is a method with three arguments:
# 1. An array of integers
# 2. An integer lower bound
# 3. An integer upper bound
#
# It returns the number of integers in the array between the lower and upper bounds,
# including (potentially) those bounds.
#
# If +array+ is empty the method should return 0
# Your Solution Below
def count_between(list_of_integers, lower_bound, upper_bound)
if lower_bound > upper_bound
return 0
else
list_of_integers.count { |num| (lower_bound..upper_bound).include?(num)}
end
end |
Fix headers not being strings in session API | module GrapeTokenAuth
module SessionsAPICore
def self.included(base)
base.helpers do
def find_resource(env, mapping)
token_authorizer = TokenAuthorizer.new(AuthorizerData.from_env(env))
token_authorizer.find_resource(mapping)
end
end
base.post '/sign_in' do
start_time = Time.now
resource = ResourceFinder.find(base.resource_scope, params)
if resource && resource.valid_password?(params[:password])
data = AuthorizerData.from_env(env)
env['rack.session'] ||= {}
data.store_resource(resource, base.resource_scope)
auth_header = AuthenticationHeader.new(data, start_time)
auth_header.headers.each do |key, value|
header key, value
end
status 200
present data: resource
else
error!({ errors: 'Invalid login credentials. Please try again.',
status: 'error' }, 401)
end
end
base.delete '/sign_out' do
resource = find_resource(env, base.resource_scope)
if resource
resource.tokens.delete(env[Configuration::CLIENT_KEY])
resource.save
status 200
else
status 404
end
end
end
end
class SessionsAPI < Grape::API
class << self
def resource_scope
:user
end
end
include SessionsAPICore
end
end
| module GrapeTokenAuth
module SessionsAPICore
def self.included(base)
base.helpers do
def find_resource(env, mapping)
token_authorizer = TokenAuthorizer.new(AuthorizerData.from_env(env))
token_authorizer.find_resource(mapping)
end
end
base.post '/sign_in' do
start_time = Time.now
resource = ResourceFinder.find(base.resource_scope, params)
if resource && resource.valid_password?(params[:password])
data = AuthorizerData.from_env(env)
env['rack.session'] ||= {}
data.store_resource(resource, base.resource_scope)
auth_header = AuthenticationHeader.new(data, start_time)
auth_header.headers.each do |key, value|
header key.to_s, value.to_s
end
status 200
present data: resource
else
error!({ errors: 'Invalid login credentials. Please try again.',
status: 'error' }, 401)
end
end
base.delete '/sign_out' do
resource = find_resource(env, base.resource_scope)
if resource
resource.tokens.delete(env[Configuration::CLIENT_KEY])
resource.save
status 200
else
status 404
end
end
end
end
class SessionsAPI < Grape::API
class << self
def resource_scope
:user
end
end
include SessionsAPICore
end
end
|
Change the name on this gem | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'layervault/version'
Gem::Specification.new do |spec|
spec.name = "layervault_ruby_client"
spec.version = LayerVault::VERSION
spec.authors = ["John McDowall"]
spec.email = ["john@mcdowall.info"]
spec.description = %q{The LayerVault Ruby API client.}
spec.summary = %q{Provides Ruby native wrappers for the LayerVault API.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "faraday"
spec.add_dependency "hashie"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
spec.add_development_dependency "multi_json"
spec.add_development_dependency "vcr"
spec.add_development_dependency "webmock", "1.13"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'layervault/version'
Gem::Specification.new do |spec|
spec.name = "layervault"
spec.version = LayerVault::VERSION
spec.authors = ["John McDowall", "Ryan LeFevre", "Kelly Sutton"]
spec.email = ["john@mcdowall.info", "ryan@layervault.com", "kelly@layervault.com"]
spec.description = %q{The LayerVault Ruby API client.}
spec.summary = %q{Provides Ruby native wrappers for the LayerVault API.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "faraday"
spec.add_dependency "hashie"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
spec.add_development_dependency "multi_json"
spec.add_development_dependency "vcr"
spec.add_development_dependency "webmock", "1.13"
end
|
Handle a situation where a server is removed at an inappropriate time, and would cause a nil object dereference otherwise. | class DashboardController < ApplicationController
def index
@backup_servers = BackupServer.accessible_by(current_ability).find(:all, :order => 'hostname')
@running = BackupJob.running(:include => [:servers]).select{|j| can? :read, j}
@failed = BackupJob.latest_problems(:include => [:servers]).select do | job |
joblist=job.server.backup_jobs.sort!{|j1,j2|j1.id <=> j2.id}
( (joblist.last == job && job.status != 'queued') ||
(job.status == 'queued' && joblist.last(2)[0] == job)
) && can?( :read, job)
end
@queued = BackupJob.queued(:include => [:servers]).select{|j| can? :read, j}
end
end
| class DashboardController < ApplicationController
def index
@backup_servers = BackupServer.accessible_by(current_ability).find(:all, :order => 'hostname')
@running = BackupJob.running(:include => [:servers]).select{|j| can? :read, j}
@failed = BackupJob.latest_problems(:include => [:servers]).select do | job |
server=job.server
if server
joblist=job.server.backup_jobs.sort!{|j1,j2|j1.id <=> j2.id}
( (joblist.last == job && job.status != 'queued') ||
(job.status == 'queued' && joblist.last(2)[0] == job)
) && can?( :read, job)
end
end
@queued = BackupJob.queued(:include => [:servers]).select{|j| can? :read, j}
end
end
|
Move tableish requirement to test that requires it. | $LOAD_PATH.unshift(File.dirname(__FILE__) + '/../../lib')
require 'mechanical-cuke'
require 'cucumber/web/tableish'
require 'test/unit/assertions'
require 'open4'
World(Test::Unit::Assertions)
Before do
@server ||= {}
server_app = File.dirname(__FILE__) + '/../../test/fixtures/server/server.rb'
@server[:pid], @server[:stdin], @server[:stdout], @server[:stderr] =
Open4::popen4 server_app
status = @server[:stdout].readline
raise "Server startup failed" if status !~ /Sinatra.* has taken the stage on/
end
After do
if @server[:pid]
Process.kill('HUP', @server[:pid])
end
end
| $LOAD_PATH.unshift(File.dirname(__FILE__) + '/../../lib')
require 'mechanical-cuke'
require 'test/unit/assertions'
require 'open4'
World(Test::Unit::Assertions)
Before do
@server ||= {}
server_app = File.dirname(__FILE__) + '/../../test/fixtures/server/server.rb'
@server[:pid], @server[:stdin], @server[:stdout], @server[:stderr] =
Open4::popen4 server_app
status = @server[:stdout].readline
raise "Server startup failed" if status !~ /Sinatra.* has taken the stage on/
end
After do
if @server[:pid]
Process.kill('HUP', @server[:pid])
end
end
|
Configure the mock Animal Service |
require 'pact/consumer/rspec'
# or require 'pact/consumer/minitest' if you are using Minitest
Pact.service_consumer "Zoo App" do
has_pact_with "Animal Service" do
mock_service :animal_service do
port 1234
end
end
end
| |
Add recipe to check zookeeper status | # coding: UTF-8
# Cookbook Name:: cerner_kafka
# Recipe:: zookeeper_status
execute 'check zookeeper' do
action :run
command " nc -z #{node["kafka"]["zookeepers"].first} 2181 "
returns [0]
end
| |
Allow multiple tags for with_tagged_logger | # Modifies logger of logged for duration of the blocks.
module Metasploit::Cache::Logged
# Changes `#logger` on `logged` for the duration of the block to `logger`.
#
# @param logged [#logger, #logger=]
# @param logger [Logger]
# @yield [logger]
# @yieldparam logger [Logger] `logger`
# @yieldreturn [void]
# @return [void]
def self.with_logger(logged, logger)
original_logger = logged.logger
begin
logged.logger = logger
yield logger
ensure
logged.logger = original_logger
end
end
# Tags {#logger} with the given tag and then runs block {with_logger}.
#
# @param logged [#logger, #logger=]
# @param logger [ActiveSupport::TaggedLogger, #tagged]
# @yield [logger]
# @yieldparam logger [ActiveSupport::TaggedLogger] `logger` with `tag` applied
# @yieldreturn [void]
# @return [void]
def self.with_tagged_logger(logged, logger, tag, &block)
logger.tagged(tag) do
with_logger(logged, logger, &block)
end
end
end | # Modifies logger of logged for duration of the blocks.
module Metasploit::Cache::Logged
# Changes `#logger` on `logged` for the duration of the block to `logger`.
#
# @param logged [#logger, #logger=]
# @param logger [Logger]
# @yield [logger]
# @yieldparam logger [Logger] `logger`
# @yieldreturn [void]
# @return [void]
def self.with_logger(logged, logger)
original_logger = logged.logger
begin
logged.logger = logger
yield logger
ensure
logged.logger = original_logger
end
end
# Tags {#logger} with the given tag and then runs block {with_logger}.
#
# @param logged [#logger, #logger=]
# @param logger [ActiveSupport::TaggedLogger, #tagged]
# @param tags [Array<String>] tags to tag logger with
# @yield [logger]
# @yieldparam logger [ActiveSupport::TaggedLogger] `logger` with `tag` applied
# @yieldreturn [void]
# @return [void]
def self.with_tagged_logger(logged, logger, *tags, &block)
logger.tagged(tags) do
with_logger(logged, logger, &block)
end
end
end |
Stop to generate an empty validations | module PrettyValidation
class Renderer
attr_reader :table_name
def self.validations_path
Rails.root.join('app', 'validations')
end
def self.generate
FileUtils.mkdir_p validations_path unless File.directory? validations_path
Schema.table_names.each { |t| new(t).write! }
end
def initialize(table_name)
@table_name = table_name
end
def render
# Delete the last new line
<<-EOF[0..-2]
module #{module_name}
extend ActiveSupport::Concern
included do
#{validations.join("\n ")}
end
end
EOF
end
def module_name
"#{table_name.classify}Validation"
end
def file_name
"#{module_name.underscore}.rb"
end
def file_path
Renderer.validations_path.join(file_name)
end
def write!
File.write(file_path, render)
end
private
def validations
sexy_validations + uniq_validations
end
def sexy_validations
Validation.sexy_validations(table_name)
end
def uniq_validations
Validation.unique_validations(table_name)
end
end
end
| module PrettyValidation
class Renderer
attr_reader :table_name
def self.validations_path
Rails.root.join('app', 'validations')
end
def self.generate
FileUtils.mkdir_p validations_path unless File.directory? validations_path
Schema.table_names.each do |t|
r = new t
r.write! unless r.validations.empty?
end
end
def initialize(table_name)
@table_name = table_name
end
def render
# Delete the last new line
<<-EOF[0..-2]
module #{module_name}
extend ActiveSupport::Concern
included do
#{validations.join("\n ")}
end
end
EOF
end
def module_name
"#{table_name.classify}Validation"
end
def file_name
"#{module_name.underscore}.rb"
end
def file_path
Renderer.validations_path.join(file_name)
end
def write!
File.write(file_path, render)
end
def validations
sexy_validations + uniq_validations
end
private
def sexy_validations
Validation.sexy_validations(table_name)
end
def uniq_validations
Validation.unique_validations(table_name)
end
end
end
|
Print sensible error message for APIError.to_s | module MediaWiki
# General exception occurred within MediaWiki::Gateway, and parent class for MediaWiki::APIError, MediaWiki::Unauthorized.
class Exception < Exception
end
# Wrapper for errors returned by MediaWiki API. Possible codes are defined in http://www.mediawiki.org/wiki/API:Errors_and_warnings.
#
# Warnings also throw errors with code 'warning', unless MediaWiki::Gateway#new was called with :ignorewarnings.
class APIError < MediaWiki::Exception
attr_reader :code, :info, :message
def initialize(code, info)
@code = code
@info = info
@message = "API error: code '#{code}', info '#{info}'"
end
end
# User is not authorized to perform this operation. Also thrown if MediaWiki::Gateway#login fails.
class Unauthorized < MediaWiki::Exception
end
end
| module MediaWiki
# General exception occurred within MediaWiki::Gateway, and parent class for MediaWiki::APIError, MediaWiki::Unauthorized.
class Exception < Exception
end
# Wrapper for errors returned by MediaWiki API. Possible codes are defined in http://www.mediawiki.org/wiki/API:Errors_and_warnings.
#
# Warnings also throw errors with code 'warning', unless MediaWiki::Gateway#new was called with :ignorewarnings.
class APIError < MediaWiki::Exception
attr_reader :code, :info, :message
def initialize(code, info)
@code = code
@info = info
@message = "API error: code '#{code}', info '#{info}'"
end
def to_s
"#{self.class.to_s}: #{@message}"
end
end
# User is not authorized to perform this operation. Also thrown if MediaWiki::Gateway#login fails.
class Unauthorized < MediaWiki::Exception
end
end
|
Add output buffer to erb runner | require 'template/helper/base'
require 'template/helper/info'
class Template::Runner::Base
include Template::Helper::Base
include Template::Helper::Info
attr_accessor :build, :filename
def initialize(_filename, _build)
self.filename = _filename
self.build = _build
@output_filename = filename.gsub(/(\.erb)$/, '')
@content = File.read(filename)
end
# TODO: Use Forwardable
def root; build.root; end
def build_path
build.__path__
end
def __path__
File.dirname filename
end
def document
build.document_struct
end
def o
@locals
end
def __render__(locals = {})
@locals = OpenStruct.new(locals)
ERB.new(@content).result(binding)
end
def __run__(locals = {})
verbose { "[T] #{filename.gsub(build_path, '')}".dark }
old_current_template = build.current_template
build.current_template = self
@output = after_render __render__(locals)
build.current_template = old_current_template
@output
end
def after_write; end
def after_render(str); str; end
def write
__run__
File.open(@output_filename, 'w') {|f| f.write(@output) }
after_write
end
end | require 'template/helper/base'
require 'template/helper/info'
class Template::Runner::Base
include Template::Helper::Base
include Template::Helper::Info
attr_accessor :build, :filename
def initialize(_filename, _build)
self.filename = _filename
self.build = _build
@output_filename = filename.gsub(/(\.erb)$/, '')
@content = File.read(filename)
end
# TODO: Use Forwardable
def root; build.root; end
def build_path
build.__path__
end
def __path__
File.dirname filename
end
def document
build.document_struct
end
def o
@locals
end
def append_to_output(str)
@erbout << str
end
def __render__(locals = {})
@locals = OpenStruct.new(locals)
ERB.new(@content, nil, nil, "@erbout").result(binding)
end
def __run__(locals = {})
verbose { "[T] #{filename.gsub(build_path, '')}".dark }
old_current_template = build.current_template
build.current_template = self
@output = after_render __render__(locals)
build.current_template = old_current_template
@output
end
def after_write; end
def after_render(str); str; end
def write
__run__
File.open(@output_filename, 'w') {|f| f.write(@output) }
after_write
end
end |
Remove unnecessary let in spec | # frozen_string_literal: true
require 'rails_helper'
describe Gitlab::DatabaseImporters::CommonMetrics::PrometheusMetric do
let(:existing_group_titles) do
::PrometheusMetricEnums.group_details.each_with_object({}) do |(key, value), memo|
memo[key] = value[:group_title]
end
end
it 'group enum equals ::PrometheusMetric' do
expect(described_class.groups).to eq(::PrometheusMetric.groups)
end
it '.group_titles equals ::PrometheusMetric' do
expect(Gitlab::DatabaseImporters::CommonMetrics::PrometheusMetricEnums.group_titles).to eq(existing_group_titles)
end
end
| # frozen_string_literal: true
require 'rails_helper'
describe Gitlab::DatabaseImporters::CommonMetrics::PrometheusMetric do
it 'group enum equals ::PrometheusMetric' do
expect(described_class.groups).to eq(::PrometheusMetric.groups)
end
it '.group_titles equals ::PrometheusMetric' do
existing_group_titles = ::PrometheusMetricEnums.group_details.each_with_object({}) do |(key, value), memo|
memo[key] = value[:group_title]
end
expect(Gitlab::DatabaseImporters::CommonMetrics::PrometheusMetricEnums.group_titles).to eq(existing_group_titles)
end
end
|
Add spec test for request. | require "spec_helper"
require 'wordpress/request'
describe Wordpress::Request do
end
| require "spec_helper"
require 'wordpress/request'
describe Wordpress::Request do
let :request do
Wordpress::Request.new(:get, 'url')
end
it "should deep clone" do
new_request = request.dup
new_request.should_not equal request
new_request.params.should_not equal request.params
new_request.body.should_not equal request.body
end
end
|
Create rake task for fixing 17th December issue | namespace :data_fix do
desc 'Fix for the 17th December incident'
task december_17: :environment do
sql_condition = [
'DATE(created_at) = ? AND outcome IS NOT NULL AND reference IS NULL',
'2015-12-17'
]
count = Application.where(*sql_condition).count
puts "Affected applications: #{count}"
Application.where(*sql_condition).each do |application|
puts "- fixing #{application.id}"
application.completed_at = Time.zone.parse('2015-12-17 20:00:00')
application.completed_by_id = application.user_id
generator_output = ReferenceGenerator.new(application).attributes
application.reference = generator_output[:reference]
application.business_entity = generator_output[:business_entity]
if application.part_payment.present?
application.state = :waiting_for_part_payment
elsif application.evidence_check.present?
application.state = :waiting_for_evidence
else
application.state = :processed
end
application.save!
end
end
end
| |
Remove is_active setter with '?' | class IrsGroup
include Mongoid::Document
include Mongoid::Timestamps
embedded_in :application_group
# Unique identifier for this Household used for reporting enrollment and premium tax credits to IRS
auto_increment :hbx_id, seed: 9999
embeds_many :comments
accepts_nested_attributes_for :comments, reject_if: proc { |attribs| attribs['content'].blank? }, allow_destroy: true
def parent
raise "undefined parent ApplicationGroup" unless application_group?
self.application_group
end
# embedded association: has_many :tax_households
def tax_households
parent.tax_households.where(:irs_group_id => self.id)
end
# embedded association: has_many :hbx_enrollments
def hbx_enrollments
parent.hbx_enrollments.where(:irs_group_id => self.id)
end
# embedded association: has_many :hbx_enrollment_exemptions
def hbx_enrollment_exemptions
parent.hbx_enrollment_exemptions.where(:irs_group_id => self.id)
end
def is_active?=(status)
self.is_active = status
end
def is_active?
self.is_active
end
end | class IrsGroup
include Mongoid::Document
include Mongoid::Timestamps
embedded_in :application_group
# Unique identifier for this Household used for reporting enrollment and premium tax credits to IRS
auto_increment :hbx_id, seed: 9999
embeds_many :comments
accepts_nested_attributes_for :comments, reject_if: proc { |attribs| attribs['content'].blank? }, allow_destroy: true
def parent
raise "undefined parent ApplicationGroup" unless application_group?
self.application_group
end
# embedded association: has_many :tax_households
def tax_households
parent.tax_households.where(:irs_group_id => self.id)
end
# embedded association: has_many :hbx_enrollments
def hbx_enrollments
parent.hbx_enrollments.where(:irs_group_id => self.id)
end
# embedded association: has_many :hbx_enrollment_exemptions
def hbx_enrollment_exemptions
parent.hbx_enrollment_exemptions.where(:irs_group_id => self.id)
end
def is_active?
self.is_active
end
end |
Update reload to support new files | # encoding: utf-8
require 'rubygems'
Gem::Specification.class_eval { def self.warn( args ); end }
require 'pry'
module Appium; end unless defined? Appium
def define_reload paths
Pry.send(:define_singleton_method, :reload) do
paths.each do |p|
# If a page obj is deleted then load will error.
begin
load p
rescue # LoadError: cannot load such file
end
end
end
nil
end
module Appium::Console
require 'appium_lib'
AwesomePrint.pry!
to_require = load_appium_txt file: Dir.pwd + '/appium.txt', verbose: true
start = File.expand_path '../start.rb', __FILE__
cmd = ['-r', start]
if to_require && !to_require.empty?
define_reload to_require
load_files = to_require.map { |f| %(require "#{f}";) }.join "\n"
cmd += [ '-e', load_files ]
end
$stdout.puts "pry #{cmd.join(' ')}"
Pry::CLI.parse_options cmd
end # module Appium::Console | # encoding: utf-8
require 'rubygems'
Gem::Specification.class_eval { def self.warn( args ); end }
require 'pry'
module Appium; end unless defined? Appium
def define_reload
Pry.send(:define_singleton_method, :reload) do
files = load_appium_txt file: Dir.pwd + '/appium.txt'
files.each do |file|
# If a page obj is deleted then load will error.
begin
load file
rescue # LoadError: cannot load such file
end
end
end
nil
end
module Appium::Console
require 'appium_lib'
AwesomePrint.pry!
to_require = load_appium_txt file: Dir.pwd + '/appium.txt', verbose: true
start = File.expand_path '../start.rb', __FILE__
cmd = ['-r', start]
if to_require && !to_require.empty?
define_reload
load_files = to_require.map { |f| %(require "#{f}";) }.join "\n"
cmd += [ '-e', load_files ]
end
$stdout.puts "pry #{cmd.join(' ')}"
Pry::CLI.parse_options cmd
end # module Appium::Console |
Fix bug where iteration over files wasn't recursive. | module Frakup
class Backupset
include DataMapper::Resource
property :id,
Serial
property :created_at,
DateTime
property :updated_at,
DateTime
has n, :backupelements
has n, :fileobjects, :through => :backupelements
def self.backup(source, target)
time_start = Time.now
$log.info "Backup started"
$log.info " - source: #{source}"
$log.info " - target: #{target}"
backupset = Backupset.create
$log.info " Created Backupset ##{backupset.id}"
Pathname.glob(File.join(source, "*")).each do |f|
Backupelement.store(backupset, f)
end
time_stop = Time.now
$log.info " Backup finished"
$log.info " - duration: #{Time.at(time_stop - time_start).gmtime.strftime('%R:%S')}"
$log.info " - backupelements: #{backupset.backupelements.count}"
$log.info " - fileobjects: #{backupset.fileobjects.count}"
$log.info " - size: #{Frakup::Helper.human_size(backupset.fileobjects.sum(:size))}"
end
end
end
| module Frakup
class Backupset
include DataMapper::Resource
property :id,
Serial
property :created_at,
DateTime
property :updated_at,
DateTime
has n, :backupelements
has n, :fileobjects, :through => :backupelements
def self.backup(source, target)
time_start = Time.now
$log.info "Backup started"
$log.info " - source: #{source}"
$log.info " - target: #{target}"
backupset = Backupset.create
$log.info " Created Backupset ##{backupset.id}"
Pathname.glob(File.join(source, "**", "*")).each do |f|
Backupelement.store(backupset, f)
end
time_stop = Time.now
$log.info " Backup finished"
$log.info " - duration: #{Time.at(time_stop - time_start).gmtime.strftime('%R:%S')}"
$log.info " - backupelements: #{backupset.backupelements.count}"
$log.info " - fileobjects: #{backupset.fileobjects.count}"
$log.info " - size: #{Frakup::Helper.human_size(backupset.fileobjects.sum(:size))}"
end
end
end
|
Add build_user option to case worker factory | # == Schema Information
#
# Table name: case_workers
#
# id :integer not null, primary key
# created_at :datetime
# updated_at :datetime
# location_id :integer
# roles :string
# deleted_at :datetime
# uuid :uuid
#
FactoryBot.define do
factory :case_worker do
after(:build) do |case_worker|
case_worker.user ||= build(:user, first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, password: 'password', password_confirmation: 'password')
case_worker.user.email = "#{case_worker.first_name}.#{case_worker.last_name}@laa.gov.uk"
end
location
roles { ['case_worker'] }
trait :case_worker do
roles { ['case_worker'] }
end
trait :admin do
roles { ['admin'] }
end
trait :provider_manager do
roles { ['provider_management'] }
end
trait :softly_deleted do
deleted_at { 10.minutes.ago }
end
end
end
| # == Schema Information
#
# Table name: case_workers
#
# id :integer not null, primary key
# created_at :datetime
# updated_at :datetime
# location_id :integer
# roles :string
# deleted_at :datetime
# uuid :uuid
#
FactoryBot.define do
factory :case_worker do
transient do
build_user { true }
end
after(:build) do |case_worker, evaluator|
if evaluator.build_user
case_worker.user ||= build(:user, first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, password: 'password', password_confirmation: 'password')
case_worker.user.email = "#{case_worker.first_name}.#{case_worker.last_name}@laa.gov.uk"
end
end
location
roles { ['case_worker'] }
trait :case_worker do
roles { ['case_worker'] }
end
trait :admin do
roles { ['admin'] }
end
trait :provider_manager do
roles { ['provider_management'] }
end
trait :softly_deleted do
deleted_at { 10.minutes.ago }
end
end
end
|
Add spec for i18n monkey patch | require 'i18n'
RSpec.describe I18n::Backend::Base do
# Since #load_erb is a protected method, this spec tests the
# interface that calls it: #load_translations
describe '#load_translations' do
let(:translations) do
I18n.backend.instance_variable_get(:@translations)
end
before do
I18n.backend = I18n::Backend::Simple.new
end
context 'when loading data from a yml.erb file' do
let(:filename) { 'en.yml.erb' }
let(:yaml) do
<<-YAML
en:
foo: 1 + 1 = <%= 1 + 1 %>
YAML
end
let(:erb_interpolated_hash) do
{ en: { foo: '1 + 1 = 2' } }
end
before do
allow(File).to receive(:read).with(filename).and_return(yaml)
I18n.backend.load_translations(filename)
end
it 'loads data from a yml.erb file and interpolates the ERB' do
expect(translations).to eq(erb_interpolated_hash)
end
end
end
end
| |
Add solution for challenge 4.6 | # Concatenate Two Arrays
# I worked on this challenge [by myself ].
# Your Solution Below
def array_concat(array_1, array_2)
array_2.each {|x| array_1<<x}
array_1.flatten
end
def array_concat(array_1, array_2)
a = array_1+array_2
a.flatten
#array_1.concat array_2
end
| # Concatenate Two Arrays
# I worked on this challenge [by myself ].
# Your Solution Below
# def array_concat(array_1, array_2)
# array_2.each {|x| array_1<<x}
# array_1.flatten
# end
# def array_concat(array_1, array_2)
# a = array_1+array_2
# a.flatten
# end
# def array_concat(array_1, array_2)
# array_1.concat array_2
# end
|
Add module to be used when we want to normalise empty values before save | module NormaliseBlankValues extend ActiveSupport::Concern
def self.included(base)
base.extend ClassMethods
end
def normalise_blank_values
attributes.each do |column, value|
self[column].present? || self[column] = nil
end
end
module ClassMethods
def normalise_blank_values
before_save :normalise_blank_values
end
end
end
ActiveRecord::Base.send(:include, NormaliseBlankValues)
| |
Add acceptance test for ovs_stats | require 'spec_helper_acceptance'
describe 'collectd::plugin::ovs_stats class', unless: default[:platform] =~ %r{ubuntu} do
context 'basic parameters' do
# Using puppet_apply as a helper
it 'works idempotently with no errors' do
pp = <<-EOS
class{'collectd':
utils => true,
}
class{ 'collectd::plugin::ovs_stats':
port => 6639,
}
# Add one write plugin to keep logs quiet
class{'collectd::plugin::csv':}
# Create a socket to query
class{'collectd::plugin::unixsock':
socketfile => '/var/run/collectd-sock',
socketgroup => 'root',
}
EOS
# Run 3 times since the collectd_version
# fact is impossible until collectd is
# installed.
apply_manifest(pp, catch_failures: false)
apply_manifest(pp, catch_failures: true)
apply_manifest(pp, catch_changes: true)
# Wait to get some data
shell('sleep 10')
end
describe service('collectd') do
it { is_expected.to be_running }
end
# it is expected to unload the ovs_stats plugin, since there
# is no ovs running inside the docker container.
# At the same time, collectd should continue to run.
describe command('collectdctl -s /var/run/collectd-sock listval') do
its(:exit_status) { is_expected.to eq 0 }
end
end
end
| |
Fix comment headers for Google Analytics embed | module Sevenhelpers
module ViewHelpers
def copyright_years(start_year = Time.now.year)
current_year = Time.now.year
if start_year > current_year # trap if user sets start year ahead of current year
output = current_year.to_s
else
output = start_year.to_s
output << "-#{current_year.to_s}" if start_year != current_year
end
output
end
def google_analytics_code(tracking_id, options = {})
options.reverse_merge! show_placeholder: true, environments: %w(production)
if options[:environments].include? Rails.env
output = <<-EOD
<-- Google Analytics -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '#{tracking_id}']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<-- end Google Analytics -->
EOD
elsif options[:show_placeholder]
output = "<!-- actual Google Analytics code will render here in #{ options[:environments].map(&:capitalize).to_sentence } -->"
else
output = ''
end
raw(output)
end
end
end | module Sevenhelpers
module ViewHelpers
def copyright_years(start_year = Time.now.year)
current_year = Time.now.year
if start_year > current_year # trap if user sets start year ahead of current year
output = current_year.to_s
else
output = start_year.to_s
output << "-#{current_year.to_s}" if start_year != current_year
end
output
end
def google_analytics_code(tracking_id, options = {})
options.reverse_merge! show_placeholder: true, environments: %w(production)
if options[:environments].include? Rails.env
output = <<-EOD
<!-- Google Analytics -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '#{tracking_id}']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<!-- end Google Analytics -->
EOD
elsif options[:show_placeholder]
output = "<!-- actual Google Analytics code will render here in #{ options[:environments].map(&:capitalize).to_sentence } -->"
else
output = ''
end
raw(output)
end
end
end |
Add test for conversation detail | require 'screenshot_helper'
describe "factlink", type: :feature do
include Acceptance::ConversationHelper
include Acceptance::FactHelper
before :each do
@user = sign_in_user(create :full_user, :confirmed)
@recipients = create_list :full_user, 2
end
it "the layout of the conversations overview page is correct" do
factlink = backend_create_fact
message_content = 'content'
send_message(message_content, factlink, @recipients)
visit "/m"
assume_unchanged_screenshot "conversations_overview"
end
end
| require 'screenshot_helper'
describe "factlink", type: :feature do
include Acceptance::ConversationHelper
include Acceptance::FactHelper
before :each do
@user = sign_in_user(create :full_user, :confirmed)
@recipients = create_list :full_user, 2
end
it "the layout of the conversations overview page is correct" do
factlink = backend_create_fact
message_content = 'content'
send_message(message_content, factlink, @recipients)
visit "/m"
assume_unchanged_screenshot "conversations_overview"
end
it "the layout of the conversations detail page is correct" do
factlink = backend_create_fact
message_content = 'content'
send_message(message_content, factlink, @recipients)
recipient_ids = Message.last.conversation.recipients.map(&:id)
@recipients.each do |recipient|
expect(recipient_ids).to include recipient.id
switch_to_user @user
open_message_with_content message_content
end
assume_unchanged_screenshot "conversations_detail"
end
end
|
Update to validate on unique marvel_id. Create loop to populate database | class Heroe < ApplicationRecord
validates :name, uniqueness: true
def self.save_hero_data
# offset = 0
response_count = nil
# until response_count == 0
# character_data = marvel_api_call
# if character_data['data']['results'].empty?
# end
# end
end
private
def self.marvel_api_call
url = "https://gateway.marvel.com:443/v1/public/characters?limit=100&offset=#{offset}&ts=#{timestamp}&apikey=#{ENV['MARVEL_PUBLIC']}&hash=#{marvel_hash}"
debugger
uri = URI(url)
response = Net::HTTP.get(uri)
response = JSON.parse(response)
end
def self.offset
Heroe.count
end
def self.marvel_hash
hash = Digest::MD5.hexdigest( timestamp + ENV['MARVEL_PRIVATE'] + ENV['MARVEL_PUBLIC'] )
end
def self.timestamp
Time.now.to_i.to_s
end
end
| class Heroe < ApplicationRecord
validates :marvel_id, uniqueness: true
def self.save_hero_data
response_count = nil
until response_count == 0
character_data = marvel_api_call['data']
if !character_data['results'].empty?
character_data['results'].each do |hero|
character = Heroe.new( :name => hero['name'], :comics => hero['comics']['available'] )
character.save
end
response_count = character_data['count']
else
break
end
end
end
private
def self.marvel_api_call
url = "https://gateway.marvel.com:443/v1/public/characters?orderBy=modified&limit=100&offset=#{Heroe.count}&ts=#{timestamp}&apikey=#{ENV['MARVEL_PUBLIC']}&hash=#{marvel_hash}"
uri = URI(url)
response = Net::HTTP.get(uri)
response = JSON.parse(response)
end
def self.marvel_hash
hash = Digest::MD5.hexdigest( timestamp + ENV['MARVEL_PRIVATE'] + ENV['MARVEL_PUBLIC'] )
end
def self.timestamp
Time.now.to_i.to_s
end
end
|
Add endpoints relating to deletion to org controller | class OrganizationsController < ApplicationController
require_permission :can_create_organization?, only: [:new, :create]
require_permission one_of: [:can_create_organization?, :can_update_organization?], except: [:new, :create]
active_tab "organizations"
def index
@organizations = current_user.organizations_with_permission_enabled(:can_update_organization_at?,
includes: :addresses)
end
def new
@organization = Organization.new
end
def edit
@redirect_to = Redirect.to(organizations_path, params, allow: [:order, :users, :user])
@organization = Organization.find params[:id]
raise PermissionError unless current_user.can_update_organization_at?(@organization)
end
def update
current_user.update_organization params
redirect_to organizations_path
end
def create
current_user.create_organization params
redirect_to organizations_path
rescue ActiveRecord::RecordInvalid => e
@organization = e.record
render :new
end
end
| class OrganizationsController < ApplicationController
require_permission :can_create_organization?, only: [:new, :create]
require_permission :can_delete_and_restore_organizations?, only: [:delete, :deleted, :restore]
require_permission one_of: [:can_create_organization?, :can_update_organization?], except: [:new, :create]
active_tab "organizations"
def index
@organizations = current_user.organizations_with_permission_enabled(:can_update_organization_at?,
includes: :addresses)
end
def new
@organization = Organization.new
end
def edit
@redirect_to = Redirect.to(organizations_path, params, allow: [:order, :users, :user])
@organization = Organization.find params[:id]
raise PermissionError unless current_user.can_update_organization_at?(@organization)
end
def update
current_user.update_organization params
redirect_to organizations_path
end
def create
current_user.create_organization params
redirect_to organizations_path
rescue ActiveRecord::RecordInvalid => e
@organization = e.record
render :new
end
def destroy
@organization = Organization.find params[:id]
if @organization.soft_delete
flash[:success] = "Organization '#{@organization.name}' deleted!"
else
flash[:error] = <<-eos
'#{@organization.name}' was unable to be deleted. We found the following open orders:
#{@organization.open_orders.map(&:id).to_sentence}
eos
end
redirect_to organizations_path
end
def deleted
@organizations = Organization.deleted
end
def restore
@organization = Organization.find_deleted params[:id]
@organization.restore
redirect_to organizations_path(@organization)
end
end
|
Set Lita plugin type in gemspec. | Gem::Specification.new do |spec|
spec.name = "lita-coin"
spec.version = "0.0.1"
spec.authors = ["Jimmy Cuadra"]
spec.email = ["jimmy@jimmycuadra.com"]
spec.description = %q{A Lita handler for flipping a coin.}
spec.summary = %q{A Lita handler for flipping a coin.}
spec.homepage = "https://github.com/jimmycuadra/lita-coin"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "lita", "~> 2.3"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec", ">= 2.14"
spec.add_development_dependency "simplecov"
spec.add_development_dependency "coveralls"
end
| Gem::Specification.new do |spec|
spec.name = "lita-coin"
spec.version = "0.0.1"
spec.authors = ["Jimmy Cuadra"]
spec.email = ["jimmy@jimmycuadra.com"]
spec.description = %q{A Lita handler for flipping a coin.}
spec.summary = %q{A Lita handler for flipping a coin.}
spec.homepage = "https://github.com/jimmycuadra/lita-coin"
spec.license = "MIT"
spec.metadata = { "lita_plugin_type" => "handler" }
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "lita", "~> 2.3"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec", ">= 2.14"
spec.add_development_dependency "simplecov"
spec.add_development_dependency "coveralls"
end
|
Add bg job for posting to bridgy | # frozen_string_literal: true
# Async job to posting webmentions to Bridgy.
# The retry interval uses the agorithm as Sidekiq but we start from 1 with an initial sleep
# as you'll never get an instant publishing.
# Assuming `rand()`` always returns 30, the longest we'll be running for is just over 27 mins
class BridgyJob
include SuckerPunch::Job
def perform(location, destination, options = { bridgy_omit_link: false, bridgy_ignore_formatting: false })
logger.info "Syndicating #{location} to #{destination}"
count = 1
post_ready = false
while count < 6
slp = ENV['RACK_ENV'] == 'test' ? 0 : (count**4) + 15 + (rand(30) * (count + 1))
logger.info "Sleeping for #{slp}s ..."
sleep slp
post_ready = HTTParty.head(location, follow_redirects: true, maintain_method_across_redirects: true).success?
break if post_ready
count += 1
end
return logger.info "#{location} never appeared. No syndication attempted." unless post_ready
resp = HTTParty.post('https://brid.gy/publish/webmention',
body: { source: location, target: "https://brid.gy/publish/#{destination}" },
query: options)
logger.info resp.created? ? "Successfully syndicated #{location} to #{destination}" : "Bridgy not happy: #{resp.code}"
end
end
| |
Support Rails 3.2 or later | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "view_source_map/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "view_source_map"
s.version = ViewSourceMap::VERSION
s.authors = ["Ryo Nakamura"]
s.email = ["r7kamura@gmail.com"]
s.homepage = "https://github.com/r7kamura/view_source_map"
s.summary = "Rails plugin to view source map"
s.description = "This is a Rails plugin to insert the path name of " +
"a rendered partial view as HTML comment in development environment"
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"]
s.add_dependency "rails", "~> 3.2.9"
s.add_development_dependency "sqlite3"
s.add_development_dependency "rspec-rails"
end
| $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "view_source_map/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "view_source_map"
s.version = ViewSourceMap::VERSION
s.authors = ["Ryo Nakamura"]
s.email = ["r7kamura@gmail.com"]
s.homepage = "https://github.com/r7kamura/view_source_map"
s.summary = "Rails plugin to view source map"
s.description = "This is a Rails plugin to insert the path name of " +
"a rendered partial view as HTML comment in development environment"
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"]
s.add_dependency "rails", ">= 3.2"
s.add_development_dependency "sqlite3"
s.add_development_dependency "rspec-rails"
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.