Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix FC019: Access node attributes in a consistent manner | #
# Cookbook Name:: sysctl
# Recipe:: service
#
# Copyright 2013-2014, OneHealth Solutions, 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.
#
template '/etc/rc.d/init.d/procps' do
source 'procps.init-rhel.erb'
mode '0755'
only_if { platform_family?('rhel', 'fedora', 'pld') }
end
service 'procps' do
supports :restart => true, :reload => true, :status => false
case node[:platform]
when 'ubuntu'
if node[:platform_version].to_f >= 9.10
provider Chef::Provider::Service::Upstart
end
end
action :enable
end
| #
# Cookbook Name:: sysctl
# Recipe:: service
#
# Copyright 2013-2014, OneHealth Solutions, 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.
#
template '/etc/rc.d/init.d/procps' do
source 'procps.init-rhel.erb'
mode '0755'
only_if { platform_family?('rhel', 'fedora', 'pld') }
end
service 'procps' do
supports :restart => true, :reload => true, :status => false
case node['platform']
when 'ubuntu'
if node['platform_version'].to_f >= 9.10
provider Chef::Provider::Service::Upstart
end
end
action :enable
end
|
Use Coveralls formatter alongside SimpleCov. | require 'tempfile'
require 'simplecov'
if SimpleCov.usable?
if defined?(TracePoint)
require_relative 'racc_coverage_helper'
RaccCoverage.start(%w(ruby18.y),
File.expand_path('../../lib/parser', __FILE__))
# Report results faster.
at_exit { RaccCoverage.stop }
end
require 'coveralls'
Coveralls.wear!
SimpleCov.start do
add_filter "/test/"
add_filter "/lib/parser/lexer.rb"
add_filter "/lib/parser/ruby18.rb"
add_filter "/lib/parser/ruby19.rb"
add_filter "/lib/parser/ruby20.rb"
end
end
# minitest/autorun must go after SimpleCov to preserve
# correct order of at_exit hooks.
require 'minitest/autorun'
$LOAD_PATH.unshift(File.expand_path('../../lib', __FILE__))
require 'parser'
| require 'tempfile'
require 'simplecov'
require 'coveralls'
if SimpleCov.usable?
if defined?(TracePoint)
require_relative 'racc_coverage_helper'
RaccCoverage.start(%w(ruby18.y),
File.expand_path('../../lib/parser', __FILE__))
# Report results faster.
at_exit { RaccCoverage.stop }
end
SimpleCov.start do
self.formatter = SimpleCov::Formatter::MultiFormatter[
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
add_filter "/test/"
add_filter "/lib/parser/lexer.rb"
add_filter "/lib/parser/ruby18.rb"
add_filter "/lib/parser/ruby19.rb"
add_filter "/lib/parser/ruby20.rb"
end
end
# minitest/autorun must go after SimpleCov to preserve
# correct order of at_exit hooks.
require 'minitest/autorun'
$LOAD_PATH.unshift(File.expand_path('../../lib', __FILE__))
require 'parser'
|
Add empty implementations of the abstract methods | #!/usr/bin/env ruby
templateCs = %{namespace Mos6510.Instructions
{
public class <class> : Instruction
{
}
}
}
templateTest = %{using NUnit.Framework;
namespace Mos6510.Tests.Instructions
{
[TestFixture]
public class <class>Tests
{
[Test]
public void TheTruth()
{
Assert.That(true, Is.True);
}
}
}
}
def replaceClass(klass, template)
template.gsub("<class>", klass)
end
if (ARGV.length != 1)
puts "Usage: newi.rb instruction\n"
exit
end
klass = ARGV[0]
codeDirectory = "Mos6510/Instructions"
testDirectory = "Mos6510.Tests/Instructions"
codeFile = "#{codeDirectory}/#{klass}.cs"
if (File.exists?(codeFile))
puts "Error: The file '#{codeFile}' already exists.\n"
exit
end
testFile = "#{testDirectory}/#{klass}Tests.cs"
if (File.exists?(testFile))
puts "Error: The file '#{testFile}' already exists.\n"
exit
end
File.open(codeFile, 'w') { |file|
file.write(replaceClass(klass, templateCs))
}
File.open(testFile, 'w') { |file|
file.write(replaceClass(klass, templateTest))
}
| #!/usr/bin/env ruby
templateCs = %{namespace Mos6510.Instructions
{
public class <class> : Instruction
{
public void Execute(ProgrammingModel model, Memory memory, byte argument)
{
throw new System.NotImplementedException();
}
public int CyclesFor(AddressingMode mode)
{
throw new System.NotImplementedException();
}
}
}
}
templateTest = %{using NUnit.Framework;
namespace Mos6510.Tests.Instructions
{
[TestFixture]
public class <class>Tests
{
[Test]
public void TheTruth()
{
Assert.That(true, Is.True);
}
}
}
}
def replaceClass(klass, template)
template.gsub("<class>", klass)
end
if (ARGV.length != 1)
puts "Usage: newi.rb instruction\n"
exit
end
klass = ARGV[0]
codeDirectory = "Mos6510/Instructions"
testDirectory = "Mos6510.Tests/Instructions"
codeFile = "#{codeDirectory}/#{klass}.cs"
if (File.exists?(codeFile))
puts "Error: The file '#{codeFile}' already exists.\n"
exit
end
testFile = "#{testDirectory}/#{klass}Tests.cs"
if (File.exists?(testFile))
puts "Error: The file '#{testFile}' already exists.\n"
exit
end
File.open(codeFile, 'w') { |file|
file.write(replaceClass(klass, templateCs))
}
File.open(testFile, 'w') { |file|
file.write(replaceClass(klass, templateTest))
}
|
Add an example composition file. | require 'musicality'
include Musicality
include Pitches
include Meters
include ScaleClasses
def scale_exercise scale_class, base_pitch, rhythm
scale = scale_class.to_pitch_seq(base_pitch)
n = scale_class.count
m = rhythm.size
rseq = RepeatingSequence.new((0...m).to_a)
aseq = AddingSequence.new([0]*(m-1) + [1])
cseq = CompoundSequence.new(:+,[aseq,rseq])
pgs = cseq.take(m*n).map {|i| scale.at(i) }
notes = make_notes(rhythm, pgs) +
make_notes([3/4.to_r,-1/4.to_r], [scale.at(n)])
rseq = RepeatingSequence.new(n.downto(n+1-m).to_a)
aseq = AddingSequence.new([0]*(m-1) + [-1])
cseq = CompoundSequence.new(:+,[aseq,rseq])
pgs = cseq.take(m*n).map {|i| scale.at(i) }
notes += make_notes(rhythm, pgs) +
make_notes([3/4.to_r,-1/4.to_r], [scale.at(0)])
return notes
end
score = Score::Measured.new(FOUR_FOUR,120) do |s|
s.parts["scale"] = Part.new(Dynamics::MP) do |p|
Heptatonic::Prima::MODES.each do |mode_n,scale_class|
[[1/4.to_r,1/4.to_r,1/2.to_r]].each do |rhythm|
p.notes += scale_exercise(scale_class, C3, rhythm)
end
end
end
s.program.push 0...s.measures_long
end
seq = ScoreSequencer.new(score.to_timed(200)).make_midi_seq("scale" => 1)
File.open("./scale_exercise.mid", 'wb'){ |fout| seq.write(fout) } | |
Use core Forwardable instead of active support extension | require 'active_support/core_ext/module/delegation'
module EmailPrefixer
class Interceptor
def delivering_email(mail)
mail.subject.prepend(subject_prefix)
end
alias_method :previewing_email, :delivering_email
private
delegate :application_name, :stage_name, to: :configuration
def configuration
EmailPrefixer.configuration
end
def subject_prefix
prefixes = []
prefixes << application_name
prefixes << stage_name.upcase unless stage_name == "production"
"[#{prefixes.join(' ')}] "
end
end
end
| module EmailPrefixer
class Interceptor
extend Forwardable
def_delegators :@configuration, :application_name, :stage_name
def initialize
@configuration = EmailPrefixer.configuration
end
def delivering_email(mail)
mail.subject.prepend(subject_prefix)
end
alias_method :previewing_email, :delivering_email
private
def subject_prefix
prefixes = []
prefixes << application_name
prefixes << stage_name.upcase unless stage_name == 'production'
"[#{prefixes.join(' ')}] "
end
end
end
|
Add origin to test data. | FactoryGirl.define do
# this user has the default role :user
factory :user do
name 'Test User'
sequence(:email) {|n| "example#{n}@example.com" }
phone '+49 30 1234567'
password 'please'
password_confirmation 'please'
factory :admin do
after(:create) do |user|
user.remove_role(:user)
user.add_role(:admin)
end
end
factory :superadmin do
after(:create) do |user|
user.remove_role(:user)
user.add_role(:admin)
user.add_role(:superadmin)
end
end
after(:create) do |user|
user.confirm
end
end
end
| FactoryGirl.define do
# this user has the default role :user
factory :user do
name 'Test User'
sequence(:email) {|n| "example#{n}@example.com" }
phone '+49 30 1234567'
password 'please'
password_confirmation 'please'
origin 'http://localhost:8000'
factory :admin do
after(:create) do |user|
user.remove_role(:user)
user.add_role(:admin)
end
end
factory :superadmin do
after(:create) do |user|
user.remove_role(:user)
user.add_role(:admin)
user.add_role(:superadmin)
end
end
after(:create) do |user|
user.confirm
end
end
end
|
Add period to Pod specification summary. | Pod::Spec.new do |s|
s.name = 'NetworkingKit'
s.version = '0.0.3'
s.summary = 'A small wrapper around NSURLSession for iOS'
s.homepage = 'https://github.com/ccrazy88/networking-kit'
s.author = { 'Chrisna Aing' => 'chrisna@chrisna.org' }
s.source = { :git => 'https://github.com/ccrazy88/networking-kit.git',
:tag => s.version.to_s }
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.platform = :ios, '8.0'
s.frameworks = 'Foundation'
s.source_files = 'Sources/NetworkingKit/**/*.{h,m,swift}'
end
| Pod::Spec.new do |s|
s.name = 'NetworkingKit'
s.version = '0.0.3'
s.summary = 'A small wrapper around NSURLSession for iOS.'
s.homepage = 'https://github.com/ccrazy88/networking-kit'
s.author = { 'Chrisna Aing' => 'chrisna@chrisna.org' }
s.source = { :git => 'https://github.com/ccrazy88/networking-kit.git',
:tag => s.version.to_s }
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.platform = :ios, '8.0'
s.frameworks = 'Foundation'
s.source_files = 'Sources/NetworkingKit/**/*.{h,m,swift}'
end
|
Work around edge case in Dex | module Pacer
module Routes
module RouteOperations
def is(value)
if value.is_a? Symbol
chain_route :filter => :property, :block => proc { |v| v.vars[value] == v }
else
chain_route({ :filter => :object, :value => value })
end
end
def is_not(value)
if value.is_a? Symbol
chain_route :filter => :property, :block => proc { |v| v.vars[value] != v }
else
chain_route({ :filter => :object, :value => value, :negate => true })
end
end
end
end
module Filter
module ObjectFilter
import com.tinkerpop.pipes.filter.ObjectFilterPipe
attr_accessor :value, :negate
protected
def attach_pipe(end_pipe)
pipe = ObjectFilterPipe.new(value, negate ? Pacer::Pipes::NOT_EQUAL : Pacer::Pipes::EQUAL)
pipe.set_starts end_pipe if end_pipe
pipe
end
def inspect_string
if negate
"is_not(#{ value.inspect })"
else
"is(#{ value.inspect })"
end
end
end
end
end
| module Pacer
module Routes
module RouteOperations
def is(value)
if value.nil? and graph and defined? Pacer::DexGraph and graph.is_a? Pacer::DexGraph
# NOTE: This is a workaround for https://github.com/tinkerpop/blueprints/issues/178
only(value)
else
if value.is_a? Symbol
chain_route :filter => :property, :block => proc { |v| v.vars[value] == v }
else
chain_route({ :filter => :object, :value => value })
end
end
end
def is_not(value)
if value.nil? and graph and defined? Pacer::DexGraph and graph.is_a? Pacer::DexGraph
# NOTE: This is a workaround for https://github.com/tinkerpop/blueprints/issues/178
except(value)
else
if value.is_a? Symbol
chain_route :filter => :property, :block => proc { |v| v.vars[value] != v }
else
chain_route({ :filter => :object, :value => value, :negate => true })
end
end
end
end
end
module Filter
module ObjectFilter
import com.tinkerpop.pipes.filter.ObjectFilterPipe
attr_accessor :value, :negate
protected
def attach_pipe(end_pipe)
pipe = ObjectFilterPipe.new(value, negate ? Pacer::Pipes::NOT_EQUAL : Pacer::Pipes::EQUAL)
pipe.set_starts end_pipe if end_pipe
pipe
end
def inspect_string
if negate
"is_not(#{ value.inspect })"
else
"is(#{ value.inspect })"
end
end
end
end
end
|
Fix flaky user name uniqueness in specs | FactoryGirl.define do
factory :user do
user_name { Faker::Internet.user_name }
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
end
end
| FactoryGirl.define do
factory :user do
sequence(:user_name) { |n| Faker::Internet.user_name + n.to_s }
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
end
end
|
Add some pending specs on queueing jobs. | shared_examples "a Que backend" do
it "should be able to drop and create the jobs table" do
DB.table_exists?(:que_jobs).should be true
Que.drop!
DB.table_exists?(:que_jobs).should be false
Que.create!
DB.table_exists?(:que_jobs).should be true
end
it "should be able to clear the jobs table" do
DB[:que_jobs].insert :type => "Que::Job"
DB[:que_jobs].count.should be 1
Que.clear!
DB[:que_jobs].count.should be 0
end
end
| shared_examples "a Que backend" do
it "should be able to drop and create the jobs table" do
DB.table_exists?(:que_jobs).should be true
Que.drop!
DB.table_exists?(:que_jobs).should be false
Que.create!
DB.table_exists?(:que_jobs).should be true
end
it "should be able to clear the jobs table" do
DB[:que_jobs].insert :type => "Que::Job"
DB[:que_jobs].count.should be 1
Que.clear!
DB[:que_jobs].count.should be 0
end
describe "when queueing jobs" do
it "should be able to queue a job with arguments" do
pending
end
it "should be able to queue a job with a specific time to run" do
pending
end
it "should be able to queue a job with a specific priority" do
pending
end
it "should be able to queue a job with queueing options in addition to argument options" do
pending
end
it "should respect a default (but overridable) priority for the job class" do
pending
end
it "should respect a default (but overridable) run_at for the job class" do
pending
end
it "should raise an error if given arguments that can't convert to and from JSON unambiguously" do
pending
end
end
end
|
Fix error value too long for type character varying(30) for workflow name | #
# Copyright (C) 2010-2016 dtk contributors
#
# This file is part of the dtk project.
#
# 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.
#
{
schema: :task,
table: :template,
columns: {
content: { type: :json },
task_action: { type: :varchar, size: 30 }
},
many_to_one: [:component, :module_branch]
}
| #
# Copyright (C) 2010-2016 dtk contributors
#
# This file is part of the dtk project.
#
# 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.
#
{
schema: :task,
table: :template,
columns: {
content: { type: :json },
task_action: { type: :varchar, size: 100 }
},
many_to_one: [:component, :module_branch]
}
|
Remove useless |args| in default Filter Proc | module Camayoc
module Handlers
class Filter
# Constructor - by default, returns true
# * +dest+ :: Handler
# * +options[]+
# * + :with+ :: Regexp matching against event namespace
# * + :if+ :: Proc taking type and event returning true
# * + :unless+ :: Converse of +if+
def initialize(dest,options={},&block)
@dest = dest
if block_given?
@filter = block
elsif options[:with]
pattern = options[:with]
@filter = Proc.new {|type,event| event.ns_stat =~ pattern }
elsif options[:if]
@filter = options[:if]
elsif options[:unless]
proc = options[:unless]
@filter = Proc.new do |type,event|
!proc.call(type,event)
end
else
@filter = Proc.new {|args| true }
end
end
def event(ev)
if @filter.call(ev.type,ev)
@dest.event(ev)
end
end
end
end
end
| module Camayoc
module Handlers
class Filter
# Constructor - by default, returns true
# * +dest+ :: Handler
# * +options[]+
# * + :with+ :: Regexp matching against event namespace
# * + :if+ :: Proc taking type and event returning true
# * + :unless+ :: Converse of +if+
def initialize(dest,options={},&block)
@dest = dest
if block_given?
@filter = block
elsif options[:with]
pattern = options[:with]
@filter = Proc.new {|type,event| event.ns_stat =~ pattern }
elsif options[:if]
@filter = options[:if]
elsif options[:unless]
proc = options[:unless]
@filter = Proc.new do |type,event|
!proc.call(type,event)
end
else
@filter = Proc.new { true }
end
end
def event(ev)
if @filter.call(ev.type,ev)
@dest.event(ev)
end
end
end
end
end
|
Add location provided field to check if location was present when decoding | module MdiCloudDecoder
class Track
attr_reader :id,
:asset,
:latitude,
:longitude,
:received_at,
:recorded_at,
:fields,
:raw_data
def initialize(json)
# Convert fields as best as possible (speed, coordinates, etc)
@fields = {}
json['fields'].each do |key,data|
@fields[key] = FieldDefinition.parse(key, data)
end
@asset = json['asset']
location = json['loc'] || [0,0]
@latitude = location[1]
@longitude = location[0]
@received_at = Time.parse(json['received_at'])
@recorded_at = Time.parse(json['recorded_at'])
@id = json['id']
@raw_data = json
end
def respond_to?(method_sym, include_private = false)
@fields.include?(method_sym.to_s.upcase) || super(sym, include_private)
end
def method_missing(method_sym, *arguments, &block)
@fields[method_sym.to_s.upcase] if @fields.include?(method_sym.to_s.upcase)
end
end
end
| module MdiCloudDecoder
class Track
attr_reader :id,
:asset,
:location_provided,
:latitude,
:longitude,
:received_at,
:recorded_at,
:fields,
:raw_data
def initialize(json)
# Convert fields as best as possible (speed, coordinates, etc)
@fields = {}
json['fields'].each do |key,data|
@fields[key] = FieldDefinition.parse(key, data)
end
@asset = json['asset']
location = json['loc'] || [0,0]
@location_provided = json['loc'].present?
@latitude = location[1]
@longitude = location[0]
@received_at = Time.parse(json['received_at'])
@recorded_at = Time.parse(json['recorded_at'])
@id = json['id']
@raw_data = json
end
def respond_to?(method_sym, include_private = false)
@fields.include?(method_sym.to_s.upcase) || super(sym, include_private)
end
def method_missing(method_sym, *arguments, &block)
@fields[method_sym.to_s.upcase] if @fields.include?(method_sym.to_s.upcase)
end
end
end
|
Remove sections from default displayable resources | module Adminpanel
class Engine < ::Rails::Engine
isolate_namespace Adminpanel
end
class << self
mattr_accessor :analytics_profile_id,
:analytics_key_path,
:analytics_key_filename,
:analytics_account_email,
:analytics_application_name,
:analytics_application_version,
:displayable_resources,
:fb_app_id,
:fb_app_secret,
:twitter_api_key,
:twitter_api_secret,
:instagram_client_id,
:instagram_client_secret
self.analytics_profile_id = nil
self.analytics_key_path = 'config/analytics'
self.analytics_key_filename = nil
self.analytics_account_email = nil
self.analytics_application_name = 'AdminPanel'
self.analytics_application_version = '1.0.0'
self.twitter_api_key = nil
self.twitter_api_secret = nil
self.displayable_resources = [
:users,
:sections
]
self.fb_app_id = nil
self.fb_app_secret = nil
self.twitter_api_key = nil
self.twitter_api_secret = nil
self.instagram_client_id = nil
self.instagram_client_secret = nil
end
def self.setup(&block)
yield self
end
end
| module Adminpanel
class Engine < ::Rails::Engine
isolate_namespace Adminpanel
end
class << self
mattr_accessor :analytics_profile_id,
:analytics_key_path,
:analytics_key_filename,
:analytics_account_email,
:analytics_application_name,
:analytics_application_version,
:displayable_resources,
:fb_app_id,
:fb_app_secret,
:twitter_api_key,
:twitter_api_secret,
:instagram_client_id,
:instagram_client_secret
self.analytics_profile_id = nil
self.analytics_key_path = 'config/analytics'
self.analytics_key_filename = nil
self.analytics_account_email = nil
self.analytics_application_name = 'AdminPanel'
self.analytics_application_version = '1.0.0'
self.twitter_api_key = nil
self.twitter_api_secret = nil
self.displayable_resources = [
:users
]
self.fb_app_id = nil
self.fb_app_secret = nil
self.twitter_api_key = nil
self.twitter_api_secret = nil
self.instagram_client_id = nil
self.instagram_client_secret = nil
end
def self.setup(&block)
yield self
end
end
|
Improve the rails helper invocation syntax | # Conventionally the engine lives in a separate file and imported here, i've
# combined them to reduce the number of files while we work on packaging.
module GovukFrontendAlpha
class Engine < ::Rails::Engine
initializer "govuk_frontend_alpha.assets.precompile" do |app|
app.config.assets.precompile += %w(
govuk-frontend*.css
govuk-template*.css
fonts*.css
govuk-template.min.js
toolkit.min.js
components.min.js
ie-shim.js
template/favicon.ico
template/apple-touch-icon-120x120.png
template/apple-touch-icon-152x152.png
template/apple-touch-icon-60x60.png
template/apple-touch-icon-76x76.png
template/opengraph-image.png
template/gov.uk_logotype_crown_invert.png
template/gov.uk_logotype_crown_invert_trans.png
template/gov.uk_logotype_crown.svg
template/opengraph-image.png
)
end
end
module ApplicationHelper
def govuk_component(name, props)
render partial: "components/#{name}", locals: props.with_indifferent_access
end
end
end
| # Conventionally the engine lives in a separate file and imported here, i've
# combined them to reduce the number of files while we work on packaging.
module GovukFrontendAlpha
class Engine < ::Rails::Engine
initializer "govuk_frontend_alpha.assets.precompile" do |app|
app.config.assets.precompile += %w(
govuk-frontend*.css
govuk-template*.css
fonts*.css
govuk-template.min.js
toolkit.min.js
components.min.js
ie-shim.js
template/favicon.ico
template/apple-touch-icon-120x120.png
template/apple-touch-icon-152x152.png
template/apple-touch-icon-60x60.png
template/apple-touch-icon-76x76.png
template/opengraph-image.png
template/gov.uk_logotype_crown_invert.png
template/gov.uk_logotype_crown_invert_trans.png
template/gov.uk_logotype_crown.svg
template/opengraph-image.png
)
end
end
module ApplicationHelper
def govuk_component
# allows components to be called like this:
# `govuk_component.button(text: 'Start now')`
DynamicComponentRenderer.new(self)
end
class DynamicComponentRenderer
def initialize(view_context)
@view_context = view_context
end
def method_missing(method, *args, &block)
@view_context.render(
partial: "components/#{method.to_s}",
locals: args.first.with_indifferent_access
)
end
end
end
end
|
Fix error in networks metadata repository | class Indocker::Networks::NetworkMetadataRepository
include SmartIoC::Iocify
bean :network_metadata_repository
def put(network_metadata)
if all.any? {|n| n.name == network_metadata.name}
raise Indocker::Errors::NetworkAlreadyDefined, network_metadata.name
end
all.push(network_metadata)
end
def find_by_name(name)
network_metadata = @all.detect {|network| network.name == name.to_s}
raise Indocker::Errors::NetworkIsNotDefined unless network_metadata
network_metadata
end
def clear
@all = []
end
def all
@all ||= []
end
def method_missing(method)
find_by_name(method)
rescue
super
end
end | class Indocker::Networks::NetworkMetadataRepository
include SmartIoC::Iocify
bean :network_metadata_repository
def put(network_metadata)
if all.any? {|n| n.name == network_metadata.name}
raise Indocker::Errors::NetworkAlreadyDefined, network_metadata.name
end
all.push(network_metadata)
end
def find_by_name(name)
network_metadata = all.detect {|network| network.name == name.to_s}
raise Indocker::Errors::NetworkIsNotDefined unless network_metadata
network_metadata
end
def clear
@all = []
end
def all
@all ||= []
end
def method_missing(method)
find_by_name(method)
rescue
super
end
end |
Use ensure_authentication_token, not reset_... as devise hook in User. | class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable
# API
devise :token_authenticatable
before_save :reset_authentication_token
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
# Tenancy
belongs_to :tenant
# Authorization roles
has_and_belongs_to_many :roles, :autosave => true
scope :by_role, lambda{|role| include(:roles).where(:name => role)}
attr_accessible :role_texts
def role?(role)
!!self.roles.find_by_name(role.to_s)
end
def role_texts
roles.map{|role| role.name}
end
def role_texts=(role_names)
self.roles = Role.where(:name => role_names)
end
# Associations
belongs_to :person
#validates_presence_of :person
accepts_nested_attributes_for :person
attr_accessible :person, :person_id, :person_attributes
# Shortcuts
def current_company
person.try(:employers).try(:first)
end
# Locale
attr_accessible :locale
# Helpers
def to_s
person.try(:to_s) || ""
end
end
| class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable
# API
devise :token_authenticatable
before_save :ensure_authentication_token
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
# Tenancy
belongs_to :tenant
# Authorization roles
has_and_belongs_to_many :roles, :autosave => true
scope :by_role, lambda{|role| include(:roles).where(:name => role)}
attr_accessible :role_texts
def role?(role)
!!self.roles.find_by_name(role.to_s)
end
def role_texts
roles.map{|role| role.name}
end
def role_texts=(role_names)
self.roles = Role.where(:name => role_names)
end
# Associations
belongs_to :person
#validates_presence_of :person
accepts_nested_attributes_for :person
attr_accessible :person, :person_id, :person_attributes
# Shortcuts
def current_company
person.try(:employers).try(:first)
end
# Locale
attr_accessible :locale
# Helpers
def to_s
person.try(:to_s) || ""
end
end
|
Fix ID name if mongo or active record | # frozen_string_literal: true
require 'spec_helper'
describe RubyRabbitmqJanus::Models::JanusInstance, type: :model,
name: :janus_instance do
let(:model) { RubyRabbitmqJanus::Models::JanusInstance }
context 'active record model' do
it { expect(model.attribute_names).to include('_id') }
it { expect(model.attribute_names).to include('instance') }
it { expect(model.attribute_names).to include('session') }
it { expect(model.attribute_names).to include('enable') }
end
end
| # frozen_string_literal: true
require 'spec_helper'
describe RubyRabbitmqJanus::Models::JanusInstance, type: :model,
name: :janus_instance do
let(:model) { RubyRabbitmqJanus::Models::JanusInstance }
context 'active record model' do
it { expect(model.attribute_names).to include(ENV['MONGO'].match?('true') ? '_id' : 'id') }
it { expect(model.attribute_names).to include('instance') }
it { expect(model.attribute_names).to include('session') }
it { expect(model.attribute_names).to include('enable') }
end
end
|
Add valid meta data to gemspec | $:.push File.expand_path("../lib", __FILE__)
require "utensils/version"
Gem::Specification.new do |s|
s.name = "utensils"
s.version = Utensils::VERSION
s.authors = ["TODO: Your name"]
s.email = ["TODO: Your email"]
s.homepage = "TODO"
s.summary = "TODO: Summary of Utensils."
s.description = "TODO: Description of Utensils."
s.files = Dir["{app,config,lib,vendor}/**/*"] + ["MIT-LICENSE", "README.md"]
s.test_files = Dir["spec/**/*"]
s.add_dependency "railties", ">= 3.2.5"
s.add_dependency "sass-rails"
s.add_dependency "coffee-rails"
# s.add_dependency "jquery-rails"
end
| $:.push File.expand_path("../lib", __FILE__)
require "utensils/version"
Gem::Specification.new do |s|
s.name = "utensils"
s.version = Utensils::VERSION
s.authors = ["Matt Kitt"]
s.email = ["info@modeset.com"]
s.homepage = "https://github.com/modeset/utensils"
s.summary = "A UI component library"
s.description = "A UI component library"
s.files = Dir["{app,config,lib,vendor}/**/*"] + ["MIT-LICENSE", "README.md"]
s.test_files = Dir["spec/**/*"]
s.add_dependency "railties", ">= 3.2.5"
s.add_dependency "sass-rails"
s.add_dependency "coffee-rails"
# s.add_dependency "jquery-rails"
end
|
Add Facter fact that provides rich details about BIOS and current system. | require 'facter'
require 'facter/manufacturer'
#
# bios_and_system.rb
#
query = {
'BIOS [Ii]nformation' => [
{ 'Vendor:' => 'bios_vendor' },
{ 'Version:' => 'bios_version' },
{ 'Release Date:' => 'bios_release_date' },
{ 'ROM Size:' => 'bios_rom_size' },
{ 'BIOS Revision:' => 'bios_revision' },
{ 'Firmware Revision' => 'bios_firmware_revision' }
],
'[Ss]ystem [Ii]nformation' => [
{ 'Manufacturer:' => 'system_manufacturer' },
{ 'Product Name:' => 'system_product_name' },
{ 'Serial Number:' => 'system_serial_number' },
{ 'UUID:' => 'system_uuid' },
{ 'Family(?: Name)?:' => 'system_family_name' }
]
}
# We call existing helper function to do the heavy-lifting ...
Facter::Manufacturer.dmi_find_system_info(query)
# vim: set ts=2 sw=2 et :
# encoding: utf-8
| |
Improve message displayed when no SCS is found | require "shellwords"
module Rubycritic
module SourceControlSystem
class Base
@@systems = []
def self.register_system
@@systems << self
end
def self.systems
@@systems
end
def self.create
supported_system = systems.detect(&:supported?)
if supported_system
supported_system.new
else
puts "Rubycritic requires a #{system_names} repository."
Double.new
end
end
def self.system_names
systems.join(", ")
end
def self.supported?
raise NotImplementedError.new("The #{self.class} class must implement the #{__method__} method.")
end
def revisions_count(path)
raise NotImplementedError.new("The #{self.class} class must implement the #{__method__} method.")
end
def date_of_last_commit(path)
raise NotImplementedError.new("The #{self.class} class must implement the #{__method__} method.")
end
def has_revision?
raise NotImplementedError.new("The #{self.class} class must implement the #{__method__} method.")
end
def head_reference
raise NotImplementedError.new("The #{self.class} class must implement the #{__method__} method.")
end
def travel_to_head
raise NotImplementedError.new("The #{self.class} class must implement the #{__method__} method.")
end
end
end
end
require "rubycritic/source_control_systems/double"
require "rubycritic/source_control_systems/git"
require "rubycritic/source_control_systems/mercurial"
| require "shellwords"
module Rubycritic
module SourceControlSystem
class Base
@@systems = []
def self.register_system
@@systems << self
end
def self.systems
@@systems
end
def self.create
supported_system = systems.detect(&:supported?)
if supported_system
supported_system.new
else
puts "RubyCritic can provide more feedback if you use a #{connected_system_names} repository."
Double.new
end
end
def self.connected_system_names
"#{systems[0...-1].join(', ')} or #{systems[-1]}"
end
def self.supported?
raise NotImplementedError.new("The #{self.class} class must implement the #{__method__} method.")
end
def revisions_count(path)
raise NotImplementedError.new("The #{self.class} class must implement the #{__method__} method.")
end
def date_of_last_commit(path)
raise NotImplementedError.new("The #{self.class} class must implement the #{__method__} method.")
end
def has_revision?
raise NotImplementedError.new("The #{self.class} class must implement the #{__method__} method.")
end
def head_reference
raise NotImplementedError.new("The #{self.class} class must implement the #{__method__} method.")
end
def travel_to_head
raise NotImplementedError.new("The #{self.class} class must implement the #{__method__} method.")
end
end
end
end
require "rubycritic/source_control_systems/double"
require "rubycritic/source_control_systems/git"
require "rubycritic/source_control_systems/mercurial"
|
Revert "Turn off threading in Bunny dispatcher because it doesn't gain us anything and it appears to gobble memory." | require 'bunny'
require 'connection_pool'
class Woodhouse::Dispatchers::BunnyDispatcher < Woodhouse::Dispatcher
def initialize(config)
super
@pool = new_pool
end
private
def deliver_job(job)
run do |conn|
exchange = conn.exchange(job.exchange_name, :type => :headers)
exchange.publish(" ", :headers => job.arguments)
end
end
def deliver_job_update(job, data)
run do |conn|
exchange = conn.direct("woodhouse.progress")
# establish durable queue to pick up updates
conn.queue(job.job_id, :durable => true).bind(exchange, :routing_key => job.job_id)
exchange.publish(data.to_json, :routing_key => job.job_id)
end
rescue => err
Woodhouse.logger.warn("Error when dispatching job update: #{err.class}: #{err.message}")
end
def run
retried = false
@pool.with do |conn|
yield conn
end
rescue Bunny::ClientTimeout
if retried
raise
else
new_pool!
retried = true
retry
end
end
private
def new_pool!
@pool = new_pool
end
def new_pool
@bunny.stop if @bunny
bunny = @bunny = Bunny.new((@config.server_info || {}).merge(:threaded => false))
@bunny.start
ConnectionPool.new { bunny.create_channel }
end
end
| require 'bunny'
require 'connection_pool'
class Woodhouse::Dispatchers::BunnyDispatcher < Woodhouse::Dispatcher
def initialize(config)
super
@pool = new_pool
end
private
def deliver_job(job)
run do |conn|
exchange = conn.exchange(job.exchange_name, :type => :headers)
exchange.publish(" ", :headers => job.arguments)
end
end
def deliver_job_update(job, data)
run do |conn|
exchange = conn.direct("woodhouse.progress")
# establish durable queue to pick up updates
conn.queue(job.job_id, :durable => true).bind(exchange, :routing_key => job.job_id)
exchange.publish(data.to_json, :routing_key => job.job_id)
end
rescue => err
Woodhouse.logger.warn("Error when dispatching job update: #{err.class}: #{err.message}")
end
def run
retried = false
@pool.with do |conn|
yield conn
end
rescue Bunny::ClientTimeout
if retried
raise
else
new_pool!
retried = true
retry
end
end
private
def new_pool!
@pool = new_pool
end
def new_pool
@bunny.stop if @bunny
bunny = @bunny = Bunny.new(@config.server_info || {})
@bunny.start
ConnectionPool.new { bunny.create_channel }
end
end
|
Use older EventMachine for now | # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$:.unshift(lib) unless $:.include?(lib)
require 'em-jack/version'
Gem::Specification.new do |s|
s.name = 'em-jack'
s.version = EMJack::VERSION
s.authors = ['Dan Sinclair']
s.email = ['dj2@everburning.com']
s.homepage = 'https://github.com/dj2/em-jack/'
s.summary = 'An evented Beanstalk client'
s.description = 'An evented Beanstalk client'
s.required_rubygems_version = '>= 1.3.6'
s.add_dependency 'eventmachine', ['>= 1.0.0.beta.3']
s.add_development_dependency 'bundler', ['~> 1.0.13']
s.add_development_dependency 'rake', ['~> 0.8.7']
s.add_development_dependency 'rspec', ['~> 2.6']
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {spec}/*`.split("\n")
s.require_path = ['lib']
end
| # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$:.unshift(lib) unless $:.include?(lib)
require 'em-jack/version'
Gem::Specification.new do |s|
s.name = 'em-jack'
s.version = EMJack::VERSION
s.authors = ['Dan Sinclair']
s.email = ['dj2@everburning.com']
s.homepage = 'https://github.com/dj2/em-jack/'
s.summary = 'An evented Beanstalk client'
s.description = 'An evented Beanstalk client'
s.required_rubygems_version = '>= 1.3.6'
s.add_dependency 'eventmachine', ['>= 0.12.10']
s.add_development_dependency 'bundler', ['~> 1.0.13']
s.add_development_dependency 'rake', ['~> 0.8.7']
s.add_development_dependency 'rspec', ['~> 2.6']
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {spec}/*`.split("\n")
s.require_path = ['lib']
end
|
Use const_defined? with full name instead. Thanks @jondeandres | require 'multi_json'
require 'rollbar/json/oj'
require 'rollbar/json/default'
begin
require 'oj'
rescue LoadError
end
module Rollbar
module JSON
extend self
attr_writer :options_module
def dump(object)
with_adapter { MultiJson.dump(object, adapter_options) }
end
def load(string)
with_adapter { MultiJson.load(string, adapter_options) }
end
def with_adapter(&block)
MultiJson.with_adapter(detect_multi_json_adapter, &block)
end
def detect_multi_json_adapter
options = {}
options[:adapter] = :oj if defined?(::Oj)
MultiJson.current_adapter(options)
end
def adapter_options
options_module.options
end
def options_module
@options_module ||= find_options_module
end
def find_options_module
module_name = multi_json_adapter_module_name
if constants.find{ |const| const.to_s == module_name }
const_get(module_name)
else
Default
end
end
# MultiJson adapters have this name structure:
# "MultiJson::Adapters::{AdapterModule}"
#
# Ex: MultiJson::Adapters::Oj
# Ex: MultiJson::Adapters::JsonGem
#
# In this method we just get the last module name.
def multi_json_adapter_module_name
MultiJson.current_adapter.name[/^MultiJson::Adapters::(.*)$/, 1]
end
end
end
| require 'multi_json'
require 'rollbar/json/oj'
require 'rollbar/json/default'
begin
require 'oj'
rescue LoadError
end
module Rollbar
module JSON
extend self
attr_writer :options_module
def dump(object)
with_adapter { MultiJson.dump(object, adapter_options) }
end
def load(string)
with_adapter { MultiJson.load(string, adapter_options) }
end
def with_adapter(&block)
MultiJson.with_adapter(detect_multi_json_adapter, &block)
end
def detect_multi_json_adapter
options = {}
options[:adapter] = :oj if defined?(::Oj)
MultiJson.current_adapter(options)
end
def adapter_options
options_module.options
end
def options_module
@options_module ||= find_options_module
end
def find_options_module
module_name = multi_json_adapter_module_name
if const_defined?("::Rollbar::JSON::#{module_name}")
const_get(module_name)
else
Default
end
end
# MultiJson adapters have this name structure:
# "MultiJson::Adapters::{AdapterModule}"
#
# Ex: MultiJson::Adapters::Oj
# Ex: MultiJson::Adapters::JsonGem
#
# In this method we just get the last module name.
def multi_json_adapter_module_name
MultiJson.current_adapter.name[/^MultiJson::Adapters::(.*)$/, 1]
end
end
end
|
Make sure RDoc being loaded. | require 'malt/engines/abstract'
module Malt::Engine
# RDoc template.
#
# http://rdoc.rubyforge.org/
#
# It's suggested that your program require 'rdoc/markup' and
# 'rdoc/markup/to_html' at load time when using this template
# engine.
class RDoc < Abstract
default :rdoc
# Convert rdoc text to html.
def render(params)
text = params[:text]
into = params[:to]
case into
when :html, nil
html_engine.convert(text).to_s
else
super(params)
end
end
private
# Load rdoc makup library if not already loaded.
def initialize_engine
return if defined?(::RDoc::Markup)
require 'rubygems' # hack
require_library 'rdoc/markup'
require_library 'rdoc/markup/to_html'
end
#
def html_engine
@html_engine ||= ::RDoc::Markup::ToHtml.new
end
end
end
| require 'malt/engines/abstract'
module Malt::Engine
# RDoc template.
#
# http://rdoc.rubyforge.org/
#
# It's suggested that your program require 'rdoc/markup' and
# 'rdoc/markup/to_html' at load time when using this template
# engine.
class RDoc < Abstract
default :rdoc
# Convert rdoc text to html.
def render(params)
text = params[:text]
into = params[:to]
case into
when :html, nil
html_engine.convert(text).to_s
else
super(params)
end
end
private
# Load rdoc makup library if not already loaded.
def initialize_engine
return if defined?(::RDoc::Markup)
require 'rubygems' # hack
require_library 'rdoc'
require_library 'rdoc/markup'
require_library 'rdoc/markup/to_html'
end
#
def html_engine
@html_engine ||= ::RDoc::Markup::ToHtml.new
end
end
end
|
Add | Handlebars template tests | require 'rails_helper'
describe Setup::HandlebarsTemplate do
test_namespace = 'Handlebars Template Test'
simple_test_name = 'Simple Test'
bulk_test_name = 'Bulk Test'
before :all do
Setup::HandlebarsTemplate.create!(
namespace: test_namespace,
name: simple_test_name,
code: "Hello {{first_name}} {{last_name}}!"
)
Setup::HandlebarsTemplate.create!(
namespace: test_namespace,
name: bulk_test_name,
bulk_source: true,
code: "{{#each_source}}[{{first_name}} {{last_name}}]{{/each_source}}"
)
end
let! :simple_test do
Setup::HandlebarsTemplate.where(namespace: test_namespace, name: simple_test_name).first
end
let! :simple_source do
Setup::JsonDataType.new(
namespace: test_namespace,
name: 'Simple Source',
schema: {
type: 'object',
properties: {
first_name: {
type: 'string'
},
last_name: {
type: 'string'
}
}
}
).new_from(first_name: 'CENIT', last_name: 'IO')
end
let! :bulk_test do
Setup::HandlebarsTemplate.where(namespace: test_namespace, name: bulk_test_name).first
end
let! :bulk_source do
dt = Setup::JsonDataType.new(
namespace: test_namespace,
name: 'Simple Source',
schema: {
type: 'object',
properties: {
first_name: {
type: 'string'
},
last_name: {
type: 'string'
}
}
}
)
[
dt.new_from(first_name: 'Albert', last_name: 'Einstein'),
dt.new_from(first_name: 'Pablo', last_name: 'Picasso'),
dt.new_from(first_name: 'Aretha', last_name: 'Franklin'),
dt.new_from(first_name: 'CENIT', last_name: 'IO')
]
end
context "simple source template" do
it "renders handlebar template" do
result = simple_test.run(source: simple_source)
expect(result).to eq('Hello CENIT IO!')
end
end
context "bulk source template" do
it "renders handlebar template" do
result = bulk_test.run(sources: bulk_source)
expected = bulk_source.map do |source|
"[#{source.first_name} #{source.last_name}]"
end.join('')
expect(result).to eq(expected)
end
end
end
| |
Add missing newline at EOF | # frozen_string_literal: true
module Users
class BlockedEmailDomain < ApplicationRecord
belongs_to :creator, class_name: 'User'
validates :creator, :domain, presence: true
validates :domain, uniqueness: true
validate :domain_is_a_domain
def domain_is_a_domain
return if domain.blank?
begin
# force the domain we'll validate to start with http:// to force ruby's
# uri parses to use its http mode instead of uri::generic
uri = URI.parse('http://' + domain)
# does the parsed host = the domain provided
valid = uri.host == domain
rescue URI::InvalidURIError
valid = false
end
return if valid == true
errors.add(:domain, 'must be a domain')
end
end
end | # frozen_string_literal: true
module Users
class BlockedEmailDomain < ApplicationRecord
belongs_to :creator, class_name: 'User'
validates :creator, :domain, presence: true
validates :domain, uniqueness: true
validate :domain_is_a_domain
def domain_is_a_domain
return if domain.blank?
begin
# force the domain we'll validate to start with http:// to force ruby's
# uri parses to use its http mode instead of uri::generic
uri = URI.parse('http://' + domain)
# does the parsed host = the domain provided
valid = uri.host == domain
rescue URI::InvalidURIError
valid = false
end
return if valid == true
errors.add(:domain, 'must be a domain')
end
end
end
|
Update WebStorm.app to 9.0.2 and fix license | cask :v1 => 'webstorm' do
version '9.0.1'
sha256 '81d07b1263cfab47f0cd6b66f0884475fcfaf3c705e6aa3f83a01bdc15c139ad'
url "http://download-cf.jetbrains.com/webstorm/WebStorm-#{version}.dmg"
homepage 'http://www.jetbrains.com/webstorm/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'WebStorm.app'
postflight do
plist_set(':JVMOptions:JVMVersion', '1.6+')
end
end
| cask :v1 => 'webstorm' do
version '9.0.2'
sha256 '9638d9a9a68e96db11f8acdc2a0a3e71a316fc14ac74193bc4bcb4745d975203'
url "http://download-cf.jetbrains.com/webstorm/WebStorm-#{version}.dmg"
homepage 'http://www.jetbrains.com/webstorm/'
license :commercial
app 'WebStorm.app'
postflight do
plist_set(':JVMOptions:JVMVersion', '1.6+')
end
end
|
Refactor code from initialize into private method | require 'confoog/version'
module Confoog
DEFAULT_CONFIG = '.confoog'
class Settings
attr_accessor :config_filename, :config_location, :status
def initialize(options = {})
# default options to avoid ambiguity
defaults = { create_file: false }
defaults.merge!(options)
# set all other unset options to return false instead of Nul.
options.default = false
@status = {}
@config_location = options[:location] || '~/'
@config_filename = options[:filename] || DEFAULT_CONFIG
# make sure the file exists ...
if File.exist?(File.expand_path(File.join @config_location, @config_filename))
status['config_exists'] = true
else
if options[:create_file] == true then
full_path = File.expand_path(File.join @config_location, @config_filename)
File.new(full_path, 'w').close
if File.exist? full_path then
status['config_exists'] = true
end
else
status['config_exists'] = false
end
end
end
end
end
| require 'confoog/version'
module Confoog
DEFAULT_CONFIG = '.confoog'
class Settings
attr_accessor :config_filename, :config_location, :status
def initialize(options = {})
# default options to avoid ambiguity
defaults = { create_file: false }
defaults.merge!(options)
# set all other unset options to return false instead of Nul.
options.default = false
@status = {}
@config_location = options[:location] || '~/'
@config_filename = options[:filename] || DEFAULT_CONFIG
# make sure the file exists or can be created...
check_exists(options)
end
private
def check_exists(options)
if File.exist?(File.expand_path(File.join @config_location, @config_filename))
status['config_exists'] = true
else
if options[:create_file] == true
full_path = File.expand_path(File.join @config_location, @config_filename)
File.new(full_path, 'w').close
if File.exist? full_path
status['config_exists'] = true
end
else
status['config_exists'] = false
end
end
end
end
end
|
Add migration to create BookingTemplate table. | class CreateBookingTemplates < ActiveRecord::Migration
def change
create_table :booking_templates do |t|
t.string "title"
t.string "amount"
t.integer "credit_account_id"
t.integer "debit_account_id"
t.text "comments"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "code"
t.string "matcher"
t.string "amount_relates_to"
t.string "type"
t.string "charge_rate_code"
t.string "salary_declaration_code"
t.integer "position"
t.timestamps
end
end
end
| |
Fix migrations dir on gem | db_path = if RubyPocket.environment.production?
[RubyPocket.data_dir, 'pocket_production.db']
else
['db', "pocket_#{RubyPocket.environment.downcase}.db"]
end
DB = Sequel.connect("sqlite://#{File.join(*db_path)}")
Sequel::Model :validation_helpers
Sequel.extension :migration
unless Sequel::Migrator.is_current?(DB, 'db/migrations')
Sequel::Migrator.run(DB, 'db/migrations')
end
| db_path = if RubyPocket.environment.production?
[RubyPocket.data_dir, 'pocket_production.db']
else
['db', "pocket_#{RubyPocket.environment.downcase}.db"]
end
DB = Sequel.connect("sqlite://#{File.join(*db_path)}")
Sequel::Model :validation_helpers
Sequel.extension :migration
Pathname(__dir__).join('../db/migrations').tap do |migrations_path|
unless Sequel::Migrator.is_current?(DB, migrations_path)
Sequel::Migrator.run(DB, migrations_path)
end
end
|
Add foreman as a dependency | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "capistrano-twingly"
spec.version = '2.0.0'
spec.authors = ["Twingly AB"]
spec.email = ["support@twingly.com"]
spec.summary = %q{Capistrano 3 tasks used for Twingly's Ruby deployment}
spec.description = %q{Capistrano 3 tasks used for Twingly's Ruby deployment}
spec.homepage = "https://github.com/twingly/capistrano-twingly"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "capistrano", "~> 3.2"
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rake"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "capistrano-twingly"
spec.version = '2.0.0'
spec.authors = ["Twingly AB"]
spec.email = ["support@twingly.com"]
spec.summary = %q{Capistrano 3 tasks used for Twingly's Ruby deployment}
spec.description = %q{Capistrano 3 tasks used for Twingly's Ruby deployment}
spec.homepage = "https://github.com/twingly/capistrano-twingly"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "capistrano", "~> 3.2"
spec.add_dependency "foreman", "~> 0.82"
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rake"
end
|
Fix database handling with old Rails versions. | # frozen_string_literal: true
require "active_record/errors"
class Gutentag::TagValidations
DEFAULTS = {
:presence => true,
:uniqueness => {:case_sensitive => false}
}.freeze
DATABASE_ERROR_CLASSES = lambda {
classes = [ActiveRecord::NoDatabaseError]
classes << Mysql2::Error if defined?(::Mysql2)
classes << PG::ConnectionBad if defined?(::PG)
classes
}.call.freeze
def self.call(klass)
new(klass).call
end
def initialize(klass)
@klass = klass
end
def call
klass.validates :name, validation_options
end
private
attr_reader :klass
def add_length_validation?
klass.table_exists? && limit.present?
rescue *DATABASE_ERROR_CLASSES
false
end
def limit
@limit ||= klass.columns_hash["name"].limit
end
def validation_options
return DEFAULTS unless add_length_validation?
DEFAULTS.merge :length => {:maximum => limit}
end
end
| # frozen_string_literal: true
require "active_model/errors"
require "active_record/errors"
class Gutentag::TagValidations
DEFAULTS = {
:presence => true,
:uniqueness => {:case_sensitive => false}
}.freeze
DATABASE_ERROR_CLASSES = lambda {
classes = []
if ActiveRecord::VERSION::STRING.to_f > 4.0
classes << ActiveRecord::NoDatabaseError
end
classes << Mysql2::Error if defined?(::Mysql2)
classes << PG::ConnectionBad if defined?(::PG)
classes
}.call.freeze
def self.call(klass)
new(klass).call
end
def initialize(klass)
@klass = klass
end
def call
klass.validates :name, validation_options
end
private
attr_reader :klass
def add_length_validation?
klass.table_exists? && limit.present?
rescue *DATABASE_ERROR_CLASSES
false
end
def limit
@limit ||= klass.columns_hash["name"].limit
end
def validation_options
return DEFAULTS unless add_length_validation?
DEFAULTS.merge :length => {:maximum => limit}
end
end
|
Include map slug in JSON response | json.maps @maps do |map|
json.id map.id
json.name map.name
json.type map.map_type
json.segments map.segments do |map_segment|
json.id map_segment.id
json.name map_segment.name
end
json.compositions @compositions_by_map[map.id] do |composition|
json.id composition.id
json.name composition.name
json.slug composition.slug
end
end
| json.maps @maps do |map|
json.id map.id
json.slug map.slug
json.name map.name
json.type map.map_type
json.segments map.segments do |map_segment|
json.id map_segment.id
json.name map_segment.name
end
json.compositions @compositions_by_map[map.id] do |composition|
json.id composition.id
json.name composition.name
json.slug composition.slug
end
end
|
Make sure the right branch is checked out. | class Git
def clone(repository, branch = 'master')
background do
base_dir = "#{Dir.tmpdir}/reviewit"
project_dir_name = "#{branch}_#{SecureRandom.hex}"
dir = "#{base_dir}/#{project_dir_name}"
FileUtils.rm_rf dir
FileUtils.mkdir_p dir
@dir = base_dir
cloned = call("git clone --depth 1 #{repository} #{project_dir_name}")
@dir = dir
reseted = call("git reset --hard origin/#{branch}") if cloned
@ready = cloned && reseted
yield(self)
FileUtils.rm_rf(dir) if cloned
end
end
attr_reader :dir
def ready?
@ready
end
def am(patch)
contents = patch.formatted
file = Tempfile.new('patch')
file.puts contents
file.close
call("git am #{file.path}")
end
def push(branch)
call("git push origin master:#{branch}")
end
def rm_branch(branch)
call("git push origin :#{branch}")
end
def sha1(branch = 'HEAD')
`cd #{@dir} && git rev-parse #{branch}`.strip
end
protected
def call(command)
`cd #{@dir} && #{command} 2>&1`
$?.success?
end
private
def background
Thread.new do
begin
yield
ensure
ActiveRecord::Base.connection.close
end
end
end
end
| class Git
def clone(repository, branch = 'master')
background do
base_dir = "#{Dir.tmpdir}/reviewit"
project_dir_name = "#{branch}_#{SecureRandom.hex}"
dir = "#{base_dir}/#{project_dir_name}"
FileUtils.rm_rf dir
FileUtils.mkdir_p dir
@dir = base_dir
@ready = call("git clone --branch #{branch} --depth 1 #{repository} #{project_dir_name}")
@dir = dir
yield(self)
FileUtils.rm_rf(dir) if cloned
end
end
attr_reader :dir
def ready?
@ready
end
def am(patch)
contents = patch.formatted
file = Tempfile.new('patch')
file.puts contents
file.close
call("git am #{file.path}")
end
def push(branch)
call("git push origin master:#{branch}")
end
def rm_branch(branch)
call("git push origin :#{branch}")
end
def sha1(branch = 'HEAD')
`cd #{@dir} && git rev-parse #{branch}`.strip
end
protected
def call(command)
`cd #{@dir} && #{command} 2>&1`
$?.success?
end
private
def background
Thread.new do
begin
yield
ensure
ActiveRecord::Base.connection.close
end
end
end
end
|
Use platform independent way to get CPU count | workers ENV.fetch('PUMA_WORKERS', `nproc`).to_i
max_threads = ENV.fetch('PUMA_MAX_THREADS', 16).to_i
min_threads = ENV.fetch('PUMA_MIN_THREADS', max_threads).to_i
threads min_threads, max_threads
environment ENV.fetch('RAILS_ENV', 'production')
bind 'unix:///tmp/run.sock'
preload_app!
# Don't wait for workers to finish their work. We might have long-running HTTP requests.
# But docker gives us only 10 seconds to gracefully handle our shutdown process.
# This settings tries to shut down all threads after 2 seconds. Puma then gives each thread
# an additional 5 seconds to finish the work. This adds up to 7 seconds which is still below
# docker's maximum of 10 seconds.
# This setting only works on Puma >= 3.4.0.
force_shutdown_after 2 if respond_to?(:force_shutdown_after)
on_worker_boot do
ActiveRecord::Base.establish_connection
end
before_fork do
ActiveRecord::Base.connection_pool.disconnect!
end
| workers ENV.fetch('PUMA_WORKERS', Etc.nprocessors).to_i
max_threads = ENV.fetch('PUMA_MAX_THREADS', 16).to_i
min_threads = ENV.fetch('PUMA_MIN_THREADS', max_threads).to_i
threads min_threads, max_threads
environment ENV.fetch('RAILS_ENV', 'production')
bind 'unix:///tmp/run.sock'
preload_app!
# Don't wait for workers to finish their work. We might have long-running HTTP requests.
# But docker gives us only 10 seconds to gracefully handle our shutdown process.
# This settings tries to shut down all threads after 2 seconds. Puma then gives each thread
# an additional 5 seconds to finish the work. This adds up to 7 seconds which is still below
# docker's maximum of 10 seconds.
# This setting only works on Puma >= 3.4.0.
force_shutdown_after 2 if respond_to?(:force_shutdown_after)
on_worker_boot do
ActiveRecord::Base.establish_connection
end
before_fork do
ActiveRecord::Base.connection_pool.disconnect!
end
|
Remove Complex literal for Travis / Ruby 2.0 | ### Range
1...42
1.0...4.2
1..(2+2)
raise..42 rescue nil
'a'..'z'
a = 42
1..a
### Boolean
nil
false
true
### Numbers
1_234
1.23e4
42i
### Symbols
:hello
:"he#{'l'*2}o"
:"h#{3}l#{raise}o#{2}" rescue nil
%s[hello]
%i[hello world]
### Strings
'world'
"w#{0}rld"
### Regexp
/regexp/
/re#{'g'}exp/i
/re#{raise}g#{3}p/i rescue nil
%r[regexp]
### Array
[1, 2, 3]
%w[hello world]
[1, *nil?, 3]
[1, *[2], 3]
[1, raise, *nil?, 3] rescue nil
[1, *raise, 3] rescue nil
### Hash
{:a => 1, :b => 2}
{a: 1, b: 2}
{a: 1, **{b: 2}}
{nil? => 1, :b => 2}
{a: raise, :b => 2} rescue nil
| ### Range
1...42
1.0...4.2
1..(2+2)
raise..42 rescue nil
'a'..'z'
a = 42
1..a
### Boolean
nil
false
true
### Numbers
1_234
1.23e4
### Symbols
:hello
:"he#{'l'*2}o"
:"h#{3}l#{raise}o#{2}" rescue nil
%s[hello]
%i[hello world]
### Strings
'world'
"w#{0}rld"
### Regexp
/regexp/
/re#{'g'}exp/i
/re#{raise}g#{3}p/i rescue nil
%r[regexp]
### Array
[1, 2, 3]
%w[hello world]
[1, *nil?, 3]
[1, *[2], 3]
[1, raise, *nil?, 3] rescue nil
[1, *raise, 3] rescue nil
### Hash
{:a => 1, :b => 2}
{a: 1, b: 2}
{a: 1, **{b: 2}}
{nil? => 1, :b => 2}
{a: raise, :b => 2} rescue nil
|
Add Client and Registrant to autoloader | module EnomAPI
autoload :Interface, File.dirname(__FILE__) + '/enom-api/interface.rb'
autoload :SearchQuery, File.dirname(__FILE__) + '/enom-api/search_query.rb'
end
| module EnomAPI
autoload :Client, File.dirname(__FILE__) + '/enom-api/client.rb'
autoload :Interface, File.dirname(__FILE__) + '/enom-api/interface.rb'
autoload :Registrant, File.dirname(__FILE__) + '/enom-api/registrant.rb'
autoload :SearchQuery, File.dirname(__FILE__) + '/enom-api/search_query.rb'
end
|
Format generated case stmt correctly | module SQL
# Example:
#
# indexed_case_stmt(:code, "DT", "AC", "XY")
#
# Will return the string:
#
# CASE code
# WHEN 'DT' THEN 1
# WHEN 'AC' THEN 2
# END
#
# Used for creating an explicit sort order in conjustion with a find:
#
# Description.where(code: codes).order(indexed_case_stmt(:code, codes))
#
class IndexedCaseStmt
def initialize(column, items)
@column = column
@items = items
end
def generate
clauses = []
@items.each_with_index do |item, index|
clauses << "WHEN '#{item}' THEN #{index}"
end
"CASE #{@column} #{clauses.join} END"
end
end
end
| module SQL
# Example:
#
# indexed_case_stmt(:code, "DT", "AC", "XY")
#
# Will return the string:
#
# CASE code
# WHEN 'DT' THEN 1
# WHEN 'AC' THEN 2
# END
#
# Used for creating an explicit sort order in conjustion with a find:
#
# Description.where(code: codes).order(indexed_case_stmt(:code, codes))
#
class IndexedCaseStmt
def initialize(column, items)
@column = column
@items = items
end
def generate
clauses = []
@items.each_with_index do |item, index|
clauses << "WHEN '#{item}' THEN #{index}"
end
"CASE #{@column} #{clauses.join(" ")} END"
end
end
end
|
Use Gem::Package with RubyGems 2.0.0. | require 'rubygems/tasks/build/task'
require 'rubygems/builder'
require 'fileutils'
module Gem
class Tasks
module Build
#
# The `build:gem` task.
#
class Gem < Task
#
# Initializes the `build:gem` task.
#
# @param [Hash] options
# Additional options.
#
def initialize(options={})
super()
yield self if block_given?
define
end
#
# Defines the `build:gem` task.
#
def define
build_task :gem
# backwards compatibility for Gem::PackageTask
task :gem => 'build:gem'
# backwards compatibility for Hoe
task :package => 'build:gem'
end
#
# Builds the `.gem` package.
#
# @param [String] path
# The path for the `.gem` package.
#
# @param [Gem::Specification] gemspec
# The gemspec to build the `.gem` package from.
#
# @api semipublic
#
def build(path,gemspec)
builder = ::Gem::Builder.new(gemspec)
mv builder.build, Project::PKG_DIR
end
end
end
end
end
| require 'rubygems/tasks/build/task'
require 'fileutils'
if Gem::VERSION > '2.' then require 'rubygems/package'
else require 'rubygems/builder'
end
module Gem
class Tasks
module Build
#
# The `build:gem` task.
#
class Gem < Task
#
# Initializes the `build:gem` task.
#
# @param [Hash] options
# Additional options.
#
def initialize(options={})
super()
yield self if block_given?
define
end
#
# Defines the `build:gem` task.
#
def define
build_task :gem
# backwards compatibility for Gem::PackageTask
task :gem => 'build:gem'
# backwards compatibility for Hoe
task :package => 'build:gem'
end
#
# Builds the `.gem` package.
#
# @param [String] path
# The path for the `.gem` package.
#
# @param [Gem::Specification] gemspec
# The gemspec to build the `.gem` package from.
#
# @api semipublic
#
def build(path,gemspec)
builder = if Gem::VERSION > '2.' then ::Gem::Package.new(gemspec)
else ::Gem::Builder.new(gemspec)
end
mv builder.build, Project::PKG_DIR
end
end
end
end
end
|
Use RSpec exit code matcher here too. | require 'git_tracker'
describe GitTracker do
subject { described_class }
let(:args) { ["a_file", "the_source", "sha1234"] }
describe ".execute" do
before do
subject.stub(:prepare_commit_msg) { true }
end
it "runs the hook, passing the args" do
subject.should_receive(:prepare_commit_msg).with(*args) { true }
subject.execute('prepare-commit-msg', *args)
end
# TODO: stop the abort from writing to stderr during tests?
it "doesn't run hooks we don't know about" do
lambda { subject.execute('non-existent-hook', *args) }.
should raise_error SystemExit, "[git_tracker] command: 'non-existent-hook' does not exist."
end
end
describe ".prepare_commit_msg" do
it "runs the hook, passing the args" do
GitTracker::PrepareCommitMessage.should_receive(:run).with(*args) { true }
subject.prepare_commit_msg(*args)
end
end
describe ".install" do
it 'tells the hook to install itself' do
GitTracker::Hook.should_receive(:install)
subject.install
end
end
end
| require 'spec_helper'
require 'git_tracker'
describe GitTracker do
subject { described_class }
let(:args) { ["a_file", "the_source", "sha1234"] }
describe ".execute" do
before do
subject.stub(:prepare_commit_msg) { true }
end
it "runs the hook, passing the args" do
subject.should_receive(:prepare_commit_msg).with(*args) { true }
subject.execute('prepare-commit-msg', *args)
end
# TODO: stop the abort from writing to stderr during tests?
it "doesn't run hooks we don't know about" do
lambda { subject.execute('non-existent-hook', *args) }.should_not succeed
end
end
describe ".prepare_commit_msg" do
it "runs the hook, passing the args" do
GitTracker::PrepareCommitMessage.should_receive(:run).with(*args) { true }
subject.prepare_commit_msg(*args)
end
end
describe ".install" do
it 'tells the hook to install itself' do
GitTracker::Hook.should_receive(:install)
subject.install
end
end
end
|
Update to reflect the correct URL | class Ability
include CanCan::Ability
def initialize(user)
# Define abilities for the passed in user here. For example:
#
# user ||= User.new # guest user (not logged in)
# if user.admin?
# can :manage, :all
# else
# can :read, :all
# end
#
# The first argument to `can` is the action you are giving the user
# permission to do.
# If you pass :manage it will apply to every action. Other common actions
# here are :read, :create, :update and :destroy.
#
# The second argument is the resource the user can perform the action on.
# If you pass :all it will apply to every resource. Otherwise pass a Ruby
# class of the resource.
#
# The third argument is an optional hash of conditions to further filter the
# objects.
# For example, here the user can only update published articles.
#
# can :update, Article, :published => true
#
# See the wiki for details:
# https://github.com/bryanrite/cancancan/wiki/Defining-Abilities
end
end
| class Ability
include CanCan::Ability
def initialize(user)
# Define abilities for the passed in user here. For example:
#
# user ||= User.new # guest user (not logged in)
# if user.admin?
# can :manage, :all
# else
# can :read, :all
# end
#
# The first argument to `can` is the action you are giving the user
# permission to do.
# If you pass :manage it will apply to every action. Other common actions
# here are :read, :create, :update and :destroy.
#
# The second argument is the resource the user can perform the action on.
# If you pass :all it will apply to every resource. Otherwise pass a Ruby
# class of the resource.
#
# The third argument is an optional hash of conditions to further filter the
# objects.
# For example, here the user can only update published articles.
#
# can :update, Article, :published => true
#
# See the wiki for details:
# https://github.com/CanCanCommunity/cancancan/wiki/Defining-Abilities
end
end
|
Refactor task to use Task model | require 'spec_helper'
require 'yaml'
describe Todoml do
describe "task" do
it "should be initialized with name and point" do
task = Todoml::Task.new({name: 'Task 1', point: 3})
task.name.should eq 'Task 1'
task.point.should eq 3
end
it "should have a default value of point 1" do
task = Todoml::Task.new({name: 'Task lazy'})
task.name.should eq 'Task lazy'
task.point.should eq 1
end
end
it "should parse simple yaml" do
YAML.load_file "./spec/data/simple.yaml"
end
describe "retrieve data" do
before :each do
@data = YAML.load_file "./spec/data/simple.yaml"
end
it "should retrieve velocity" do
@data['velocity'].should eq 10
end
it "should retreve tasks" do
@data['CURRENT'].count.should eq 1
task = @data['CURRENT'].first
task[0].should eq "User can read learn you some erlang"
task[1].should eq 3
end
end
end
| require 'spec_helper'
require 'yaml'
describe Todoml do
describe "task" do
it "should be initialized with name and point" do
task = Todoml::Task.new({name: 'Task 1', point: 3})
task.name.should eq 'Task 1'
task.point.should eq 3
end
it "should have a default value of point 1" do
task = Todoml::Task.new({name: 'Task lazy'})
task.name.should eq 'Task lazy'
task.point.should eq 1
end
end
it "should parse simple yaml" do
YAML.load_file "./spec/data/simple.yaml"
end
describe "retrieve data" do
before :each do
@data = YAML.load_file "./spec/data/simple.yaml"
end
it "should retrieve velocity" do
@data['velocity'].should eq 10
end
it "should retreve tasks" do
@data['CURRENT'].count.should eq 1
task = @data['CURRENT'].first
task = Todoml::Task.new({name: task[0], point: task[1]})
task.name.should eq "User can read learn you some erlang"
task.point.should eq 3
end
end
end
|
Refactor slug counter calculation to avoid increasing queries | # frozen_string_literal: true
module GobiertoCommon
module Sluggable
extend ActiveSupport::Concern
included do
before_validation :set_slug
after_destroy :add_archived_to_slug
end
private
def set_slug
if slug.present? && !slug.include?("archived-")
self.slug = slug.tr("_", " ").parameterize
return
end
base_slug = attributes_for_slug.join("-").tr("_", " ").parameterize
new_slug = base_slug
if uniqueness_validators.present?
count = 2
uniqueness_validators.each do |validator|
while self.class.exists?(scope_attributes(validator.options[:scope]).merge(slug: new_slug))
new_slug = "#{ base_slug }-#{ count }"
count += 1
end
end
end
self.slug = new_slug
end
def add_archived_to_slug
unless destroyed?
update_attribute(:slug, "archived-" + id.to_s)
end
end
def uniqueness_validators
@uniqueness_validators ||= self.class.validators_on(:slug).select { |validator| validator.kind == :uniqueness }
end
def scope_attributes(options)
options = [options].compact unless options.is_a? Enumerable
attributes.slice(*options.map(&:to_s))
end
end
end
| # frozen_string_literal: true
module GobiertoCommon
module Sluggable
extend ActiveSupport::Concern
included do
before_validation :set_slug
after_destroy :add_archived_to_slug
end
private
def set_slug
if slug.present? && !slug.include?("archived-")
self.slug = slug.tr("_", " ").parameterize
return
end
base_slug = attributes_for_slug.join("-").tr("_", " ").parameterize
new_slug = base_slug
if uniqueness_validators.present?
uniqueness_validators.each do |validator|
if (related_slugs = self.class.where("slug ~* ?", "#{ new_slug }-\\d+$").where(scope_attributes(validator.options[:scope]))).exists?
max_count = related_slugs.pluck(:slug).map { |slug| slug.scan(/\d+$/).first.to_i }.max
new_slug = "#{ base_slug }-#{ max_count + 1 }"
elsif self.class.exists?(scope_attributes(validator.options[:scope]).merge(slug: new_slug))
new_slug = "#{ base_slug }-2"
end
end
end
self.slug = new_slug
end
def add_archived_to_slug
unless destroyed?
update_attribute(:slug, "archived-" + id.to_s)
end
end
def uniqueness_validators
@uniqueness_validators ||= self.class.validators_on(:slug).select { |validator| validator.kind == :uniqueness }
end
def scope_attributes(options)
options = [options].compact unless options.is_a? Enumerable
attributes.slice(*options.map(&:to_s))
end
end
end
|
Remove specific that changes over time | require 'vcr_helper'
require 'lexhub'
describe 'Counting words in all commit messages' do
it "counts the words" do
VCR.use_cassette('collect all the words') do
repo = Lexhub::Repo.new('joemsak', 'lexhub')
repo.words.keys.count.should == 53
repo.words['initial'].should == { :count => 1 }
end
end
end
| require 'vcr_helper'
require 'lexhub'
describe 'Counting words in all commit messages' do
it "counts the words" do
VCR.use_cassette('collect all the words') do
repo = Lexhub::Repo.new('joemsak', 'lexhub')
repo.words['initial'].should == { :count => 1 }
end
end
end
|
Raise an ActiveRecord::RecordNotFound exception in ProductsController | Spree::ProductsController.class_eval do
before_filter :can_show_product, :only => :show
private
def can_show_product
@product ||= Spree::Product.find_by_permalink!(params[:id])
if @product.stores.empty? || !@product.stores.include?(current_store)
render :file => "#{::Rails.root}/public/404", :status => 404, :formats => [:html]
end
end
end
| Spree::ProductsController.class_eval do
before_filter :can_show_product, :only => :show
private
def can_show_product
@product ||= Spree::Product.find_by_permalink!(params[:id])
if @product.stores.empty? || !@product.stores.include?(current_store)
raise ActiveRecord::RecordNotFound
end
end
end
|
Add silent fail on failed login | class SessionsController < ApplicationController
def create
if Artist.find_by(email: params[:session][:email]).present?
user = Artist.find_by(email: params[:session][:email])
if user && user.authenticate(params[:session][:password])
session[:artist_id] = user.id
redirect_to artist_path(user)
else
redirect_to '/login'
end
elsif Organization.find_by(email: params[:session][:email]).present?
user = Organization.find_by(email: params[:session][:email])
if user && user.authenticate(params[:session][:password])
session[:organization_id] = user.id
redirect_to organization_path(user)
else
redirect_to '/login'
end
else
flash.now[:danger] = 'Invalid email/password combination'
redirect_to '/login'
end
end
def destroy
if session[:artist_id]
session[:artist_id] = nil
else
session[:organization_id] = nil
end
redirect_to root_path
end
end
| class SessionsController < ApplicationController
def create
if Artist.find_by(email: params[:session][:email]).present?
@user = Artist.find_by(email: params[:session][:email])
if @user && @user.authenticate(params[:session][:password])
session[:artist_id] = @user.id
redirect_to artist_path(@user)
else
# render json: "{error: 'Invalid email/password combination'}"
redirect_to root_path
end
elsif Organization.find_by(email: params[:session][:email]).present?
@user = Organization.find_by(email: params[:session][:email])
if @user && @user.authenticate(params[:session][:password])
session[:organization_id] = @user.id
redirect_to organization_path(@user)
else
# render json: "{error: 'Invalid email/password combination'}"
redirect_to root_path
end
else
# render json: "{error: 'Invalid email/password combination'}"
redirect_to root_path
end
end
def destroy
if session[:artist_id]
session[:artist_id] = nil
else
session[:organization_id] = nil
end
redirect_to root_path
end
end
|
Fix when all of the parameters are not used | require 'json'
require 'net/http'
require 'uri'
module PagerDuty
class Full
attr_reader :apikey, :subdomain
def initialize(apikey, subdomain)
@apikey = apikey
@subdomain = subdomain
end
def api_call(path, params)
uri = URI.parse("https://#{@subdomain}.pagerduty.com/api/v1/#{path}")
http = Net::HTTP.new(uri.host, uri.port)
# This is probably stupid
query_string = ""
params.each do |key, val|
next unless val != nil
query_string << '&' unless key == params.keys.first
query_string << "#{URI.encode(key.to_s)}=#{URI.encode(params[key])}"
end
uri.query = query_string
req = Net::HTTP::Get.new(uri.request_uri)
res = http.get(uri.to_s, {
'Content-type' => 'application/json',
'Authorization' => "Token token=#{@apikey}"
})
end
def Incident()
PagerDuty::Resource::Incident.new(@apikey, @subdomain)
end
def Schedule()
PagerDuty::Resource::Schedule.new(@apikey, @subdomain)
end
end
end
| require 'json'
require 'net/http'
require 'uri'
module PagerDuty
class Full
attr_reader :apikey, :subdomain
def initialize(apikey, subdomain)
@apikey = apikey
@subdomain = subdomain
end
def api_call(path, params)
uri = URI.parse("https://#{@subdomain}.pagerduty.com/api/v1/#{path}")
http = Net::HTTP.new(uri.host, uri.port)
output = []
params.each_pair do |key,val|
output << "#{URI.encode(key.to_s)}=#{URI.encode(val)}"
end
uri.query = "?#{output.join("&")}"
req = Net::HTTP::Get.new(uri.request_uri)
res = http.get(uri.to_s, {
'Content-type' => 'application/json',
'Authorization' => "Token token=#{@apikey}"
})
end
def Incident()
PagerDuty::Resource::Incident.new(@apikey, @subdomain)
end
def Schedule()
PagerDuty::Resource::Schedule.new(@apikey, @subdomain)
end
end
end
|
Improve OrdersHelper spec and delete dead code | # frozen_string_literal: true
require "spec_helper"
describe Admin::OrdersHelper, type: :helper do
describe "#order_adjustments_for_display" do
let(:order) { create(:order) }
it "selects eligible adjustments" do
adjustment = create(:adjustment, adjustable: order, amount: 1)
expect(helper.order_adjustments_for_display(order)).to eq [adjustment]
end
it "filters shipping method adjustments" do
create(:adjustment, adjustable: order, amount: 1, originator_type: "Spree::ShippingMethod")
expect(helper.order_adjustments_for_display(order)).to eq []
end
it "filters ineligible adjustments" do
create(:adjustment, adjustable: order, amount: 0, eligible: false,
originator_type: "Spree::TaxRate")
expect(helper.order_adjustments_for_display(order)).to eq []
end
end
end
| # frozen_string_literal: true
require "spec_helper"
describe Admin::OrdersHelper, type: :helper do
describe "#order_adjustments_for_display" do
let(:order) { create(:order) }
it "selects eligible adjustments" do
adjustment = create(:adjustment, order: order, adjustable: order, amount: 1)
expect(helper.order_adjustments_for_display(order)).to eq [adjustment]
end
it "filters shipping method adjustments" do
create(:adjustment, order: order, adjustable: order, amount: 1, originator_type: "Spree::ShippingMethod")
expect(helper.order_adjustments_for_display(order)).to eq []
end
it "filters ineligible adjustments" do
create(:adjustment, adjustable: order, amount: 0, eligible: false,
originator_type: "Spree::TaxRate")
expect(helper.order_adjustments_for_display(order)).to eq []
end
end
end
|
Add tests for request methods for networking security groups. | Shindo.tests('HP::Network | networking security group requests', ['hp', 'networking', 'securitygroup']) do
@security_group_format = {
'id' => String,
'name' => String,
'description' => String,
'tenant_id' => String,
'security_group_rules' => [Hash]
}
tests('success') do
@sec_group_id = nil
tests("#create_security_group('fog_security_group', 'tests group')").formats(@security_group_format) do
attributes = {:name => 'fog_security_group', :description => 'tests group'}
data = HP[:network].create_security_group(attributes).body['security_group']
@sec_group_id = data['id']
data
end
tests("#get_security_group('#{@sec_group_id}')").formats(@security_group_format) do
HP[:network].get_security_group(@sec_group_id).body['security_group']
end
tests("#list_security_groups").formats('security_groups' => [@security_group_format]) do
HP[:network].list_security_groups.body
end
tests("#delete_security_group('#{@sec_group_id}')").succeeds do
HP[:network].delete_security_group(@sec_group_id)
end
end
tests('failure') do
tests("#get_security_group(0)").raises(Fog::HP::Network::NotFound) do
HP[:network].get_security_group(0)
end
tests("#delete_security_group(0)").raises(Fog::HP::Network::NotFound) do
HP[:network].delete_security_group(0)
end
end
end
| |
Return the params, eh, instead of an array of the required params. | require_dependency "fieri/application_controller"
module Fieri
class JobsController < ApplicationController
def create
CookbookWorker.perform_async(job_params)
render text: "ok"
rescue ActionController::ParameterMissing => e
render status: 400, text: "Error: #{e.message}"
end
private
def job_params
[:cookbook_name, :cookbook_version, :cookbook_artifact_url].each do |param|
params.require(param)
end
end
end
end
| require_dependency "fieri/application_controller"
module Fieri
class JobsController < ApplicationController
def create
CookbookWorker.perform_async(job_params)
render text: "ok"
rescue ActionController::ParameterMissing => e
render status: 400, text: "Error: #{e.message}"
end
private
def job_params
[:cookbook_name, :cookbook_version, :cookbook_artifact_url].each do |param|
params.require(param)
end
params
end
end
end
|
Fix dropbox credentials not working with Pathname | require "uri"
module Paperclip
module Storage
module Dropbox
class UrlGenerator
def initialize(attachment, attachment_options)
@attachment = attachment
@attachment_options = attachment_options
end
def generate(style, options)
if @attachment.present?
url = file_url(style)
url = URI.parse(url)
url.query = [url.query, "dl=1"].compact.join("&") if options[:download]
url.to_s
else
@attachment_options[:interpolator].interpolate(@attachment_options[:default_url], @attachment, style)
end
end
private
def user_id
@attachment_options[:dropbox_credentials][:user_id]
end
end
end
end
end
| require "uri"
module Paperclip
module Storage
module Dropbox
class UrlGenerator
def initialize(attachment, attachment_options)
@attachment = attachment
@attachment_options = attachment_options
end
def generate(style, options)
if @attachment.present?
url = file_url(style)
url = URI.parse(url)
url.query = [url.query, "dl=1"].compact.join("&") if options[:download]
url.to_s
else
@attachment_options[:interpolator].interpolate(@attachment_options[:default_url], @attachment, style)
end
end
private
def user_id
@attachment.dropbox_credentials[:user_id]
end
end
end
end
end
|
Upgrade gemspec dependency to use Rails 5.1 | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "jbadmin/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "jbadmin"
s.version = Jbadmin::VERSION
s.authors = ["Nick Brabant"]
s.email = ["nick@juliabalfour.com"]
s.homepage = "https://github.com/juliabalfour/jbadmin"
s.summary = "Rails plugin for admin sites"
s.description = "Rails plugin for admin sites"
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"]
s.add_dependency "rails", ">= 5.0.2"
s.add_dependency "sass-rails", ">= 5.0.4"
s.add_dependency "jquery-rails", ">= 4.3.1"
s.add_dependency "haml", ">= 4.0.7"
s.add_dependency "font-awesome-sass", "~> 4.7.0"
s.add_dependency "gravatar_image_tag", ">= 1.2"
s.add_dependency "breadcrumbs_on_rails", ">= 3.0"
s.add_development_dependency "sqlite3"
s.add_development_dependency "bump"
end
| $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "jbadmin/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "jbadmin"
s.version = Jbadmin::VERSION
s.authors = ["Nick Brabant"]
s.email = ["nick@juliabalfour.com"]
s.homepage = "https://github.com/juliabalfour/jbadmin"
s.summary = "Rails plugin for admin sites"
s.description = "Rails plugin for admin sites"
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"]
s.add_dependency "rails", ">= 5.1.0"
s.add_dependency "sass-rails", ">= 5.0.4"
s.add_dependency "jquery-rails", ">= 4.3.1"
s.add_dependency "haml", ">= 4.0.7"
s.add_dependency "font-awesome-sass", "~> 4.7.0"
s.add_dependency "gravatar_image_tag", ">= 1.2"
s.add_dependency "breadcrumbs_on_rails", ">= 3.0"
s.add_development_dependency "sqlite3"
s.add_development_dependency "bump"
end
|
Fix project factory to use Date in release_date | # Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :project do
book
client
release_date 3.months.since
end
end
| # Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :project do
book
client
release_date 3.months.since.to_date
end
end
|
Use mercurial as dep instead of hg | require 'formula'
class Gh < Formula
VERSION = '0.6.1'
homepage 'https://github.com/jingweno/gh'
url "https://github.com/jingweno/gh/archive/#{VERSION}.tar.gz"
sha1 '1e4ca70ebf018ae192a641f18b735beca5df5c31'
version "#{VERSION}-boxen1"
head 'https://github.com/jingweno/gh.git'
depends_on 'hg'
depends_on 'go'
def install
go_path = Dir.getwd
system "GOPATH='#{go_path}' go get -d ./..."
system "GOPATH='#{go_path}' go build -o gh"
bin.install 'gh'
end
def caveats; <<-EOS.undent
To upgrade gh, run `brew upgrade https://raw.github.com/jingweno/gh/master/homebrew/gh.rb`
More information here: https://github.com/jingweno/gh/blob/master/README.md
EOS
end
test do
assert_equal VERSION, `#{bin}/gh version`.split.last
end
end
| require 'formula'
class Gh < Formula
VERSION = '0.6.1'
homepage 'https://github.com/jingweno/gh'
url "https://github.com/jingweno/gh/archive/#{VERSION}.tar.gz"
sha1 '1e4ca70ebf018ae192a641f18b735beca5df5c31'
version "#{VERSION}-boxen1"
head 'https://github.com/jingweno/gh.git'
depends_on 'mercurial'
depends_on 'go'
def install
go_path = Dir.getwd
system "GOPATH='#{go_path}' go get -d ./..."
system "GOPATH='#{go_path}' go build -o gh"
bin.install 'gh'
end
def caveats; <<-EOS.undent
To upgrade gh, run `brew upgrade https://raw.github.com/jingweno/gh/master/homebrew/gh.rb`
More information here: https://github.com/jingweno/gh/blob/master/README.md
EOS
end
test do
assert_equal VERSION, `#{bin}/gh version`.split.last
end
end
|
Add log_error to log ruby errors | require "logger"
require "colorize"
module Logging
@loggers = {}
def logger
@logger ||= Logging.logger_for self.class.name
end
def self.logger_for(class_name)
@loggers[class_name] ||= create_logger_for(class_name)
end
def self.create_logger_for(class_name)
logger = Logger.new STDERR
logger.progname = class_name
logger.formatter = LogFormatter.new
logger
end
def self.included(base)
base.define_singleton_method(:logger) do
@logger ||= Logging.logger_for self.name
end
end
class LogFormatter < Logger::Formatter
def call(severity, time, progname, msg)
color = :default
case severity
when "DEBUG"
color = :light_blue
when "WARN"
color = :magenta
when "INFO"
color = :cyan
when "ERROR"
color = :light_red
when "FATAL"
color = :light_red
end
possible_colors = String.color_codes.keys.delete_if { |sym| sym.to_s.include?("black") || sym.to_s.include?("default") }
progname_color = possible_colors[progname.hash % possible_colors.length]
"#{time.strftime("%H:%M:%S")} [#{severity.colorize(color)}] [#{progname.colorize(progname_color)}]: #{msg}\n"
end
end
end
| require "logger"
require "colorize"
module Logging
@loggers = {}
def logger
@logger ||= Logging.logger_for self.class.name
end
def log_error(error)
logger.error "Error: #{error.message}"
error.backtrace.each { |line| logger.error line }
end
def self.logger_for(class_name)
@loggers[class_name] ||= create_logger_for(class_name)
end
def self.create_logger_for(class_name)
logger = Logger.new STDERR
logger.progname = class_name
logger.formatter = LogFormatter.new
logger
end
def self.included(base)
base.define_singleton_method(:logger) do
@logger ||= Logging.logger_for self.name
end
end
class LogFormatter < Logger::Formatter
def call(severity, time, progname, msg)
color = :default
case severity
when "DEBUG"
color = :light_blue
when "WARN"
color = :magenta
when "INFO"
color = :cyan
when "ERROR"
color = :light_red
when "FATAL"
color = :light_red
end
possible_colors = String.color_codes.keys.delete_if { |sym| sym.to_s.include?("black") || sym.to_s.include?("default") }
progname_color = possible_colors[progname.hash % possible_colors.length]
"#{time.strftime("%H:%M:%S")} [#{severity.colorize(color)}] [#{progname.colorize(progname_color)}]: #{msg}\n"
end
end
end
|
Add tests for the Git Source plugin | require 'spec_helper'
describe Cyclid::API::Plugins::Git do
it 'creates a new instance' do
expect{ Cyclid::API::Plugins::Git.new }.to_not raise_error
end
class TestTransport
attr_reader :cmd, :path
def exec(cmd, path = nil)
@cmd = cmd
@path = path
true
end
end
it 'clones a git repository' do
transport = TestTransport.new
sources = { url: 'https://test.example.com/example/test' }
git = nil
expect{ git = Cyclid::API::Plugins::Git.new }.to_not raise_error
expect(git.checkout(transport, nil, sources)).to be true
expect(transport.cmd).to eq('git clone https://test.example.com/example/test')
end
it 'clones a git repository with an OAuth token' do
transport = TestTransport.new
sources = { url: 'https://test.example.com/example/test', token: 'abcxyz' }
git = nil
expect{ git = Cyclid::API::Plugins::Git.new }.to_not raise_error
expect(git.checkout(transport, nil, sources)).to be true
expect(transport.cmd).to eq('git clone https://abcxyz@test.example.com/example/test')
end
it 'clones a git repository with a branch' do
transport = TestTransport.new
sources = { url: 'https://test.example.com/example/test', branch: 'test' }
ctx = { workspace: '/test' }
git = nil
expect{ git = Cyclid::API::Plugins::Git.new }.to_not raise_error
expect(git.checkout(transport, ctx, sources)).to be true
expect(transport.path).to eq('/test/test')
expect(transport.cmd).to eq('git checkout test')
end
end
| |
Set time zone to Berlin | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module D21
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# config.middleware.use I18n::JS::Middleware # I18n-js
config.logger = Logger.new(STDOUT)
end
end
| require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module D21
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# config.middleware.use I18n::JS::Middleware # I18n-js
config.logger = Logger.new(STDOUT)
config.time_zone = 'Berlin'
end
end
|
Add origin head to tests Origin header value must be different from server domain | module RequestHelper
def authorized_headers
{
'HTTP_ACCEPT' => 'application/vnd.api+json',
'HTTP_AUTHORIZATION' => 'Token openworksauthtoken'
}
end
def authorized_preflight_headers
{
'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' => 'accept, authorization, origin',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'GET',
}
end
end
module ActionDispatch::Integration::RequestHelpers
def options(path, parameters = nil, headers_or_env = nil)
process :options, path, parameters, headers_or_env
end
end
| module RequestHelper
def authorized_headers
{
'HTTP_ACCEPT' => 'application/vnd.api+json',
'HTTP_AUTHORIZATION' => 'Token openworksauthtoken'
}
end
def authorized_preflight_headers
{
'HTTP_ACCESS_CONTROL_REQUEST_HEADER' => 'accept, authorization, origin',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'GET',
'ORIGIN' => 'http://otherdomain.test/'
}
end
end
module ActionDispatch::Integration::RequestHelpers
def options(path, parameters = nil, headers_or_env = nil)
process :options, path, parameters, headers_or_env
end
end
|
Include SVGComponent support by default | require 'browser'
require 'clearwater/component'
require 'clearwater/link'
require 'clearwater/application'
| require 'browser'
require 'clearwater/component'
require 'clearwater/svg_component'
require 'clearwater/link'
require 'clearwater/application'
|
Remove one more occurrence of render_with_scope | class Spree::UserPasswordsController < Devise::PasswordsController
include Spree::Core::ControllerHelpers
helper 'spree/users', 'spree/base'
after_filter :associate_user
def new
super
end
# Temporary Override until next Devise release (i.e after v1.3.4)
# line:
# respond_with resource, :location => new_session_path(resource_name)
# is generating bad url /session/new.user
#
# overridden to:
# respond_with resource, :location => login_path
#
def create
self.resource = resource_class.send_reset_password_instructions(params[resource_name])
if resource.errors.empty?
set_flash_message(:notice, :send_instructions) if is_navigational_format?
respond_with resource, :location => spree.login_path
else
respond_with_navigational(resource){ render_with_scope :new }
end
end
def edit
super
end
def update
super
end
end
| class Spree::UserPasswordsController < Devise::PasswordsController
include Spree::Core::ControllerHelpers
helper 'spree/users', 'spree/base'
after_filter :associate_user
def new
super
end
# Temporary Override until next Devise release (i.e after v1.3.4)
# line:
# respond_with resource, :location => new_session_path(resource_name)
# is generating bad url /session/new.user
#
# overridden to:
# respond_with resource, :location => login_path
#
def create
self.resource = resource_class.send_reset_password_instructions(params[resource_name])
if resource.errors.empty?
set_flash_message(:notice, :send_instructions) if is_navigational_format?
respond_with resource, :location => spree.login_path
else
respond_with_navigational(resource) { render :new }
end
end
def edit
super
end
def update
super
end
end
|
Fix some gem description details | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "r2/version"
Gem::Specification.new do |s|
s.name = "r2"
s.version = R2::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Matt Sanford"]
s.email = ["matt@twitter.com"]
s.homepage = ""
s.summary = %q{CSS flipper for right-to-left processing}
s.description = %q{A Ruby port of https://github.com/ded/r2}
s.rubyforge_project = "r2"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
end
| # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "r2/version"
Gem::Specification.new do |s|
s.name = "r2"
s.version = R2::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Matt Sanford"]
s.email = ["matt@twitter.com"]
s.homepage = ""
s.summary = %q{CSS flipper for right-to-left processing}
s.description = %q{CSS flipper for right-to-left processing. A Ruby port of https://github.com/ded/r2}
s.rubyforge_project = "r2"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
end
|
Add preprocessor definition to podspec | Pod::Spec.new do |s|
s.name = 'libPusher'
s.version = '1.4'
s.license = 'MIT'
s.summary = 'An Objective-C client for the Pusher.com service'
s.homepage = 'https://github.com/lukeredpath/libPusher'
s.author = 'Luke Redpath'
s.source = { :git => 'git://github.com/lukeredpath/libPusher.git', :tag => 'v1.4' }
s.source_files = 'Library/*'
s.requires_arc = true
s.dependency 'SocketRocket', "0.2"
s.compiler_flags = '-Wno-arc-performSelector-leaks', '-Wno-format'
end
| Pod::Spec.new do |s|
s.name = 'libPusher'
s.version = '1.4'
s.license = 'MIT'
s.summary = 'An Objective-C client for the Pusher.com service'
s.homepage = 'https://github.com/lukeredpath/libPusher'
s.author = 'Luke Redpath'
s.source = { :git => 'git://github.com/lukeredpath/libPusher.git', :tag => 'v1.4' }
s.source_files = 'Library/*'
s.requires_arc = true
s.dependency 'SocketRocket', "0.2"
s.compiler_flags = '-Wno-arc-performSelector-leaks', '-Wno-format'
s.xcconfig = { 'GCC_PREPROCESSOR_DEFINITIONS' => 'kPTPusherClientLibraryVersion=@\"1.5\"' }
end
|
Fix list of files in gemspec. | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/mince_model/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = "mince_model"
gem.version = MinceModel::VERSION
gem.authors = ["Matt Simpson", "Craig Buchek"]
gem.email = ["matt.simpson3@gmail.com"]
gem.description = %q{Common model behavior for objects backed by Mince}
gem.summary = %q{Common model behavior for objects backed by Mince}
gem.homepage = "http://github.com/ionicmobile/mince_model"
gem.files = %w(lib/mince_model lib/mince_model/version)
gem.test_files = %w(spec/lib/mince_model)
gem.require_paths = ["lib"]
gem.add_dependency 'activesupport', '~> 3.2'
gem.add_dependency 'activemodel', '~> 3.2'
gem.add_development_dependency('rspec', "~> 2.11")
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/mince_model/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = "mince_model"
gem.version = MinceModel::VERSION
gem.authors = ["Matt Simpson", "Craig Buchek"]
gem.email = ["matt.simpson3@gmail.com"]
gem.description = %q{Common model behavior for objects backed by Mince}
gem.summary = %q{Common model behavior for objects backed by Mince}
gem.homepage = "http://github.com/ionicmobile/mince_model"
gem.files = %w(lib/mince_model.rb lib/mince_model/version.rb)
gem.test_files = %w(spec/lib/mince_model_spec.rb)
gem.require_paths = ["lib"]
gem.add_dependency 'activesupport', '~> 3.2'
gem.add_dependency 'activemodel', '~> 3.2'
gem.add_development_dependency('rspec', "~> 2.11")
end
|
Fix specs now that order's store is required | RSpec.feature 'Admin orders', type: :feature do
background do
sign_in_as! create(:admin_user)
end
# Regression #203
scenario 'can list orders' do
expect { visit spree.admin_orders_path }.not_to raise_error
end
# Regression #203
scenario 'can new orders' do
FactoryGirl.create(:country)
expect { visit spree.new_admin_order_path }.not_to raise_error
end
# Regression #203
scenario 'can not edit orders' do
expect { visit spree.edit_admin_order_path('nodata') }.to raise_error(ActiveRecord::RecordNotFound)
end
# Regression #203
scenario 'can edit orders' do
create(:order, number: 'R123')
visit spree.edit_admin_order_path('R123')
expect(page).not_to have_text 'Authorization Failure'
end
end
| RSpec.feature 'Admin orders', type: :feature do
background do
create(:store)
sign_in_as! create(:admin_user)
end
# Regression #203
scenario 'can list orders' do
expect { visit spree.admin_orders_path }.not_to raise_error
end
# Regression #203
scenario 'can new orders' do
FactoryGirl.create(:country)
expect { visit spree.new_admin_order_path }.not_to raise_error
end
# Regression #203
scenario 'can not edit orders' do
expect { visit spree.edit_admin_order_path('nodata') }.to raise_error(ActiveRecord::RecordNotFound)
end
# Regression #203
scenario 'can edit orders' do
create(:order, number: 'R123')
visit spree.edit_admin_order_path('R123')
expect(page).not_to have_text 'Authorization Failure'
end
end
|
Add name stanza to Google Chrome Beta | cask :v1 => 'google-chrome-beta' do
version :latest
sha256 :no_check
url 'https://dl.google.com/chrome/mac/beta/googlechrome.dmg'
homepage 'https://www.google.com/chrome/browser/beta.html?platform=mac&extra=betachannel'
license :gratis
tags :vendor => 'Google'
app 'Google Chrome.app'
zap :delete => [
'~/Library/Application Support/Google/Chrome',
'~/Library/Caches/Google/Chrome',
'~/Library/Caches/com.google.Chrome',
'~/Library/Caches/com.google.Chrome.helper.EH',
'~/Library/Caches/com.google.Keystone.Agent',
'~/Library/Caches/com.google.SoftwareUpdate',
'~/Library/Google/GoogleSoftwareUpdate',
'~/Library/Logs/GoogleSoftwareUpdateAgent.log',
],
:rmdir => [
'~/Library/Caches/Google',
'~/Library/Google',
]
caveats <<-EOS.undent
The Mac App Store version of 1Password won't work with a Homebrew-Cask-linked Google Chrome. To bypass this limitation, you need to either:
+ Move Google Chrome to your /Applications directory (the app itself, not a symlink).
+ Install 1Password from outside the Mac App Store (licenses should transfer automatically, but you should contact AgileBits about it).
EOS
end
| cask :v1 => 'google-chrome-beta' do
version :latest
sha256 :no_check
url 'https://dl.google.com/chrome/mac/beta/googlechrome.dmg'
name 'Google Chrome'
homepage 'https://www.google.com/chrome/browser/beta.html?platform=mac&extra=betachannel'
license :gratis
tags :vendor => 'Google'
app 'Google Chrome.app'
zap :delete => [
'~/Library/Application Support/Google/Chrome',
'~/Library/Caches/Google/Chrome',
'~/Library/Caches/com.google.Chrome',
'~/Library/Caches/com.google.Chrome.helper.EH',
'~/Library/Caches/com.google.Keystone.Agent',
'~/Library/Caches/com.google.SoftwareUpdate',
'~/Library/Google/GoogleSoftwareUpdate',
'~/Library/Logs/GoogleSoftwareUpdateAgent.log',
],
:rmdir => [
'~/Library/Caches/Google',
'~/Library/Google',
]
caveats <<-EOS.undent
The Mac App Store version of 1Password won't work with a Homebrew-Cask-linked Google Chrome. To bypass this limitation, you need to either:
+ Move Google Chrome to your /Applications directory (the app itself, not a symlink).
+ Install 1Password from outside the Mac App Store (licenses should transfer automatically, but you should contact AgileBits about it).
EOS
end
|
Define only the reader because the writer is defined below | require 'ostruct'
class Persistable
def persisted?
@persisted ||= nil
end
def save!
@persisted = true
end
end
class ParentRubyObject < Persistable
attr_accessor \
:before_save_value,
:dynamic_field,
:nil_field,
:number_field,
:string_field,
:false_field,
:id,
:extra_fields
attr_writer :child_ruby_objects
def initialize
self.id = 23
self.before_save_value = 11
end
def save!
super
child_ruby_objects.each(&:save!)
end
def child_ruby_objects
@child_ruby_objects ||= []
end
def before_validation_value
1
end
end
class ChildRubyObject < Persistable
attr_accessor \
:parent_ruby_object,
:parent_ruby_object_id,
:number_field
def parent_ruby_object=(parent_ruby_object)
@parent_ruby_object = parent_ruby_object
@parent_ruby_object_id = parent_ruby_object.id
end
end
module NamespacedClasses
class RubyObject < OpenStruct
attr_accessor :display
end
end
class Troublemaker
def raise_exception=(value)
raise "Troublemaker exception" if value
end
end
class Sequencer
attr_accessor :simple_iterator, :param_iterator, :block_iterator
class Namespaced
attr_accessor :iterator
end
end
class ClassWithInit < Struct.new(:arg1, :arg2)
end
| require 'ostruct'
class Persistable
def persisted?
@persisted ||= nil
end
def save!
@persisted = true
end
end
class ParentRubyObject < Persistable
attr_accessor \
:before_save_value,
:dynamic_field,
:nil_field,
:number_field,
:string_field,
:false_field,
:id,
:extra_fields
attr_writer :child_ruby_objects
def initialize
self.id = 23
self.before_save_value = 11
end
def save!
super
child_ruby_objects.each(&:save!)
end
def child_ruby_objects
@child_ruby_objects ||= []
end
def before_validation_value
1
end
end
class ChildRubyObject < Persistable
attr_accessor \
:parent_ruby_object_id,
:number_field
attr_reader \
:parent_ruby_object
def parent_ruby_object=(parent_ruby_object)
@parent_ruby_object = parent_ruby_object
@parent_ruby_object_id = parent_ruby_object.id
end
end
module NamespacedClasses
class RubyObject < OpenStruct
attr_accessor :display
end
end
class Troublemaker
def raise_exception=(value)
raise "Troublemaker exception" if value
end
end
class Sequencer
attr_accessor :simple_iterator, :param_iterator, :block_iterator
class Namespaced
attr_accessor :iterator
end
end
class ClassWithInit < Struct.new(:arg1, :arg2)
end
|
Remove the use of the wlp provider as its all in wlp_application now | # Install the helloworld application
# TODO: use app from wasdev
serverName = "Test1"
application "HelloworldApp2" do
path "/usr/local/helloworldApp"
repository "http://central.maven.org/maven2/org/apache/tuscany/sca/samples/helloworld-webapp/2.0/helloworld-webapp-2.0.war"
scm_provider Chef::Provider::RemoteFile::Deploy
owner "wlp"
group "wlp-admin"
wlp_application do
server_name serverName
features [ "jsp-2.2", "servlet-3.0" ]
# application name and location default to above "HelloworldApp" and path
# config other application attributes via attributes here, eg:
# application_type "war"
# application_location "/some/file"
# application_context_root "someroot"
# application_auto_start "true"
# or, to use a custom xml template from this cookbook:
# application_xml_template "HelloworldApp.xml.erb"
end
wlp do
server_name serverName
end
end
| # Install the helloworld application
# TODO: use app from wasdev
serverName = "Test1"
application "HelloworldApp2" do
path "/usr/local/helloworldApp"
repository "http://central.maven.org/maven2/org/apache/tuscany/sca/samples/helloworld-webapp/2.0/helloworld-webapp-2.0.war"
scm_provider Chef::Provider::RemoteFile::Deploy
owner "wlp"
group "wlp-admin"
wlp_application do
server_name serverName
features [ "jsp-2.2", "servlet-3.0" ]
# application name and location default to above "HelloworldApp" and path
# config other application attributes via attributes here, eg:
# application_type "war"
# application_location "/some/file"
# application_context_root "someroot"
# application_auto_start "true"
# or, to use a custom xml template from this cookbook:
# application_xml_template "HelloworldApp.xml.erb"
end
end
|
Fix zone topic formulas creation | # frozen_string_literal: true
module Api
module V2
class ZoneTopicFormulasController < FormulasController
def find_rule
package = current_project_anchor.project.packages.find(params[:set_id])
rule = package.zone_activity_rule
if rule.nil?
rule = package.rules.create!(kind: :zone, name: package.name + " - zone activity")
end
rule
end
end
end
end | # frozen_string_literal: true
module Api
module V2
class ZoneTopicFormulasController < FormulasController
def find_rule
package = current_project_anchor.project.packages.find(params[:set_id])
rule = package.zone_activity_rule
if rule.nil?
rule = package.rules.create!(kind: :zone_activity, name: package.name + " - zone activity")
end
rule
end
end
end
end |
Increment version number for CocoaPods | Pod::Spec.new do |s|
s.name = 'GEOSwift'
s.version = '7.2.0'
s.swift_version = '5.1'
s.cocoapods_version = '>= 1.4.0'
s.summary = 'The Swift Geometry Engine.'
s.description = <<~DESC
Easily handle a geometric object model (points, linestrings, polygons etc.) and related
topological operations (intersections, overlapping etc.). A type-safe, MIT-licensed Swift
interface to the OSGeo's GEOS library routines.
DESC
s.homepage = 'https://github.com/GEOSwift/GEOSwift'
s.license = {
type: 'MIT',
file: 'LICENSE'
}
s.authors = 'Andrea Cremaschi', 'Andrew Hershberger', 'Virgilio Favero Neto'
s.platforms = { ios: "9.0", osx: "10.9", tvos: "9.0" }
s.source = {
git: 'https://github.com/GEOSwift/GEOSwift.git',
tag: s.version
}
s.source_files = 'GEOSwift/**/*.{swift,h}'
s.dependency 'geos', '~> 6.0'
end
| Pod::Spec.new do |s|
s.name = 'GEOSwift'
s.version = '8.0.0'
s.swift_version = '5.1'
s.cocoapods_version = '>= 1.4.0'
s.summary = 'The Swift Geometry Engine.'
s.description = <<~DESC
Easily handle a geometric object model (points, linestrings, polygons etc.) and related
topological operations (intersections, overlapping etc.). A type-safe, MIT-licensed Swift
interface to the OSGeo's GEOS library routines.
DESC
s.homepage = 'https://github.com/GEOSwift/GEOSwift'
s.license = {
type: 'MIT',
file: 'LICENSE'
}
s.authors = 'Andrea Cremaschi', 'Andrew Hershberger', 'Virgilio Favero Neto'
s.platforms = { ios: "9.0", osx: "10.9", tvos: "9.0" }
s.source = {
git: 'https://github.com/GEOSwift/GEOSwift.git',
tag: s.version
}
s.source_files = 'GEOSwift/**/*.{swift,h}'
s.dependency 'geos', '~> 6.0'
end
|
Fix for reddit's split listings on links. | require 'hashie'
module Reddit
module Base
# Client that does everything BasicClient does but also attempts to
# coerce and parse JSON.
class Client < BasicClient
def initialize(options)
super(options)
connection.builder.insert_before FaradayMiddleware::FollowRedirects, FaradayMiddleware::ParseJson
connection.builder.insert_before FaradayMiddleware::Reddit::Modhash, Faraday::ManualCache, expires_in: 30
connection.builder.insert_before Faraday::ManualCache, FaradayMiddleware::Reddit::ForceJson
end
def delete(url, **options)
nocache = options.delete(:nocache)
response = connection.delete(url, **options)
Mash.new response.body
end
def get(url, **options)
nocache = options.delete(:nocache)
response = connection.get do |req|
req.url url
req.headers['x-faraday-manual-cache'] = 'NOCACHE' if nocache
req.params = options
end
Mash.new response.body
end
def post(url, **options)
nocache = options.delete(:nocache)
response = connection.post(url, **options)
Mash.new response.body
end
def put(url, **options)
nocache = options.delete(:nocache)
response = connection.put(url, **options)
Mash.new response.body
end
end
end
end
| require 'hashie'
module Reddit
module Base
# Client that does everything BasicClient does but also attempts to
# coerce and parse JSON.
class Client < BasicClient
def initialize(options)
super(options)
connection.builder.insert_before FaradayMiddleware::FollowRedirects, FaradayMiddleware::ParseJson
connection.builder.insert_before FaradayMiddleware::Reddit::Modhash, Faraday::ManualCache, expires_in: 30
connection.builder.insert_before Faraday::ManualCache, FaradayMiddleware::Reddit::ForceJson
end
def delete(url, **options)
nocache = options.delete(:nocache)
response = connection.delete(url, **options)
mash response
end
def get(url, **options)
nocache = options.delete(:nocache)
response = connection.get do |req|
req.url url
req.headers['x-faraday-manual-cache'] = 'NOCACHE' if nocache
req.params = options
end
mash response
end
def post(url, **options)
nocache = options.delete(:nocache)
response = connection.post(url, **options)
mash response
end
def put(url, **options)
nocache = options.delete(:nocache)
response = connection.put(url, **options)
mash response
end
def mash(response)
if response.body.is_a? Array
response.body.map { |x| Mash.new x }
else
Mash.new response.body
end
end
end
end
end
|
Test for icinga::pager_contact api key | require_relative '../../../../spec_helper'
describe 'icinga::pager_contact', :type => :define do
let(:title) { 'pager_nonworkhours' }
it { should contain_file('/etc/icinga/conf.d/contact_pager_nonworkhours.cfg').
with_content(/command_name\s+notify-host-by-pagerduty/).
with_content(/command_line\s+\/usr\/local\/bin\/pagerduty_nagios.pl\senqueue\s-f\spd_nagios_object=host/).
with_content(/command_name\s+notify-service-by-pagerduty/).
with_content(/command_line\s+\/usr\/local\/bin\/pagerduty_nagios.pl\senqueue\s-f\spd_nagios_object=service/).
with_content(/service_notification_period\s+24x7/)
}
end
| require_relative '../../../../spec_helper'
describe 'icinga::pager_contact', :type => :define do
let(:title) { 'pager_nonworkhours' }
let(:params) {{
:pagerduty_apikey => '1234554321',
}}
it { should contain_file('/etc/icinga/conf.d/contact_pager_nonworkhours.cfg').
with_content(/command_name\s+notify-host-by-pagerduty/).
with_content(/command_line\s+\/usr\/local\/bin\/pagerduty_nagios.pl\senqueue\s-f\spd_nagios_object=host/).
with_content(/command_name\s+notify-service-by-pagerduty/).
with_content(/command_line\s+\/usr\/local\/bin\/pagerduty_nagios.pl\senqueue\s-f\spd_nagios_object=service/).
with_content(/service_notification_period\s+24x7/).
with_content(/pager\s+1234554321/)
}
end
|
Update gemspec with RuboCop recommendations | # frozen_string_literal: true
require_relative 'lib/svgeez/version'
Gem::Specification.new do |spec|
spec.required_ruby_version = '>= 2.5', '< 4'
spec.name = 'svgeez'
spec.version = Svgeez::VERSION
spec.authors = ['Jason Garber']
spec.email = ['jason@sixtwothree.org']
spec.summary = 'Automatically generate an SVG sprite from a folder of SVG icons.'
spec.description = spec.summary
spec.homepage = 'https://github.com/jgarber623/svgeez'
spec.license = 'MIT'
spec.files = Dir.chdir(File.expand_path(__dir__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(bin|spec)/}) }
end
spec.bindir = 'exe'
spec.executables = ['svgeez']
spec.require_paths = ['lib']
spec.metadata['bug_tracker_uri'] = "#{spec.homepage}/issues"
spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/v#{spec.version}/CHANGELOG.md"
spec.add_runtime_dependency 'listen', '~> 3.5'
spec.add_runtime_dependency 'mercenary', '~> 0.4.0'
end
| # frozen_string_literal: true
require_relative 'lib/svgeez/version'
Gem::Specification.new do |spec|
spec.required_ruby_version = '>= 2.5', '< 4'
spec.name = 'svgeez'
spec.version = Svgeez::VERSION
spec.authors = ['Jason Garber']
spec.email = ['jason@sixtwothree.org']
spec.summary = 'Automatically generate an SVG sprite from a folder of SVG icons.'
spec.description = spec.summary
spec.homepage = 'https://github.com/jgarber623/svgeez'
spec.license = 'MIT'
spec.files = Dir['exe/**/*', 'lib/**/*'].reject { |f| File.directory?(f) }
spec.files += %w[LICENSE CHANGELOG.md CODE_OF_CONDUCT.md CONTRIBUTING.md README.md]
spec.files += %w[svgeez.gemspec]
spec.bindir = 'exe'
spec.executables = ['svgeez']
spec.require_paths = ['lib']
spec.metadata = {
'bug_tracker_uri' => "#{spec.homepage}/issues",
'changelog_uri' => "#{spec.homepage}/blob/v#{spec.version}/CHANGELOG.md",
'rubygems_mfa_required' => 'true'
}
spec.add_runtime_dependency 'listen', '~> 3.5'
spec.add_runtime_dependency 'mercenary', '~> 0.4.0'
end
|
Add rspec as a development dependency. | # encoding: utf-8
$:.unshift File.expand_path('../lib', __FILE__)
require 'covenant/version'
Gem::Specification.new do |s|
s.name = "covenant"
s.version = Covenant::VERSION
s.authors = ["David Leal"]
s.email = ["gems@mojotech.com"]
s.homepage = "https://github.com/mojotech/covenant"
s.summary = "Assertion library for Ruby"
s.files = `git ls-files app lib`.split("\n")
s.platform = Gem::Platform::RUBY
s.require_paths = ['lib']
s.rubyforge_project = '[none]'
end
| # encoding: utf-8
$:.unshift File.expand_path('../lib', __FILE__)
require 'covenant/version'
Gem::Specification.new do |s|
s.name = "covenant"
s.version = Covenant::VERSION
s.authors = ["David Leal"]
s.email = ["gems@mojotech.com"]
s.homepage = "https://github.com/mojotech/covenant"
s.summary = "Assertion library for Ruby"
s.files = `git ls-files app lib`.split("\n")
s.platform = Gem::Platform::RUBY
s.require_paths = ['lib']
s.rubyforge_project = '[none]'
s.add_development_dependency 'rspec', '>= 2.11'
end
|
Allow all core to edit abuse reports - 2 | # frozen_string_literal: true
class AbuseReportStatusesController < ApplicationController
before_action :verify_core, except: [:index, :show]
before_action :set_status, except: [:index, :create]
before_action :verify_admin, only: [:edit, :update, :destroy]
def index
@statuses = AbuseReportStatus.all
end
def create
@status = AbuseReportStatus.new status_params
if @status.save
flash[:success] = 'Created status.'
redirect_back fallback_location: abuse_status_path(@status)
else
flash[:danger] = 'Failed to create status.'
redirect_to abuse_statuses_path
end
end
def show
@reports = @status.reports.includes(:contact, :status, :user)
end
def edit; end
def update
if @status.update status_params
flash[:success] = 'Updated status.'
redirect_to abuse_status_path(@status)
else
flash[:danger] = 'Failed to update.'
render :edit
end
end
def destroy
if @status.destroy
flash[:success] = 'Removed status.'
redirect_to abuse_statuses_path
else
flash[:danger] = 'Failed to remove.'
redirect_to abuse_status_path(@status)
end
end
private
def set_status
@status = AbuseReportStatus.find params[:id]
end
def status_params
params.require(:abuse_report_status).permit(:name, :details, :icon, :color)
end
end
| # frozen_string_literal: true
class AbuseReportStatusesController < ApplicationController
before_action :verify_core, except: [:index, :show]
before_action :set_status, except: [:index, :create]
before_action :verify_admin, only: destroy
def index
@statuses = AbuseReportStatus.all
end
def create
@status = AbuseReportStatus.new status_params
if @status.save
flash[:success] = 'Created status.'
redirect_back fallback_location: abuse_status_path(@status)
else
flash[:danger] = 'Failed to create status.'
redirect_to abuse_statuses_path
end
end
def show
@reports = @status.reports.includes(:contact, :status, :user)
end
def edit; end
def update
if @status.update status_params
flash[:success] = 'Updated status.'
redirect_to abuse_status_path(@status)
else
flash[:danger] = 'Failed to update.'
render :edit
end
end
def destroy
if @status.destroy
flash[:success] = 'Removed status.'
redirect_to abuse_statuses_path
else
flash[:danger] = 'Failed to remove.'
redirect_to abuse_status_path(@status)
end
end
private
def set_status
@status = AbuseReportStatus.find params[:id]
end
def status_params
params.require(:abuse_report_status).permit(:name, :details, :icon, :color)
end
end
|
Reduce n+1 queries in performance scheduler | # -*- encoding : utf-8 -*-
class Jmd::VenuesController < Jmd::BaseController
load_and_authorize_resource :contest
load_and_authorize_resource :venue
def schedule
# @contest is fetched by CanCan
# @venue is fetched by CanCan
@contest_categories = @contest.contest_categories.includes(:category)
@performances = @contest.performances
.includes(:predecessor, :participants, { contest_category: :category })
.venueless_or_at_stage_venue(@venue.id)
.browsing_order
end
end
| # -*- encoding : utf-8 -*-
class Jmd::VenuesController < Jmd::BaseController
load_and_authorize_resource :contest
load_and_authorize_resource :venue
def schedule
# @contest is fetched by CanCan
# @venue is fetched by CanCan
@contest_categories = @contest.contest_categories.includes(:category)
@performances = @contest.performances
.includes(:predecessor, :participants, :pieces, { contest_category: :category })
.venueless_or_at_stage_venue(@venue.id)
.browsing_order
end
end
|
Load in the engines that we're using dynamically rather than writing out each one. | require 'refinery'
require 'core/lib/core'
require 'dashboard/lib/dashboard'
require 'images/lib/images'
require 'pages/lib/pages'
require 'resources/lib/resources'
require 'settings/lib/settings'
require 'authentication/lib/authentication'
| require 'refinery'
# Load all dependencies generically using the same name as the folder they're in.
# This is the naming convention we'll have to stick to and it also happens
# to be the standard naming convention.
Dir[File.expand_path("../**", __FILE__).to_s].each do |dir|
if (dir = Pathname.new(dir)).directory?
if (require_file = dir.join('lib', "#{dir.split.last}.rb")).file?
require require_file
end
end
end
|
Fix homepage to use SSL in Zotero Cask | cask :v1 => 'zotero' do
version '4.0.26.2'
sha256 '7aeaf0997e27b23c7af2217275f80487e07d2988e814a9c35401e493b25cff14'
url "https://download.zotero.org/standalone/#{version}/Zotero-#{version}.dmg"
name 'Zotero'
homepage 'http://www.zotero.org/'
license :affero
app 'Zotero.app'
end
| cask :v1 => 'zotero' do
version '4.0.26.2'
sha256 '7aeaf0997e27b23c7af2217275f80487e07d2988e814a9c35401e493b25cff14'
url "https://download.zotero.org/standalone/#{version}/Zotero-#{version}.dmg"
name 'Zotero'
homepage 'https://www.zotero.org/'
license :affero
app 'Zotero.app'
end
|
Load 5.2 defaults in ASt dummy app | # frozen_string_literal: true
require_relative "boot"
require "rails"
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_view/railtie"
require "sprockets/railtie"
require "active_storage/engine"
#require "action_mailer/railtie"
#require "rails/test_unit/railtie"
#require "action_cable/engine"
Bundler.require(*Rails.groups)
module Dummy
class Application < Rails::Application
config.load_defaults 5.1
config.active_storage.service = :local
end
end
| # frozen_string_literal: true
require_relative "boot"
require "rails"
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_view/railtie"
require "sprockets/railtie"
require "active_storage/engine"
#require "action_mailer/railtie"
#require "rails/test_unit/railtie"
#require "action_cable/engine"
Bundler.require(*Rails.groups)
module Dummy
class Application < Rails::Application
config.load_defaults 5.2
config.active_storage.service = :local
end
end
|
Fix naming issue in podspec | Pod::Spec.new do |s|
s.name = "color"
s.version = "0.0.2"
s.summary = "A collection of categories and utilities that extend UIColor."
s.homepage = "https://github.com/thisandagain/color"
s.license = 'MIT'
s.author = { "Andrew Sliwinski" => "andrewsliwinski@acm.org" }
s.source = { :git => "https://github.com/thisandagain/color.git", :tag => "v0.0.2" }
s.platform = :ios, '5.0'
s.source_files = 'EDColor'
s.frameworks = 'UIKit', 'SenTestingKit'
s.requires_arc = true
end
| Pod::Spec.new do |s|
s.name = "EDColor"
s.version = "0.0.2"
s.summary = "A collection of categories and utilities that extend UIColor."
s.homepage = "https://github.com/thisandagain/color"
s.license = 'MIT'
s.author = { "Andrew Sliwinski" => "andrewsliwinski@acm.org" }
s.source = { :git => "https://github.com/thisandagain/color.git", :tag => "v0.0.2" }
s.platform = :ios, '5.0'
s.source_files = 'EDColor'
s.frameworks = 'UIKit', 'SenTestingKit'
s.requires_arc = true
end
|
Check for the existence of the id before calling Model::[]. | module Shield
module Helpers
def ensure_authenticated(model)
return if authenticated(model)
session[:return_to] = request.fullpath
redirect_to_login
end
def authenticated(model)
@_authenticated ||= {}
@_authenticated[model] ||= model[session[model.to_s]]
end
def redirect_to_login
redirect "/login"
end
def redirect_to_stored(default = "/")
redirect(session.delete(:return_to) || default)
end
def login(model, username, password)
instance = model.authenticate(username, password)
if instance
session[model.to_s] = instance.id
return true
else
return false
end
end
def logout(model)
session.delete(model.to_s)
session.delete(:return_to)
@_authenticated.delete(model) if defined?(@_authenticated)
end
end
end | module Shield
module Helpers
def ensure_authenticated(model)
return if authenticated(model)
session[:return_to] = request.fullpath
redirect_to_login
end
def authenticated(model)
@_authenticated ||= {}
@_authenticated[model] ||= session[model.to_s] && model[session[model.to_s]]
end
def redirect_to_login
redirect "/login"
end
def redirect_to_stored(default = "/")
redirect(session.delete(:return_to) || default)
end
def login(model, username, password)
instance = model.authenticate(username, password)
if instance
session[model.to_s] = instance.id
return true
else
return false
end
end
def logout(model)
session.delete(model.to_s)
session.delete(:return_to)
@_authenticated.delete(model) if defined?(@_authenticated)
end
end
end |
Fix bug with TestRunner tests() | module GUnit
# How many tests have run
# How many passing test responses
# How many failing test responses
# How many exception test responses
# A TestRunner object discovers TestCase classes
# The TestRunner object calls suite() on all TestCase classes
# Each TestCase class returns a TestSuite object with instances of itself (TestCases) each with a method to be executed
# The TestRunner object calls run() on all TestSuite objects, collecting TestResponses
# Each TestSuite object calls run() on all of its TestCase objects, yielding TestResponses
# Each TestCase object executes its method, returning a TestResponse
# The TestRunner displays the TestResponses as they are yielded
# After all tests have run, the TestRunner displays a summery of results
class TestRunner
# TestSuites and/or TestCases
attr_writer :tests
attr_reader :responses
def initialize(*args)
@responses = []
end
def tests
@tests || []
end
def run
self.tests.each do |test|
case
when test.is_a?(TestSuite)
test.run{|response| @responses << response }
when test.is_a?(TestCase)
@responses << test.run
end
end
end
end
end | module GUnit
# How many tests have run
# How many passing test responses
# How many failing test responses
# How many exception test responses
# A TestRunner object discovers TestCase classes
# The TestRunner object calls suite() on all TestCase classes
# Each TestCase class returns a TestSuite object with instances of itself (TestCases) each with a method to be executed
# The TestRunner object calls run() on all TestSuite objects, collecting TestResponses
# Each TestSuite object calls run() on all of its TestCase objects, yielding TestResponses
# Each TestCase object executes its method, returning a TestResponse
# The TestRunner displays the TestResponses as they are yielded
# After all tests have run, the TestRunner displays a summery of results
class TestRunner
# TestSuites and/or TestCases
attr_writer :tests
attr_reader :responses
def initialize(*args)
@responses = []
end
def tests
@tests ||= []
end
def run
self.tests.each do |test|
case
when test.is_a?(TestSuite)
test.run{|response| @responses << response }
when test.is_a?(TestCase)
@responses << test.run
end
end
end
end
end |
Create default values for some databases. | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
| # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
rail_lines = %w[ brown purple yellow red blue orange green ]
rail_lines.each { |line| Line.find_or_create_by(line_name: line) }
Map.create(name: '2015 CTA Rail Map', author: 'system')
|
Include stdout/stderr when there's an error generating keys | require 'tmpdir'
require 'fileutils'
require 'open3'
module Hooks
def self.global_setup
print 'Setting up environment... '
ENV.delete 'GPG_AGENT_INFO'
@home = Dir.mktmpdir
ENV['HOME'] = @home
param_file = File.join(File.dirname(__FILE__), 'gpg-params.txt')
cmd = "gpg --debug-quick-random --batch --gen-key #{param_file}"
Open3.popen3 cmd do |stdin, stdout, stderr, wait_thr|
raise "Failed to generate GPG keys" unless wait_thr.value.success?
end
puts 'done.'
end
def self.global_teardown
recursive_delete(@home)
end
def self.teardown
['.config', '.local'].each do |dir|
recursive_delete(@home, dir)
end
end
def self.recursive_delete(*components)
dir = File.join(*components)
FileUtils.rm_r dir if File.directory? dir
end
end
| require 'tmpdir'
require 'fileutils'
require 'open3'
module Hooks
def self.global_setup
print 'Setting up environment... '
ENV.delete 'GPG_AGENT_INFO'
@home = Dir.mktmpdir
ENV['HOME'] = @home
param_file = File.join(File.dirname(__FILE__), 'gpg-params.txt')
cmd = "gpg --debug-quick-random --batch --gen-key #{param_file}"
Open3.popen3 cmd do |stdin, stdout, stderr, wait_thr|
raise "Failed to generate GPG keys:\n#{stdout}\n#{stderr}" unless wait_thr.value.success?
end
puts 'done.'
end
def self.global_teardown
recursive_delete(@home)
end
def self.teardown
['.config', '.local'].each do |dir|
recursive_delete(@home, dir)
end
end
def self.recursive_delete(*components)
dir = File.join(*components)
FileUtils.rm_r dir if File.directory? dir
end
end
|
Use the json_response format when returning the index of orgs. | class Api::V1::OrganizationsController < Api::ApiController
# Given organization_id, look up org profile
# GET /organizations/{id}
def show
get_organization(params[:id])
unless @organization
@status = :fail
@data = {id: "Organization #{params[:id]} not found."}
render status: :not_found, json: json_response(:fail, data: @data)
end
end
def index
orgs = current_user.viewable_organizations.map{ |o| {id: o.id, name: o.name}}
render status: 200, json: orgs
end
private
def get_organization(org_id)
org_id = org_id.to_i unless org_id.blank?
if @user.viewable_organization_ids.include?(org_id)
@organization = Organization.find_by_id(org_id)
end
end
end
| class Api::V1::OrganizationsController < Api::ApiController
# Given organization_id, look up org profile
# GET /organizations/{id}
def show
get_organization(params[:id])
unless @organization
@status = :fail
@data = {id: "Organization #{params[:id]} not found."}
render status: :not_found, json: json_response(:fail, data: @data)
end
end
def index
orgs = current_user.viewable_organizations.map{ |o| {id: o.id, name: o.name}}
render status: 200, json: json_response(:success, data: orgs)
end
private
def get_organization(org_id)
org_id = org_id.to_i unless org_id.blank?
if @user.viewable_organization_ids.include?(org_id)
@organization = Organization.find_by_id(org_id)
end
end
end
|
Use Date class to set correct publish date | # frozen_string_literal: true
require_relative 'lib/chainer/version'
Gem::Specification.new do |s|
s.name = 'chainer'
s.version = ::Chainer::VERSION
s.date = '2017-03-01'
s.summary = 'Allows to pipe Ruby calls in a nice way'
s.description = 'Allows to pipe Ruby calls in a nice way'
s.authors = ['Viktor Lazarev']
s.email = 'taurus101v@gmail.com'
s.files = `git ls-files lib`.split("\n")
s.homepage = 'https://github.com/gentoid/chainer'
s.license = 'MIT'
s.add_development_dependency 'rubocop', '~> 0.47'
s.add_development_dependency 'rubocop-rspec', '~> 1.12'
s.add_development_dependency 'rspec', '~> 3.5'
s.add_development_dependency 'yard', '~> 0.9.8'
end
| # frozen_string_literal: true
require_relative 'lib/chainer/version'
require 'date'
Gem::Specification.new do |s|
s.name = 'chainer'
s.version = ::Chainer::VERSION
s.date = Date.today.to_s
s.summary = 'Allows to pipe Ruby calls in a nice way'
s.description = 'Allows to pipe Ruby calls in a nice way'
s.authors = ['Viktor Lazarev']
s.email = 'taurus101v@gmail.com'
s.files = `git ls-files lib`.split("\n")
s.homepage = 'https://github.com/gentoid/chainer'
s.license = 'MIT'
s.add_development_dependency 'rubocop', '~> 0.47'
s.add_development_dependency 'rubocop-rspec', '~> 1.12'
s.add_development_dependency 'rspec', '~> 3.5'
s.add_development_dependency 'yard', '~> 0.9.8'
end
|
Refactor SingleByteXorCracker method parameter names to reflect contract | require 'matasano_crypto_challenges/representations/hexadecimal'
module MatasanoCryptoChallenges
class SingleByteXorCracker
attr_reader :normally_frequent_bytes
def initialize(normally_frequent_bytes=' etaoinshrdlu'.bytes)
@normally_frequent_bytes = Array(normally_frequent_bytes)
end
def crack(hexadecimal)
best = Representations::Hexadecimal.from_bytes([])
1.upto 255 do |key_seed|
key = Representations::Hexadecimal.from_bytes([key_seed] *
hexadecimal.bytes.length)
guess = (hexadecimal ^ key)
if best.normalcy_score < (guess.normalcy_score = normalcy_score(guess))
best = guess
end
end
best
end
private
def frequent_bytes(hexadecimal)
table = {}
hexadecimal.bytes.each do |b|
table[b] = table[b].to_i + 1
end
table.to_a.
sort { |left, right| left.last <=> right.last }.
reverse.
collect(&:first).
slice 0, normally_frequent_bytes.length
end
def normalcy_score(hexadecimal)
normally_frequent_bytes.length -
(frequent_bytes(hexadecimal) - normally_frequent_bytes).length
end
end
end
| require 'matasano_crypto_challenges/representations/hexadecimal'
module MatasanoCryptoChallenges
class SingleByteXorCracker
attr_reader :normally_frequent_bytes
def initialize(normally_frequent_bytes=' etaoinshrdlu'.bytes)
@normally_frequent_bytes = Array(normally_frequent_bytes)
end
def crack(representation)
best = Representations::Hexadecimal.from_bytes([])
1.upto 255 do |key_seed|
key = Representations::Hexadecimal.from_bytes([key_seed] *
representation.bytes.length)
guess = (representation ^ key)
if best.normalcy_score < (guess.normalcy_score = normalcy_score(guess))
best = guess
end
end
best
end
private
def frequent_bytes(representation)
table = {}
representation.bytes.each do |b|
table[b] = table[b].to_i + 1
end
table.to_a.
sort { |left, right| left.last <=> right.last }.
reverse.
collect(&:first).
slice 0, normally_frequent_bytes.length
end
def normalcy_score(representation)
normally_frequent_bytes.length -
(frequent_bytes(representation) - normally_frequent_bytes).length
end
end
end
|
Order newest stuff first in user backend. | class UsersController < ApplicationController
before_filter :require_no_user, :only => [:new, :create]
before_filter :require_user, :only => [:show, :edit, :update]
def show
@user = @current_user
@invoices = @user.invoices.unpaid
@orders_to_ship = @user.orders.to_ship
@orders_awaiting_payment = @user.orders.awaiting_payment
@orders_processing = @user.orders.processing
@orders_unprocessed = @user.orders.unprocessed
@last_shipped_orders = @user.orders.shipped.limit(5)
@addresses = @user.addresses.active
@notifications = @user.notifications
# To return after switching off notifications for a product
session[:return_to] = user_path(@user)
end
def me
show
render :action => 'show'
end
end
| class UsersController < ApplicationController
before_filter :require_no_user, :only => [:new, :create]
before_filter :require_user, :only => [:show, :edit, :update]
def show
@user = @current_user
@invoices = @user.invoices.unpaid.order("created_at DESC")
@orders_to_ship = @user.orders.to_ship.order("created_at DESC")
@orders_awaiting_payment = @user.orders.awaiting_payment.order("created_at DESC")
@orders_processing = @user.orders.processing.order("created_at DESC")
@orders_unprocessed = @user.orders.unprocessed.order("created_at DESC")
@last_shipped_orders = @user.orders.shipped.order("created_at DESC").limit(5)
@addresses = @user.addresses.active
@notifications = @user.notifications
# To return after switching off notifications for a product
session[:return_to] = user_path(@user)
end
def me
show
render :action => 'show'
end
end
|
Add addressable as explicit dependency | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/healthy/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = "healthy"
gem.version = Healthy::VERSION
gem.summary = %q{Arranges communication between Mirth and RoQua}
gem.description = %q{Receives queries from RoQua, sends them to Mirth, and translates Mirth's responses back into Rubyland.}
gem.license = "MIT"
gem.authors = ["Marten Veldthuis"]
gem.email = "marten@roqua.nl"
gem.homepage = "https://github.com/roqua/healthy"
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ['lib']
gem.add_dependency 'activesupport', '~> 3.2'
gem.add_development_dependency 'bundler', '~> 1.0'
gem.add_development_dependency 'rake', '~> 0.8'
gem.add_development_dependency 'rspec', '~> 2.4'
gem.add_development_dependency 'yard', '~> 0.8'
gem.add_development_dependency 'webmock', '~> 1.13'
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/healthy/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = "healthy"
gem.version = Healthy::VERSION
gem.summary = %q{Arranges communication between Mirth and RoQua}
gem.description = %q{Receives queries from RoQua, sends them to Mirth, and translates Mirth's responses back into Rubyland.}
gem.license = "MIT"
gem.authors = ["Marten Veldthuis"]
gem.email = "marten@roqua.nl"
gem.homepage = "https://github.com/roqua/healthy"
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ['lib']
gem.add_dependency 'activesupport', '~> 3.2'
gem.add_dependency 'addressable', '~> 2.3'
gem.add_development_dependency 'bundler', '~> 1.0'
gem.add_development_dependency 'rake', '~> 0.8'
gem.add_development_dependency 'rspec', '~> 2.4'
gem.add_development_dependency 'yard', '~> 0.8'
gem.add_development_dependency 'webmock', '~> 1.13'
end
|
Update test to account for longer allowed location on an intitiative. | require 'test_helper'
class InitiativeTest < ActiveSupport::TestCase
def setup
@area = Area.create(name: "Example Area", description: "Example description")
@initiative = Initiative.new(name: "Example Initiative",
description: "Example description.", area_id: @area.id, location: "TestTest")
end
test "should be valid" do
assert @initiative.valid?
end
test "name should be present" do
@initiative.name = ""
assert_not @initiative.valid?
end
test "description should be present" do
@initiative.description = ""
assert_not @initiative.valid?
end
test "location should be present" do
@initiative.location = ""
assert_not @initiative.valid?
end
test "area_id should be present" do
@initiative.area_id = nil
assert_not @initiative.valid?
end
test "location should not be too long" do
@initiative.location = "a" * 51
assert_not @initiative.valid?
end
test "name should not be too long" do
@initiative.name = "a" * 51
assert_not @initiative.valid?
end
test "description should not be too long" do
@initiative.description = "a" * 256
assert_not @initiative.valid?
end
end
| require 'test_helper'
class InitiativeTest < ActiveSupport::TestCase
def setup
@area = Area.create(name: "Example Area", description: "Example description")
@initiative = Initiative.new(name: "Example Initiative",
description: "Example description.", area_id: @area.id, location: "TestTest")
end
test "should be valid" do
assert @initiative.valid?
end
test "name should be present" do
@initiative.name = ""
assert_not @initiative.valid?
end
test "description should be present" do
@initiative.description = ""
assert_not @initiative.valid?
end
test "location should be present" do
@initiative.location = ""
assert_not @initiative.valid?
end
test "area_id should be present" do
@initiative.area_id = nil
assert_not @initiative.valid?
end
test "location should not be too long" do
@initiative.location = "a" * 256
assert_not @initiative.valid?
end
test "name should not be too long" do
@initiative.name = "a" * 51
assert_not @initiative.valid?
end
test "description should not be too long" do
@initiative.description = "a" * 256
assert_not @initiative.valid?
end
end
|
Check for invalid table x and y | # Robot class
class Robot
# The x position on the table
attr_accessor:x
# The y position on the table
attr_accessor:y
# The direction the robot is facing
attr_accessor:face
# Initialize the robot with x and y position and direction facing.
def initialize(x, y, face)
@x = x
@y = y
@face = face
end
end | # Robot class
class Robot
# The x position on the table
attr_accessor:x
# The y position on the table
attr_accessor:y
# The direction the robot is facing
attr_accessor:face
# Initialize the robot with x and y position and direction the robos is facing.
# = Parameters
# - +x+:: the x position on the table
# - +y+:: the y position on the table
# - +face+:: the direction the robot is facing
def initialize(x, y, face)
raise ArgumentError, 'Robot x position is invalid.' unless x.is_a?(Numeric)
raise ArgumentError, 'Robot y position is invalid.' unless y.is_a?(Numeric)
@x = x
@y = y
@face = face
end
end |
Add dependency on activerecord-tableless 1.1.3, fixes issues with testing outside Rails. | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/savant/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Joe Lind", "Thomas Mayfield"]
gem.email = ["info@terriblelabs.com"]
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 = "savant"
gem.require_paths = ["lib"]
gem.version = Savant::VERSION
gem.add_dependency 'rails'
gem.add_dependency 'activerecord-tableless'
gem.add_dependency 'squeel'
gem.add_development_dependency 'rspec'
gem.add_development_dependency 'sqlite3'
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/savant/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Joe Lind", "Thomas Mayfield"]
gem.email = ["info@terriblelabs.com"]
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 = "savant"
gem.require_paths = ["lib"]
gem.version = Savant::VERSION
gem.add_dependency 'rails'
gem.add_dependency 'activerecord-tableless', '>= 1.1.3'
gem.add_dependency 'squeel'
gem.add_development_dependency 'rspec'
gem.add_development_dependency 'sqlite3'
end
|
Fix upload factory so we don't get same UUID for every test | FactoryGirl.define do
factory :upload, class: "S3Relay::Upload" do
uuid SecureRandom.uuid
filename "cat.png"
content_type "image/png"
upload_type "FileUpload"
end
factory :icon_upload, parent: :upload do
upload_type "IconUpload"
end
factory :photo_upload, parent: :upload do
upload_type "PhotoUpload"
end
end
| FactoryGirl.define do
factory :upload, class: "S3Relay::Upload" do
uuid { SecureRandom.uuid }
end
factory :file_upload, parent: :upload do
filename "cat.png"
content_type "image/png"
upload_type "FileUpload"
end
factory :icon_upload, parent: :upload do
filename "cat.png"
content_type "image/png"
upload_type "IconUpload"
end
factory :photo_upload, parent: :upload do
filename "cat.png"
content_type "image/png"
upload_type "PhotoUpload"
end
end
|
Allow non-mandatory fields to be nil | require 'skr/db/migration_helpers'
class CreateCustomerProject < ActiveRecord::Migration
def change
create_skr_table :customer_projects do |t|
t.skr_code_identifier
t.text :description, :po_num, null: false
t.skr_reference :sku, single: true
t.skr_reference :customer, single: true
t.jsonb :rates
t.timestamps null: false
end
end
end
| require 'skr/db/migration_helpers'
class CreateCustomerProject < ActiveRecord::Migration
def change
create_skr_table :customer_projects do |t|
t.skr_code_identifier
t.text :description, :po_num
t.skr_reference :sku, single: true
t.skr_reference :customer, single: true
t.jsonb :rates
t.timestamps null: false
end
end
end
|
Revert "pin rake < 11 as last_comment is removed" | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "gitable"
s.version = "0.3.1"
s.authors = ["Martin Emde"]
s.email = ["martin.emde@gmail.com"]
s.homepage = "http://github.org/martinemde/gitable"
s.summary = %q{Addressable::URI with additional support for Git "URIs"}
s.description = %q{Addressable::URI for Git "URIs" with special handling for scp-style remotes that Addressable intentionally doesn't parse.}
s.license = 'MIT'
s.add_dependency "addressable", ">= 2.2.7"
s.add_development_dependency "rspec", "~>2.11"
s.add_development_dependency "rake", "< 11"
s.add_development_dependency "simplecov"
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.extra_rdoc_files = ["LICENSE", "README.md"]
end
| # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "gitable"
s.version = "0.3.1"
s.authors = ["Martin Emde"]
s.email = ["martin.emde@gmail.com"]
s.homepage = "http://github.org/martinemde/gitable"
s.summary = %q{Addressable::URI with additional support for Git "URIs"}
s.description = %q{Addressable::URI for Git "URIs" with special handling for scp-style remotes that Addressable intentionally doesn't parse.}
s.license = 'MIT'
s.add_dependency "addressable", ">= 2.2.7"
s.add_development_dependency "rspec", "~>2.11"
s.add_development_dependency "rake"
s.add_development_dependency "simplecov"
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.extra_rdoc_files = ["LICENSE", "README.md"]
end
|
Fix assignment condition for jruby. | module NoaaWeatherClient
module Responses
module ValidatableXmlResponse
SCHEMA_PATH = File.expand_path("../../../../data/xml", __FILE__)
class InvalidXmlError < ArgumentError; end
def validate!(doc, schema_name)
# chdir to help Nokogiri load included schemas
Dir.chdir(SCHEMA_PATH) do
schema_file = File.join(SCHEMA_PATH, "#{schema_name}.xsd")
schema = Nokogiri::XML::Schema(File.read(schema_file))
unless (errors = schema.validate(doc)).empty?
raise InvalidXmlError, "Invalid xml: #{errors.map(&:message).join("\n")}"
end
end
end
end
end
end
| module NoaaWeatherClient
module Responses
module ValidatableXmlResponse
SCHEMA_PATH = File.expand_path("../../../../data/xml", __FILE__)
class InvalidXmlError < ArgumentError; end
def validate!(doc, schema_name)
# chdir to help Nokogiri load included schemas
Dir.chdir(SCHEMA_PATH) do
schema_file = File.join(SCHEMA_PATH, "#{schema_name}.xsd")
schema = Nokogiri::XML::Schema(File.read(schema_file))
errors = schema.validate(doc)
unless errors.empty?
raise InvalidXmlError, "Invalid xml: #{errors.map(&:message).join("\n")}"
end
end
end
end
end
end
|
Update solr 4 test with latest version of solr and jetty. | node.set['solr']['version'] = '4.2.1'
node.set['solr']['checksum'] = '648a4b2509f6bcac83554ca5958cf607474e81f34e6ed3a0bc932ea7fac40b99'
node.set['jetty']['port'] = 8983
node.set['jetty']['version'] = '9.0.3.v20130506'
node.set['jetty']['link'] = 'http://eclipse.org/downloads/download.php?file=/jetty/9.0.3.v20130506/dist/jetty-distribution-9.0.3.v20130506.tar.gz&r=1'
node.set['jetty']['checksum'] = 'eff8c9c63883cae04cec82aca01640411a6f8804971932cd477be2f98f90a6c4'
include_recipe 'hipsnip-solr' | node.set['solr']['version'] = '4.5.1'
node.set['solr']['checksum'] = '8f53f9a317cbb2f0c8304ecf32aa3b8c9a11b5947270ba8d1d6372764d46f781'
node.set['jetty']['port'] = 8983
node.set['jetty']['version'] = '9.0.6.v20130930'
node.set['jetty']['link'] = 'http://eclipse.org/downloads/download.php?file=/jetty/9.0.6.v20130930/dist/jetty-distribution-9.0.6.v20130930.tar.gz&r=1'
node.set['jetty']['checksum'] = 'c35c6c0931299688973e936186a6237b69aee2a7912dfcc2494bde9baeeab58f'
include_recipe 'hipsnip-solr' |
Remove part of the user controller logic | class UsersController < ApplicationController
# User a special layout for the user feed.
layout "user-feed", :only => [:show]
# GET - Show a user.
def show
@user = User.find(params[:id])
end
# GET - Show template to create a user.
def new
@user = User.new
end
# POST - Create a user.
def create
@user = User.new(user_params)
if @user.save
flash[:success] = "Welcome to move #{user_params[:name]}"
redirect_to user_path(@user)
else
flash[:error] = @user.errors.full_messages[0]
render 'new'
end
end
# GET - Show template to edit a user.
def edit
end
# PUT - Update a user.
def update
end
# DELETE - Delete a user.
def delete
end
# GET - Show Login template.
def login
@user = User.new
end
def auth_local
@user = User.find_by_email(params[:user][:email])
if (@user != nil)
if (@user.password == params[:user][:password])
redirect_to user_path(@user)
else
flash[:error] = "Your enter a wrong password."
redirect_to root_path
end
else
flash[:error] = "This user doesn't exists."
redirect_to root_path
end
end
private
def user_params
params.require(:user).permit(:name, :password, :email, :tel, :country, :user_picture)
end
end
| class UsersController < ApplicationController
# User a special layout for the user feed.
layout "user-feed", :only => [:show]
# GET - Show a user.
def show
@user = User.find(current_user)
end
end
|
Make convention available to all classes derived from BaseControllers::VirtualHost | module BaseControllers
# This is an abstract base class for controllers that deal with actions for a particular Convention.
# In theory that should be most things in this app. It defines a couple convenience methods, most
# notably a method called convention, which returns the current Convention object for the domain
# name being requested.
class VirtualHost < ApplicationController
protected
# Returns the appropriate Convention object for the domain name of the request. This relies on
# the Intercode::FindVirtualHost Rack middleware having already run, since it sets the key
# "intercode.convention" inside the Rack environment.
def convention
@convention ||= env["intercode.convention"]
end
# Make the current convention object available to CMS templates, so they can do, for example:
# <h1>Welcome to {{ convention.name }}, {{ user.name }}!</h1>
def liquid_assigns
super.merge("convention" => convention)
end
end
end | module BaseControllers
# This is an abstract base class for controllers that deal with actions for a particular Convention.
# In theory that should be most things in this app. It defines a couple convenience methods, most
# notably a method called convention, which returns the current Convention object for the domain
# name being requested.
class VirtualHost < ApplicationController
protected
# Returns the appropriate Convention object for the domain name of the request. This relies on
# the Intercode::FindVirtualHost Rack middleware having already run, since it sets the key
# "intercode.convention" inside the Rack environment.
def convention
@convention ||= env["intercode.convention"]
end
helper_method :convention
# Make the current convention object available to CMS templates, so they can do, for example:
# <h1>Welcome to {{ convention.name }}, {{ user.name }}!</h1>
def liquid_assigns
super.merge("convention" => convention)
end
end
end
|
Fix dump in new gem toml-rb | property :path, String, name_property: true
property :config, Hash, required: true
default_action :create
load_current_value do
require 'toml-rb'
if ::File.exist?(path)
config ::TomlRB.load_file(path)
else
current_value_does_not_exist!
end
end
action :create do
require 'toml-rb'
converge_if_changed do
::IO.write(path, ::TomlRB::Generator.new(config).body)
end
end
| property :path, String, name_property: true
property :config, Hash, required: true
default_action :create
load_current_value do
require 'toml-rb'
if ::File.exist?(path)
config ::TomlRB.load_file(path)
else
current_value_does_not_exist!
end
end
action :create do
require 'toml-rb'
converge_if_changed do
::IO.write(path, ::TomlRB.dump(config))
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.