Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Refactor arrays with splat (*) | module Lighter
class LampControl
def initialize(opts = {})
# Connect to the server and save the socket
@sock = opts[:socket]
end
def fade(lamps, length, cols)
send(fadeData(lamps,length,cols))
end
def set(lamps, cols)
send(setData(lamps, cols))
end
private
... | module Lighter
class LampControl
def initialize(opts = {})
# Connect to the server and save the socket
@sock = opts[:socket]
end
def fade(lamps, length, cols)
send(fadeData(lamps,length,cols))
end
def set(lamps, cols)
send(setData(lamps, cols))
end
private
... |
Document how we mean to go on | module CineworldUk
VERSION = "0.0.1"
end
| # Ruby interface for http://www.cineworld.co.uk
# @version 0.0.1
module CineworldUk
# Gem version
VERSION = "0.0.1"
end
|
Update site spec with shoulda gem | require 'rails_helper'
RSpec.describe Site, 'site attribut testing' do
it 'cannot save without a name' do
site = build(:site, name: nil)
result = site.save
expect(result).to be false
end
it 'can have many tracks' do
site = build(:site, :has_tracks)
expect(site.tracks.count).to eq(3)
end
en... | require 'rails_helper'
RSpec.describe Site, "validations" do
it { is_expected.to validate_presence_of(:name) }
end
RSpec.describe Site, 'obsolete association testing' do
it 'can have many tracks' do
site = build(:site, :has_tracks)
expect(site.tracks.count).to eq(3)
end
end
|
CHANGE STUFF TO FIND BUG | require "base64"
module Identity
class HerokuAPI < Excon::Connection
def initialize(options={})
headers = {
"Accept" => "application/vnd.heroku+json; version=3"
}.merge(options[:headers] || {})
if options[:user] || options[:pass]
authorization = Base64.urlsafe_encode64(
... | require "base64"
module Identity
class HerokuAPI < Excon::Connection
def initialize(options={})
headers = {
"Accept" => "application/vnd.heroku+json; version=3"
}.merge(options[:headers] || {})
if options[:user] || options[:pass]
authorization = ["#{options[:user] || ''}:#{optio... |
Change repo example in yard docs | require 'yaml'
require 'rom/repository'
require 'rom/yaml/dataset'
module ROM
module YAML
# YAML repository
#
# @example
# repository = ROM::YAML::Repository.new('/path/to/data.yml')
# repository.dataset(:users)
# repository.dataset?(:users) # => true
# repository[:users]
#
... | require 'yaml'
require 'rom/repository'
require 'rom/yaml/dataset'
module ROM
module YAML
# YAML repository
#
# Connects to a yaml file and uses it as a data-source
#
# @example
# ROM.setup(:yaml, '/path/to/data.yml')
#
# rom = ROM.finalize.env
#
# repository = rom.repo... |
Remove the test from the old sync install | control 'chef-server' do
describe package('chef-server-core') do
it { should be_installed }
end
describe package('chef-manage') do
it { should be_installed }
end
describe command('chef-manage-ctl status') do
its(:exit_status) { should eq 0 }
end
describe command('sudo chef-sync-ctl sync-sta... | control 'chef-server' do
describe package('chef-server-core') do
it { should be_installed }
end
describe package('chef-manage') do
it { should be_installed }
end
describe command('chef-manage-ctl status') do
its(:exit_status) { should eq 0 }
end
end
|
Fix mini ports compilation issue | require "rake/clean"
require "rake/extensioncompiler"
require "mini_portile"
$recipes = {}
$recipes[:sqlite3] = MiniPortile.new "sqlite3", BINARY_VERSION
$recipes[:sqlite3].files << "http://sqlite.org/sqlite-autoconf-#{URL_VERSION}.tar.gz"
namespace :ports do
directory "ports"
desc "Install port sqlite3 #{$reci... | require "rake/clean"
require "rake/extensioncompiler"
require "mini_portile"
$recipes = {}
$recipes[:sqlite3] = MiniPortile.new "sqlite3", BINARY_VERSION
$recipes[:sqlite3].files << "http://sqlite.org/sqlite-autoconf-#{URL_VERSION}.tar.gz"
namespace :ports do
directory "ports"
desc "Install port sqlite3 #{$reci... |
Fix unknown action name handling | require "serverkit/actions/apply"
require "serverkit/actions/diff"
require "serverkit/actions/inspect"
require "serverkit/actions/validate"
require "serverkit/errors/missing_action_name_argument_error"
require "serverkit/errors/missing_recipe_path_argument_error"
require "serverkit/errors/unknown_action_name_error"
mo... | require "serverkit/actions/apply"
require "serverkit/actions/diff"
require "serverkit/actions/inspect"
require "serverkit/actions/validate"
require "serverkit/errors/missing_action_name_argument_error"
require "serverkit/errors/missing_recipe_path_argument_error"
require "serverkit/errors/unknown_action_name_error"
mo... |
Add sequel real world discourse bench | require "bundler/setup"
require "sequel"
require_relative "support/benchmark_sequel"
db_setup script: "bm_discourse_setup.rb"
DB = Sequel.connect(ENV.fetch("DATABASE_URL"))
class User < Sequel::Model
one_to_many :topic_users
one_to_many :category_users
one_to_many :topics
end
class Topic < Sequel::Model
on... | |
Update admin_partner_id primary key to bigint | class ChangeAdminPartnerIdToBigint < ActiveRecord::Migration[6.0]
def up
change_column :admin_partners, :id, :bigint
end
def down
change_column :admin_partners, :id, :integer
end
end
| |
Revert "Add bcrypt and bundle" | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'users/version'
Gem::Specification.new do |spec|
spec.name = "users"
spec.version = Users::VERSION
spec.authors = ["Dax"]
spec.email = ["d.dax@email.com"]
sp... | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'users/version'
Gem::Specification.new do |spec|
spec.name = "users"
spec.version = Users::VERSION
spec.authors = ["Dax"]
spec.email = ["d.dax@email.com"]
sp... |
Redefine class in instance matcher spec | RSpec.describe Mutant::Matcher::Methods::Instance, '#each' do
let(:object) { described_class.new(env, Foo) }
let(:env) { Fixtures::TEST_ENV }
subject { object.each { |matcher| yields << matcher } }
let(:yields) { [] }
module Bar
def method_d
end
def method_e
end
end
clas... | RSpec.describe Mutant::Matcher::Methods::Instance, '#each' do
let(:object) { described_class.new(env, class_under_test) }
let(:env) { Fixtures::TEST_ENV }
subject { object.each { |matcher| yields << matcher } }
let(:yields) { [] }
let(:class_under_test) do
parent = Module.new do
def... |
Fix app not found error | class AddTypeToMiniapp < ActiveRecord::Migration
def change
MiniApp.where(:name=>app.name).delete_all
mini_app = MiniappStudy::Question.new(:name=>"study", :order_number=>90)
mini_app.save!
end
end
| class AddTypeToMiniapp < ActiveRecord::Migration
def change
MiniApp.where(:name=>"study").delete_all
mini_app = MiniappStudy::Question.new(:name=>"study", :order_number=>90)
mini_app.save!
end
end
|
Fix doc for jazzy and CocoaPods | Pod::Spec.new do |s|
s.name = "TDRedux.swift"
s.version = "1.4.2"
s.summary = "Yet another Redux written in Swift"
s.description = <<-DESC
TDRedux.swift is a micro framework which helps you build
apps with the Redux architecture.
I wrote it because it is fun and easy to write you... | Pod::Spec.new do |s|
s.name = "TDRedux.swift"
s.version = "1.4.3"
s.summary = "Yet another Redux written in Swift"
s.description = <<-DESC
TDRedux.swift is a micro framework which helps you build
apps with the Redux architecture.
I wrote it because it is fun and easy to write you... |
Fix Ruby 1.8 syntax error. | require 'geocoder/lookups/base'
require 'geocoder/results/ovi'
module Geocoder::Lookup
class Ovi < Base
def name
"Ovi"
end
def required_api_key_parts
[]
end
def query_url(query)
"#{protocol}://lbs.ovi.com/search/6.2/#{if query.reverse_geocode? then 'reverse' end}geocode.json?... | require 'geocoder/lookups/base'
require 'geocoder/results/ovi'
module Geocoder::Lookup
class Ovi < Base
def name
"Ovi"
end
def required_api_key_parts
[]
end
def query_url(query)
"#{protocol}://lbs.ovi.com/search/6.2/#{if query.reverse_geocode? then 'reverse' end}geocode.json?... |
Update activities controller test show | require 'test_helper'
module Backend
class ActivitiesControllerTest < ActionController::TestCase
test_restfully_all_actions family: { mode: :index, name: :mussel_farming, format: :json }
end
end
| require 'test_helper'
module Backend
class ActivitiesControllerTest < ActionController::TestCase
test_restfully_all_actions family: { mode: :index, name: :mussel_farming, format: :json }, except: :show
test 'show action' do
get :show, {:id=>"NaID", :redirect=>root_url, :locale=>@locale}
assert_r... |
Raise custom 422 type error when failed parsing json. | # encoding: utf-8
require 'faraday'
require 'github_api/error'
module Github
class Response::RaiseError < Faraday::Response::Middleware
def on_complete(env)
case env[:status].to_i
when 400
raise Github::BadRequest.new(response_message(env), env[:response_headers])
when 401
rai... | # encoding: utf-8
require 'faraday'
require 'github_api/error'
module Github
class Response::RaiseError < Faraday::Response::Middleware
def on_complete(env)
case env[:status].to_i
when 400
raise Github::BadRequest.new(response_message(env), env[:response_headers])
when 401
rai... |
Enhance AnsibleTower Job to process job options | module MiqAeMethodService
class MiqAeServiceServiceAnsibleTower < MiqAeServiceService
require_relative "mixins/miq_ae_service_service_ansible_tower_mixin"
include MiqAeServiceServiceAnsibleTowerMixin
expose :launch_job
expose :job
end
end
| module MiqAeMethodService
class MiqAeServiceServiceAnsibleTower < MiqAeServiceService
require_relative "mixins/miq_ae_service_service_ansible_tower_mixin"
include MiqAeServiceServiceAnsibleTowerMixin
expose :launch_job
expose :job
expose :job_options
expose :job_options=
end
end
|
Add alias method for `DMM::Result` class | # encoding: utf-8
require 'ruby-dmm/response/item'
module DMM
class Response
attr_reader :request, :result
def initialize(response)
@request = response[:request][:parameters][:parameter].inject({}) {|hash, params| hash.merge(params[:name].to_sym => params[:value]) }
if response[:result][:message... | # encoding: utf-8
require 'ruby-dmm/response/item'
module DMM
class Response
attr_reader :request, :result
def initialize(response)
@request = response[:request][:parameters][:parameter].inject({}) {|hash, params| hash.merge(params[:name].to_sym => params[:value]) }
if response[:result][:message... |
Add an environment task, useful for some reason | # encoding: utf-8
module Specjour
module DbScrub
begin
require 'rake'
extend Rake::DSL if defined?(Rake::DSL)
if defined?(Rails) && Rails.version =~ /^3/
load 'rails/tasks/misc.rake'
load 'active_record/railties/databases.rake'
else
load 'tasks/misc.rake'
l... | # encoding: utf-8
module Specjour
module DbScrub
begin
require 'rake'
extend Rake::DSL if defined?(Rake::DSL)
if defined?(Rails) && Rails.version =~ /^3/
Rake::Task.define_task(:environment) { }
load 'rails/tasks/misc.rake'
load 'active_record/railties/databases.rake'
... |
Add unit tests for slave recipe | # encoding: utf-8
require 'spec_helper'
describe 'mesos::slave' do
before do
File.stub(:exist?).and_call_original
File.stub(:exist?).with('/usr/local/sbin/mesos-master').and_return(false)
File.stub(:exists?).and_call_original
File.stub(:exists?).with('/usr/local/sbin/mesos-master').and_return(false)... | |
Refactor query on Queries controller. | # The queries controller is an api-only controller used to provide
# api users with very specific data without any waste.
class QueriesController < ApplicationController
def show
@results = []
num_records = params[:count] || 5
case params[:group_by]
when "section"
for section in @account.main_c... | # The queries controller is an api-only controller used to provide
# api users with very specific data without any waste.
class QueriesController < ApplicationController
def show
@results = []
num_records = params[:count] || 5
case params[:group_by]
when "section"
for section in @account.main_c... |
Fix problem with the generated title | # Takes a conversation and consistently summarizes it to at maximum LENGTH.
# Consistently is important because it shouldn't change after the first message
# so the labels in the UI are consistent.
class ConversationSummarizer
LENGTH = 140
attr_accessor :conversation
def initialize(conversation)
self.conve... | # Takes a conversation and consistently summarizes it to at maximum LENGTH.
# Consistently is important because it shouldn't change after the first message
# so the labels in the UI are consistent.
class ConversationSummarizer
LENGTH = 140
attr_accessor :conversation
def initialize(conversation)
self.conve... |
Fix site figure file extension constraint incorrect | # frozen_string_literal: true
class SiteFigureUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
def store_dir
'uploads' \
"/#{model.class.to_s.underscore}" \
"/#{mounted_as}/#{model.id}"
end
def default_url(*)
ActionController::Base
.helpers
.asset_path('a... | # frozen_string_literal: true
class SiteFigureUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
def store_dir
'uploads' \
"/#{model.class.to_s.underscore}" \
"/#{mounted_as}/#{model.id}"
end
def default_url(*)
ActionController::Base
.helpers
.asset_path('a... |
Raise exception when location doesn't exist | require 'geocoder'
require 'digest/sha1'
require 'json'
module GeoLookup
CACHE_DIR = "/tmp/jekyll-geo-cache"
def self.lookup(query)
Dir.mkdir(CACHE_DIR) if not Dir.exists?(CACHE_DIR)
hash = Digest::SHA1.hexdigest query.inspect
cache_file = "#{CACHE_DIR}/#{hash}"
return JSON.par... | require 'geocoder'
require 'digest/sha1'
require 'json'
module GeoLookup
CACHE_DIR = "/tmp/jekyll-geo-cache"
def self.lookup(query)
Dir.mkdir(CACHE_DIR) if not Dir.exists?(CACHE_DIR)
hash = Digest::SHA1.hexdigest query.inspect
cache_file = "#{CACHE_DIR}/#{hash}"
return JSON.par... |
Add method to setup cucumber.yml file to use | module IntegrationHelper
class TestRepo
REPO = "https://github.com/renderedtext/test-boosters-tests.git".freeze
attr_reader :project_path
def initialize(test_project)
@repo_path = "/tmp/test-boosters-tests"
@project_path = "/tmp/test-boosters-tests/#{test_project}"
@env = ""
end
... | module IntegrationHelper
class TestRepo
REPO = "https://github.com/renderedtext/test-boosters-tests.git".freeze
attr_reader :project_path
def initialize(test_project)
@repo_path = "/tmp/test-boosters-tests"
@project_path = "/tmp/test-boosters-tests/#{test_project}"
@env = ""
end
... |
Add environment variable to skip integration tests | require 'yaml'
require 'helper'
class IntegrationTest < MiniTest::Test
class << self
attr_accessor :api
end
def accounts
YAML.load_file(File.expand_path('../fixtures/mws.yml', __FILE__))
rescue Errno::ENOENT
skip('Credentials missing')
end
def setup
@clients = accounts.map { |mws| self.cl... | require 'yaml'
require 'helper'
class IntegrationTest < MiniTest::Test
class << self
attr_accessor :api
end
def accounts
skip if ENV['SKIP_INTEGRATION']
YAML.load_file(File.expand_path('../fixtures/mws.yml', __FILE__))
rescue Errno::ENOENT
skip('Credentials missing')
end
def setup
@cl... |
Use a better mechanism for locating files in the gemspec | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/celluloid/zmq/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Tony Arcieri"]
gem.email = ["tony.arcieri@gmail.com"]
gem.description = "Celluloid bindings to the ffi-rzmq library"
gem.summary = "Celluloid::ZMQ p... | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/celluloid/zmq/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Tony Arcieri"]
gem.email = ["tony.arcieri@gmail.com"]
gem.description = "Celluloid bindings to the ffi-rzmq library"
gem.summary = "Celluloid::ZMQ p... |
Add more info to the description | lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'tools/version'
Gem::Specification.new do |spec|
spec.name = 'bt-tools'
spec.version = Tools::VERSION
spec.authors = ['Andrew Page']
spec.email = %w(andrew@andrewpage.me)
... | lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'tools/version'
Gem::Specification.new do |spec|
spec.name = 'bt-tools'
spec.version = Tools::VERSION
spec.authors = ['Andrew Page']
spec.email = %w(andrew@andrewpage.me)
... |
Use new README in gemspec | lib = File.expand_path("../lib", __FILE__)
$:.unshift lib unless $:.include? lib
require "gas/version"
Gem::Specification.new do |s|
s.name = "gas"
s.version = Gas::VERSION
s.authors = "Fredrik Wallgren"
s.email = "fredrik.wallgren@gmail.com"
s.homepage = "https://github.com/walle/gas"
s.summary = "Manage... | lib = File.expand_path("../lib", __FILE__)
$:.unshift lib unless $:.include? lib
require "gas/version"
Gem::Specification.new do |s|
s.name = "gas"
s.version = Gas::VERSION
s.authors = "Fredrik Wallgren"
s.email = "fredrik.wallgren@gmail.com"
s.homepage = "https://github.com/walle/gas"
s.summary = "Manage... |
Remove "factor" from the Input spec factory | FactoryGirl.define do
factory :input do
sequence(:lookup_id)
key { "input-#{ lookup_id }" }
factor 1
min_value 0
max_value 100
start_value 10
end
factory :gql_input, parent: :input do
start_value_gql 'present:2 * 4'
min_value_gql 'present:2 * 2'
max_value_gql 'present:2 * ... | FactoryGirl.define do
factory :input do
sequence(:lookup_id)
key { "input-#{ lookup_id }" }
min_value 0
max_value 100
start_value 10
end
factory :gql_input, parent: :input do
start_value_gql 'present:2 * 4'
min_value_gql 'present:2 * 2'
max_value_gql 'present:2 * 8'
end
f... |
Use rsyslog 2.0 for Chef 11 compat | name 'bluepill'
maintainer 'Chef Software, Inc.'
maintainer_email 'cookbooks@chef.io'
license 'Apache 2.0'
description 'Installs bluepill gem and configures to manage services, includes bluepill_service LWRP'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '2.4.0'
recipe 'bluepill::defa... | name 'bluepill'
maintainer 'Chef Software, Inc.'
maintainer_email 'cookbooks@chef.io'
license 'Apache 2.0'
description 'Installs bluepill gem and configures to manage services, includes bluepill_service LWRP'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '2.4.0'
recipe 'bluepill::defa... |
Add images import to podfile | Pod::Spec.new do |s|
s.name = 'ios-sdk'
s.version = '0.1.0'
s.summary = 'Mapzen iOS SDK'
s.description = 'Mapzen iOS SDK'
s.homepage = 'https://mapzen.com/projects/mobile/'
s.license = { :type => 'MIT', :file => 'LICENSE.md' }
s.author = { 'Mapzen' => 'io... | Pod::Spec.new do |s|
s.name = 'ios-sdk'
s.version = '0.1.0'
s.summary = 'Mapzen iOS SDK'
s.description = 'Mapzen iOS SDK'
s.homepage = 'https://mapzen.com/projects/mobile/'
s.license = { :type => 'MIT', :file => 'LICENSE.md' }
s.author = { 'Mapzen' => 'io... |
Fix scoping issue on Ruby 1.8 and make sure dirs exist when unzipping. | require 'zip/zip'
module Selenium
module WebDriver
module ZipHelper
module_function
def unzip(path)
destination = Dir.mktmpdir("unzip")
FileReaper << destination
Zip::ZipFile.open(path) do |zip|
zip.each do |entry|
zip.extract(entry, File.join(destina... | require 'zip/zip'
module Selenium
module WebDriver
module ZipHelper
module_function
def unzip(path)
destination = Dir.mktmpdir("unzip")
FileReaper << destination
Zip::ZipFile.open(path) do |zip|
zip.each do |entry|
to = File.join(destination, entry.na... |
Improve with trait * Add each difficulty factories | FactoryGirl.define do
factory :music do
sequence(:name) { |n| "music_#{n}" }
type "Music::HardMusic"
difficulty '10+'
score 1000
achivement_rate 95.0
clear_level 1
play_count 0
miss_count 2
end
end
| FactoryGirl.define do
factory :music do
sequence(:name) { |n| "music_#{n}" }
type "Music::HardMusic"
difficulty '10+'
score 1000
achivement_rate 95.0
clear_level 1
play_count 0
miss_count 2
Settings.difficulty.each do |d|
trait "difficulty_#{d}".to_sym do
difficulty ... |
Remove bootstrap-sass version sniffing, its implemented in bootstrap-navbar gem now | require 'bootstrap-navbar'
module BootstrapNavbar::Helpers
def prepare_html(html)
html.html_safe
end
end
module RailsBootstrapNavbar
class Railtie < Rails::Railtie
config.after_initialize do
BootstrapNavbar.configure do |config|
config.current_url_method = if Rails.version >= '3.2'
... | require 'bootstrap-navbar'
module BootstrapNavbar::Helpers
def prepare_html(html)
html.html_safe
end
end
module RailsBootstrapNavbar
class Railtie < Rails::Railtie
config.after_initialize do
BootstrapNavbar.configure do |config|
config.current_url_method = if Rails.version >= '3.2'
... |
Add plugin for NAT (conntrack) metrics | #!/usr/bin/env ruby
require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'sensu-plugin/metric/cli'
require 'socket'
class Conntrack < Sensu::Plugin::Metric::CLI::Graphite
option :scheme,
:description => "Metric naming scheme, text to prepend to .$parent.$child",
:long => "--scheme SCHEME",
:default => "... | |
Fix aliased operators specs on Ruby 1.8.7 | require 'spec_helper'
describe SexyScopes::Arel::PredicateMethods do
before do
@attribute = User.attribute(:score)
end
RUBY_19_METHODS = %w( != !~ )
METHODS = {
# Arel method => [ Ruby operator, SQL operator ]
:eq => [ '==', '= %s' ],
:in => [ nil, 'IN ... | require 'spec_helper'
describe SexyScopes::Arel::PredicateMethods do
before do
@attribute = User.attribute(:score)
end
RUBY_19_METHODS = %w( != !~ )
METHODS = {
# Arel method => [ Ruby operator, SQL operator ]
:eq => [ '==', '= %s' ],
:in => [ nil, 'IN ... |
Add test for failed JSON loading | require File.dirname(__FILE__) + '/spec_helper.rb'
describe "AMEE module" do
it "should cope if json gem isn't available" do
# Monkeypatch Kernel#require to make sure that require 'json'
# raises a LoadError
module Kernel
def require_with_mock(string)
raise LoadError.new if string == 'json... | |
Add digest require to UploadHelper | module UploadHelper
def self.validate(text)
return false if text.nil? or text.length <= 0
secret = ENV["TREESTATS_SECRET"]
return true if secret.nil?
result = false
begin
l = eval "lambda { |x| #{secret} }"
rescue SyntaxError => e
# Allow uploads on eval exception
puts "Up... | require "digest"
module UploadHelper
def self.validate(text)
return false if text.nil? or text.length <= 0
secret = ENV["TREESTATS_SECRET"]
return true if secret.nil?
result = false
begin
l = eval "lambda { |x| #{secret} }"
rescue SyntaxError => e
# Allow uploads on eval except... |
Convert controller spec to request spec | # frozen_string_literal: true
require 'rails_helper'
describe ActiveCoursesController do
render_views
describe '#index' do
let!(:course) do
create(:course, title: 'My awesome course', end: 1.day.from_now)
end
it 'lists a soon-ending course' do
get :index
expect(response.body).to ha... | # frozen_string_literal: true
require 'rails_helper'
describe ActiveCoursesController, type: :request do
describe '#index' do
let!(:course) do
create(:course, title: 'My awesome course', end: 1.day.from_now)
end
it 'lists a soon-ending course' do
get '/active_courses'
expect(response.... |
Use `system` over `exec` to spawn a subshell. If using verbose, use `%x[command]` instead to return output. | def scp_transfer(direction, from, to, options = {})
remote_prefix = "#{domain!}:"
remote_prefix = "#{user}@#{remote_prefix}" if user?
command = "scp"
command << " -i #{identity_file}" if identity_file?
command << " -P #{port}" if port?
case direction
when :up then to = remote_prefix + to
when :down ... | def scp_transfer(direction, from, to, options = {})
remote_prefix = "#{domain!}:"
remote_prefix = "#{user}@#{remote_prefix}" if user?
command = "scp"
command << " -i #{identity_file}" if identity_file?
command << " -P #{port}" if port?
case direction
when :up then to = remote_prefix + to
when :down ... |
Remove unnecessary items from podspec | Pod::Spec.new do |s|
s.name = "PXInfiniteScrollView"
s.version = "0.1.2"
s.summary = "Pages. It loops. It's infinite."
s.description = <<-DESC
It has uses. Just don't scroll too fast.
DESC
s.homepage = "https://github.co... | Pod::Spec.new do |s|
s.name = "PXInfiniteScrollView"
s.version = "0.1.2"
s.summary = "Pages. It loops. It's infinite."
s.description = <<-DESC
It has uses. Just don't scroll too fast.
DESC
s.homepage = "https://github.co... |
Add missing ZeroMoney cop require | # frozen_string_literal: true
require 'rubocop/cop/money/missing_currency'
| # frozen_string_literal: true
require 'rubocop/cop/money/missing_currency'
require 'rubocop/cop/money/zero_money'
|
Rename TQ1 start_date and end_date |
class HL7::Message::Segment::TQ1 < HL7::Message::Segment
weight 2
add_field :set_id, idx: 1
add_field :quantity, idx: 2
add_field :repeat_pattern, idx: 3
add_field :explicit_time, idx: 4
add_field :relative_time_and_units, idx: 5
add_field :service_duration, idx: 6
add_field :start_date_time, idx: 7
... |
class HL7::Message::Segment::TQ1 < HL7::Message::Segment
weight 2
add_field :set_id, idx: 1
add_field :quantity, idx: 2
add_field :repeat_pattern, idx: 3
add_field :explicit_time, idx: 4
add_field :relative_time_and_units, idx: 5
add_field :service_duration, idx: 6
add_field :start_date, idx: 7
add_f... |
Add TODO for remebering to refactor todo's output | # What_now definitions
require 'ptools'
Todo = Struct.new :text, :path, :line
module WhatNow
class << self
def ignorecase
@ignorecase = true
end
def search_line(line, line_number, path)
regex = @ignorecase ? /TODO:?\s*(.+)$/i : /TODO:?\s*(.+)$/
text = regex.match(line)
Todo.ne... | # What_now definitions
require 'ptools'
# TODO this struct should know how to print itself
Todo = Struct.new :text, :path, :line
module WhatNow
class << self
def ignorecase
@ignorecase = true
end
def search_line(line, line_number, path)
regex = @ignorecase ? /TODO:?\s*(.+)$/i : /TODO:?\s*... |
Add Sinatra and ActiveRecord dependencies | require File.expand_path('../lib/dredge/version', __FILE__)
Gem::Specification.new do |s|
s.name = 'dredge'
s.version = Dredge::VERSION
s.date = Time.now.strftime('%Y-%m-%d')
s.summary = 'Dredge is an ActiveRecord based data analysis tool'
s.homepage = 'https://github.com/lmars/dredge'
s.ema... | require File.expand_path('../lib/dredge/version', __FILE__)
Gem::Specification.new do |s|
s.name = 'dredge'
s.version = Dredge::VERSION
s.date = Time.now.strftime('%Y-%m-%d')
s.summary = 'Dredge is an ActiveRecord based data analysis tool'
s.homepage = 'https://github.com/lmars/dredge'
s.ema... |
Add a spec to test interface validatation | require 'spec_helper'
include PacketFu
describe Utils do
context "when using ifconfig" do
it "should return a hash" do
PacketFu::Utils.ifconfig().should be_a(::Hash)
end
it "should prevent non-interface values" do
expect {
PacketFu::Utils.ifconfig("not_a_interface")
}.to raise... | |
Update to match tumblr API change, only fetch text posts | class BlogFetcher
BASE_URL = 'http://blog.mayday.us/api'
ENDPOINTS = {
recent: '/read/json?num=5',
press_releases: '/read/json?tagged=press%20release&num=5'
}
KEY_BASE = "blog_feeds"
EXPIRE_SECONDS = 3.hours.to_i
def self.feed(param:, reset:false)
!reset && redis.get(key(param)) || fet... | class BlogFetcher
BASE_URL = 'http://blog.mayday.us/api'
ENDPOINTS = {
recent: '/read/json?num=5&type=text',
press_releases: '/read/json?tagged=press%20release&num=5&type=text'
}
KEY_BASE = "blog_feeds"
EXPIRE_SECONDS = 3.hours.to_i
def self.feed(param:, reset:false)
!reset && redis.ge... |
Remove newlines from monkey-patch warning | require 'puppet/util/autoload'
require 'puppet/util/log'
Puppet::Util::Log.create({:level => :warning, :source => __FILE__, :message => "\n\n***** Monkey-patching out gem autoload feature *****\n\n"})
Puppet::Util::Autoload.class_eval do
def self.gem_directories
[]
end
end
| require 'puppet/util/autoload'
require 'puppet/util/log'
Puppet::Util::Log.create({:level => :warning, :source => __FILE__, :message => "***** Monkey-patching out gem autoload feature *****"})
Puppet::Util::Autoload.class_eval do
def self.gem_directories
[]
end
end
|
Add question and answer wrappers | require "isurvey/version"
module Isurvey
attr_accessor :company_identifier, :survey_password
def savon_client
@savon_client ||= Savon.client(
wsdl: "https://isurveysoft.com/servicesv3/exportservice.asmx?WSDL"
)
end
def savon_call(operation)
self.savon_client.call(
operation,
mes... | require "isurvey/version"
module Isurvey
class SOAPClient
attr_accessor :company_identifier, :survey_password
def self.savon_client
@savon_client ||= Savon.client(
wsdl: "https://isurveysoft.com/servicesv3/exportservice.asmx?WSDL"
)
end
def self.savon_call(operation)
self... |
Make sure Time extensions are loaded | require 'net/http'
require 'json'
require 'simple_segment/version'
require 'simple_segment/client'
module SimpleSegment
end
| require 'net/http'
require 'json'
require 'time'
require 'simple_segment/version'
require 'simple_segment/client'
module SimpleSegment
end
|
Improve specs for class 2 exercise 4 | RSpec.describe 'Class 2 Exercise 4' do
let(:exercise4) do
load File.expand_path('../../../lib/class2/exercise4.rb', __FILE__)
end
before do
stubs = %w(Samuel Leroy Jackson)
allow_any_instance_of(Kernel).to receive(:gets).and_return(*stubs)
end
it 'outputs to STDOUT' do
expect { exercise4 }.t... | RSpec.describe 'Class 2 Exercise 4' do
let(:exercise4) do
load File.expand_path('../../../lib/class2/exercise4.rb', __FILE__)
end
before do
allow_any_instance_of(Kernel).to receive(:gets).and_return('anything')
end
it 'outputs to STDOUT' do
expect { exercise4 }.to output.to_stdout
end
conte... |
Add commented out logging override to generated config file | # Centralized way to overwrite any Adhearsion platform or plugin configuration
# - Execute rake adhearsion:config:desc to get the configuration options
# - Execute rake adhearsion:config:show to get the configuration values
#
# To update a plugin configuration you can write either:
#
# * Option 1
# Adhearsion... | # Centralized way to overwrite any Adhearsion platform or plugin configuration
# - Execute rake adhearsion:config:desc to get the configuration options
# - Execute rake adhearsion:config:show to get the configuration values
#
# To update a plugin configuration you can write either:
#
# * Option 1
# Adhearsion... |
Use >= 2.1.0 so that gem installs of newer versions of rails can still run the shoulda tests | # Specifies gem version of Rails to use when vendor/rails is not present
old_verbose, $VERBOSE = $VERBOSE, nil
RAILS_GEM_VERSION = '2.1.0' unless defined? RAILS_GEM_VERSION
$VERBOSE = old_verbose
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
config.log_level = :debug
config.... | # Specifies gem version of Rails to use when vendor/rails is not present
old_verbose, $VERBOSE = $VERBOSE, nil
RAILS_GEM_VERSION = '>= 2.1.0' unless defined? RAILS_GEM_VERSION
$VERBOSE = old_verbose
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
config.log_level = :debug
conf... |
Create a simple string with reverse and upcase method | # Solution Below
old_string = "Ruby is cool"
new_string = old_string.reverse.upcase
# RSpec Tests. They are included in this file because the local variables you are creating are not accessible across files. If we try to run these files as a separate file per normal operation, the local variable checks will retur... | |
Add rake as development depencency | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/ruremai/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ['hibariya']
gem.email = ['celluloid.key@gmail.com']
gem.description = %q{Object.method(:name).rurema!}
gem.summary = %q{Open ruby reference manual by brows... | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/ruremai/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ['hibariya']
gem.email = ['celluloid.key@gmail.com']
gem.description = %q{Object.method(:name).rurema!}
gem.summary = %q{Open ruby reference manual by brows... |
Handle user names with periods in them. | #
# Cookbook Name:: user
# Recipe:: data_bag
#
# Copyright 2011, Fletcher Nichol
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | #
# Cookbook Name:: user
# Recipe:: data_bag
#
# Copyright 2011, Fletcher Nichol
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... |
Add basic spec for league requests page | require 'spec_helper'
describe LeagueRequestsController do
render_views
before do
@user = create :user
sign_in @user
end
describe '#new' do
context 'for non-admins' do
it 'redirect to root for non admins' do
get :new
response.should redirect_to(root_path)
end
end
... | |
Document interface in namespace docs | module Metasploit
module Model
module Search
# Namespace for search operators
module Operator
end
end
end
end | module Metasploit
module Model
module Search
# # Declaring operator classes
#
# ## Interface
#
# Operators do not need to subclass any specific superclass, but they are expected to define certain methods.
#
# class MyOperator
# #
# # Instance M... |
Allow to override description of Rake task | require 'rake'
require 'rake/tasklib'
module FoodCritic
module Rake
class LintTask < ::Rake::TaskLib
attr_accessor :name, :files
attr_writer :options
def initialize(name = :foodcritic)
@name = name
@files = [Dir.pwd]
@options = {}
yield self if block_given?
... | require 'rake'
require 'rake/tasklib'
module FoodCritic
module Rake
class LintTask < ::Rake::TaskLib
attr_accessor :name, :files
attr_writer :options
def initialize(name = :foodcritic)
@name = name
@files = [Dir.pwd]
@options = {}
yield self if block_given?
... |
Fix Upstart service spec path | # coding: UTF-8
require 'spec_helper'
context 'when node[zookeeper][service_style] is set to upstart on Ubuntu' do
describe file '/etc/init/zookeeper' do
it { is_expected.to be_file }
end
describe service 'zookeeper' do
it { is_expected.to be_enabled }
it { is_expected.to be_running.under 'upstart'... | # coding: UTF-8
require 'spec_helper'
context 'when node[zookeeper][service_style] is set to upstart on Ubuntu' do
describe file '/etc/init/zookeeper.conf' do
it { is_expected.to be_file }
end
describe service 'zookeeper' do
it { is_expected.to be_enabled }
it { is_expected.to be_running.under 'ups... |
Update mutable specs to use etc_file helper | require File.join(File.dirname(__FILE__), 'spec_helper')
require 'rdf/ntriples'
describe RDF::Mutable do
before :each do
@filename = "etc/doap.nt"
# Possible reference implementations are RDF::Repository and RDF::Graph.
@repo = RDF::Repository.new
@subject = RDF::URI.new("http://rubygems.o... | require File.join(File.dirname(__FILE__), 'spec_helper')
require 'rdf/ntriples'
describe RDF::Mutable do
before :each do
@filename = etc_file("doap.nt")
# Possible reference implementations are RDF::Repository and RDF::Graph.
@repo = RDF::Repository.new
@subject = RDF::URI.new("http://ruby... |
Use HTTP methods for custom routes | # -*- encoding : utf-8 -*-
# Here you can override or add to the pages in the core website
Rails.application.routes.draw do
# brand new controller example
# match '/mycontroller' => 'general#mycontroller'
# Additional help page example
# match '/help/help_out' => 'help#help_out'
end
| # -*- encoding : utf-8 -*-
# Here you can override or add to the pages in the core website
Rails.application.routes.draw do
# brand new controller example
# get '/mycontroller' => 'general#mycontroller'
# Additional help page example
# get '/help/help_out' => 'help#help_out'
end
|
Change by_pass param to bypass | module SimpleFilter
module Filter
attr_accessor :filters
def filter(name, options = {})
method_module = ModuleHelper.module_for 'Filter', name, self
value_param = options.fetch :value_param, false
by_pass = options.fetch :by_pass, false
method_module.module_eval <<-CODE, __FILE__, __... | module SimpleFilter
module Filter
attr_accessor :filters
def filter(name, options = {})
method_module = ModuleHelper.module_for 'Filter', name, self
value_param = options.fetch :value_param, false
bypass = options.fetch :bypass, false
method_module.module_eval <<-CODE, __FILE__, __LI... |
Fix the gemspec executables prefix | # frozen-string-literal: true
# encoding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'statsd/instrument/version'
Gem::Specification.new do |spec|
spec.name = "statsd-instrument"
spec.version = StatsD::Instrument::VERSION
spec.authors = ["Jess... | # frozen-string-literal: true
# encoding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'statsd/instrument/version'
Gem::Specification.new do |spec|
spec.name = "statsd-instrument"
spec.version = StatsD::Instrument::VERSION
spec.authors = ["Jess... |
Migrate to the correct version. | # Since we've designed metrics/docs tables to revolve around
# the pods table, but be independent of each other, we can
# run all trunk migrations first, then all others.
#
# Helper method
#
def foreign_key_delete_cascade source_table, target_table, foreign_key
<<-SQL
ALTER TABLE #{source_table} DROP CONSTRAINT ... | # Since we've designed metrics/docs tables to revolve around
# the pods table, but be independent of each other, we can
# run all trunk migrations first, then all others.
#
# Helper method
#
def foreign_key_delete_cascade source_table, target_table, foreign_key
<<-SQL
ALTER TABLE #{source_table} DROP CONSTRAINT ... |
Increase size of activity feed | class ProjectsController < ApplicationController
def index
@projects = Project.by_last_updated
@entry = Entry.new
@activities = Entry.last(10).reverse
end
def show
@project = Project.find(params[:id])
end
def new
@project = Project.new
end
def create
@project = Project.new(proje... | class ProjectsController < ApplicationController
def index
@projects = Project.by_last_updated
@entry = Entry.new
@activities = Entry.last(20).reverse
end
def show
@project = Project.find(params[:id])
end
def new
@project = Project.new
end
def create
@project = Project.new(proje... |
Add checks on Ceph backend for Glance | require 'spec_helper'
#
# Glance
#
describe service('glance-api') do
it { should be_enabled }
it { should be_running }
end
describe port(9292) do
it { should be_listening.with('tcp') }
end
describe service('glance-registry') do
it { should be_enabled }
it { should be_running }
end
describe port(9191) do
... | require 'spec_helper'
#
# Glance
#
describe service('glance-api') do
it { should be_enabled }
it { should be_running }
end
describe port(9292) do
it { should be_listening.with('tcp') }
end
describe service('glance-registry') do
it { should be_enabled }
it { should be_running }
end
describe port(9191) do
... |
Remove support for attaching a custom resource to itself | require_relative './resource'
module Convection
module Model
class Template
# TODO: We've been back on forth on the name for this concept.
# Is CustomResource *really* better than ResourceGroup?
class CustomResource
include DSL::Helpers
include DSL::IntrinsicFunctions
in... | require_relative './resource'
module Convection
module Model
class Template
# TODO: We've been back on forth on the name for this concept.
# Is CustomResource *really* better than ResourceGroup?
class CustomResource
include DSL::Helpers
include DSL::IntrinsicFunctions
in... |
Move the warning about specs as root | use_realpath = File.respond_to?(:realpath)
root = File.dirname(__FILE__)
dir = "fixtures/code"
CODE_LOADING_DIR = use_realpath ? File.realpath(dir, root) : File.expand_path(dir, root)
# Don't run ruby/spec as root
raise 'ruby/spec is not designed to be run as root' if Process.uid == 0
# Enable Thread.report_on_except... | use_realpath = File.respond_to?(:realpath)
root = File.dirname(__FILE__)
dir = "fixtures/code"
CODE_LOADING_DIR = use_realpath ? File.realpath(dir, root) : File.expand_path(dir, root)
# Enable Thread.report_on_exception by default to catch thread errors earlier
if Thread.respond_to? :report_on_exception=
Thread.repo... |
Fix bug: encode uri query | module SyoboiCalendar
module Agent
extend self
# These CONSTANTS will create method
# such as Agent.base, Agent.search, Agent.json
BASE_URL = "http://cal.syoboi.jp"
SEARCH_URL = BASE_URL + "/find"
JSON_URL = BASE_URL + "/json.php"
LOGIN_URL = BASE_URL + "/usr"
def login(args)
... | require "uri"
module SyoboiCalendar
module Agent
extend self
# These CONSTANTS will create method
# such as Agent.base, Agent.search, Agent.json
BASE_URL = "http://cal.syoboi.jp"
SEARCH_URL = BASE_URL + "/find"
JSON_URL = BASE_URL + "/json.php"
LOGIN_URL = BASE_URL + "/usr"
d... |
Fix wrong inverse_of resulting in wrongly preloaded data | # frozen_string_literal: true
class Span < ApplicationRecord
self.primary_key = 'id'
extend Model::Range
include Model::Duration
attribute :id, :uuid
attribute :trace_id, :uuid
attribute :platform_id, :uuid
attribute :application_id, :uuid
belongs_to :trace
belongs_to :platform
has_many :traces... | # frozen_string_literal: true
class Span < ApplicationRecord
self.primary_key = 'id'
extend Model::Range
include Model::Duration
attribute :id, :uuid
attribute :trace_id, :uuid
attribute :platform_id, :uuid
attribute :application_id, :uuid
belongs_to :trace
belongs_to :platform
has_many :traces... |
Add You Need A Budget | class YouNeedABudget < Cask
url 'http://www.youneedabudget.com/CDNOrigin/download/ynab4/liveCaptive/Mac/YNAB4_LiveCaptive_4.1.553.dmg'
homepage 'http://www.youneedabudget.com/'
version '4.1.553'
sha1 'bf10b82ecf741d4655ab864717e307eb1858e385'
end
| |
Add support for Amazon Linux | name 'statsd'
maintainer 'Mike Heffner'
maintainer_email 'mike@librato.com'
license 'Apache 2.0'
description 'Installs/Configures statsd'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.3.3'
depends 'build-essential'
depends 'git'
depends 'no... | name 'statsd'
maintainer 'Mike Heffner'
maintainer_email 'mike@librato.com'
license 'Apache 2.0'
description 'Installs/Configures statsd'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.3.3'
depends 'build-essential'
depends 'git'
depends 'no... |
Allow hashes as values/input to config parameters | name 'rabbitmq'
maintainer 'Simple Finance'
maintainer_email 'ops@simple.com'
license 'Apache 2.0'
description 'Installs RabbitMQ, an Erlang message queue application'
version '1.0.0'
depends 'erlang'
| name 'rabbitmq'
maintainer 'Simple Finance'
maintainer_email 'ops@simple.com'
license 'Apache 2.0'
description 'Installs RabbitMQ, an Erlang message queue application'
version '1.1.0'
depends 'erlang'
|
Test if element is empty | # frozen_string_literal: true
module SwaggerDocsGenerator
# # Metadata generated
#
# Metadata generated in swagger json file
class Metadata
attr_reader :config
def initialize
@config = SwaggerDocsGenerator.configuration
end
def construct_swagger_file
hash = {}
SwaggerDocsGen... | # frozen_string_literal: true
module SwaggerDocsGenerator
# # Metadata generated
#
# Metadata generated in swagger json file
class Metadata
attr_reader :config
def initialize
@config = SwaggerDocsGenerator.configuration
end
def construct_swagger_file
hash = {}
SwaggerDocsGen... |
Clear AssetHat.html_cache after every test | require 'rubygems'
require 'test/unit'
require 'active_support'
require 'action_controller'
require 'action_view/test_case'
require 'shoulda'
require 'asset_hat'
require 'flexmock/test_unit'
Dir[File.join(File.dirname(__FILE__), %w[.. app helpers *])].each { |f| require f }
ActionController::Base.perform_caching = ... | require 'rubygems'
require 'test/unit'
require 'active_support'
require 'action_controller'
require 'action_view/test_case'
require 'shoulda'
require 'asset_hat'
require 'flexmock/test_unit'
Dir[File.join(File.dirname(__FILE__), %w[.. app helpers *])].each { |f| require f }
ActionController::Base.perform_caching = ... |
Reduce size of the package file | # frozen_string_literal: true
rootdir = File.expand_path(File.dirname(__FILE__))
require "#{rootdir}/lib/thinreports/version"
Gem::Specification.new do |s|
s.name = 'thinreports'
s.version = Thinreports::VERSION
s.author = 'Matsukei Co.,Ltd.'
s.email = 'thinreports@gmail.com'
s.summar... | # frozen_string_literal: true
rootdir = File.expand_path(File.dirname(__FILE__))
require "#{rootdir}/lib/thinreports/version"
Gem::Specification.new do |s|
s.name = 'thinreports'
s.version = Thinreports::VERSION
s.author = 'Matsukei Co.,Ltd.'
s.email = 'thinreports@gmail.com'
s.summar... |
Write the detail of gemspec | # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'guideline/version'
Gem::Specification.new do |gem|
gem.name = "guideline"
gem.version = Guideline::VERSION
gem.authors = ["Ryo NAKAMURA"]
gem.email ... | # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'guideline/version'
Gem::Specification.new do |gem|
gem.name = "guideline"
gem.version = Guideline::VERSION
gem.authors = ["Ryo NAKAMURA"]
gem.email ... |
Make the version check more liberal | require_relative "lib/cocoaseeds/version"
require "date"
Gem::Specification.new do |s|
s.name = "cocoaseeds"
s.version = Seeds::VERSION
s.date = Date.today
s.summary = "Git Submodule Alternative for Cocoa."
s.description = "Git Submodule Alternative for Cocoa.\n\n"\
"i... | require_relative "lib/cocoaseeds/version"
require "date"
Gem::Specification.new do |s|
s.name = "cocoaseeds"
s.version = Seeds::VERSION
s.date = Date.today
s.summary = "Git Submodule Alternative for Cocoa."
s.description = "Git Submodule Alternative for Cocoa.\n\n"\
"i... |
Simplify exception handling in Job | class BulkProcessor
class Job < ActiveJob::Base
queue_as 'bulk_processor'
def perform(records, item_proccessor, handler, payload)
item_proccessor_class = item_proccessor.constantize
handler_class = handler.constantize
successes = {}
failures = {}
records.each_with_index do |rec... | class BulkProcessor
class Job < ActiveJob::Base
queue_as 'bulk_processor'
def perform(records, item_proccessor, handler, payload)
item_proccessor_class = item_proccessor.constantize
handler_class = handler.constantize
successes = {}
failures = {}
records.each_with_index do |rec... |
Use new accessor for failure predicate | module Cooperator
class Context
def initialize(attributes = {})
@_attributes = {_failure: false}
attributes.each do |k, v|
self[k] = v
end
end
def errors
@_errors ||= Hash.new { |h, k| h[k] = [] }
end
def success!
self[:_failure] = false
end
def fa... | module Cooperator
class Context
def initialize(attributes = {})
@_attributes = {_failure: false}
attributes.each do |k, v|
self[k] = v
end
end
def errors
@_errors ||= Hash.new { |h, k| h[k] = [] }
end
def success!
self[:_failure] = false
end
def fa... |
Make sure we load the rspec above, not the gem | task :pre_commit => [:clobber_sqlite, :migrate, :generate_rspec, :specs, :spec]
task :clobber_sqlite do
rm_rf 'db/*.db'
end
task :generate_rspec do
`ruby script/generate rspec --force`
raise "Failed to generate rspec environment" if $? != 0
end
task :specs do
command = "spec specs"
puts `#{command}`
rais... | # We have to make sure the rspec lib above gets loaded rather than the gem one (in case it's installed)
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + '/../../../../lib'))
require 'spec/rake/spectask'
task :pre_commit => [:clobber_sqlite, :migrate, :generate_rspec, :spec, :specs]
task :clobber_sqlite do... |
Add a rake task to migrate the homepage | require 'gds_api/publishing_api'
require 'highline'
desc "Migrate the homepage"
task migrate_homepage: :environment do
cli = HighLine.new
cli.say cli.color(
"Publishing the homepage will make the old service manual inaccessible. Continue?",
:red
)
exit unless cli.agree "Are you sure you wish to continu... | |
Test to ensure that falsy objects aren't wrapped by deprecation proxies | require 'abstract_unit'
require 'active_support/deprecation'
class ProxyWrappersTest < Test::Unit::TestCase
Waffles = false
NewWaffles = :hamburgers
def test_deprecated_object_proxy_doesnt_wrap_falsy_objects
proxy = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(nil, "message")
assert !pro... | |
Revert "I need to path this helper to not fail if the env variables are missing" | class MyModel < ActiveRecord::Base
if ENV['ALGOLIASEARCH_APPLICATION_ID']
include AlgoliaSearch
algoliasearch auto_index: false, auto_remove: false do
end
end
end
| class MyModel < ActiveRecord::Base
algoliasearch auto_index: false, auto_remove: false do
end
end
|
Update Address::VERSION constant to 0.4.0 | require 'dm-core'
require 'dm-types'
require 'dm-validations'
# Require dm-address files
%w{ phone_number zip_code polymorphic preferred us }.each do |file|
require 'dm-address/' + file
end
module DataMapper
module Address
VERSION = '0.3.0'
DEFAULTS = {
:phone_format => PhoneNumber::DEFAULT_FOR... | require 'dm-core'
require 'dm-types'
require 'dm-validations'
# Require dm-address files
%w{ phone_number zip_code polymorphic preferred us }.each do |file|
require 'dm-address/' + file
end
module DataMapper
module Address
VERSION = '0.4.0'
DEFAULTS = {
:phone_format => PhoneNumber::DEFAULT_FOR... |
Make it work out of the box on Ubuntu 10.10 | require 'mkmf'
dir_config("QAR")
$LIBS << " -lcurl"
qmake_path = `which qmake`.chomp
if qmake_path.empty?
warn "********************************************************************************"
warn 'Cannot find qmake (should be installed with Qt development packages)'
warn "***********************************... | require 'mkmf'
dir_config("QAR")
$LIBS << " -lcurl"
qmake_path = `which qmake`.chomp
if qmake_path.empty?
warn "********************************************************************************"
warn 'Cannot find qmake (should be installed with Qt development packages)'
warn "***********************************... |
Remove serialization of violations_archive on Build | class Build < ActiveRecord::Base
belongs_to :repo
has_many :violations, dependent: :destroy
before_create :generate_uuid
validates :repo, presence: true
serialize :violations_archive, Array
def status
if violations.any?
'failed'
else
'passed'
end
end
private
def generate_... | class Build < ActiveRecord::Base
belongs_to :repo
has_many :violations, dependent: :destroy
before_create :generate_uuid
validates :repo, presence: true
def status
if violations.any?
'failed'
else
'passed'
end
end
private
def generate_uuid
self.uuid = SecureRandom.uuid
... |
Disable X-Frame-Options header from being set with Rack::Protection | require_relative "env"
def config_for(kind)
YAML.load_file(File.expand_path("../#{kind}.yml", __FILE__))
end
set :router, config_for(:router)
set :solr, config_for(:solr)[ENV["RACK_ENV"]]
set :slimmer_headers, config_for(:slimmer_headers)
set :slimmer_asset_host, ENV["SLIMMER_ASSET_HOST"]
set :top_results, 4
set :... | require_relative "env"
def config_for(kind)
YAML.load_file(File.expand_path("../#{kind}.yml", __FILE__))
end
set :router, config_for(:router)
set :solr, config_for(:solr)[ENV["RACK_ENV"]]
set :slimmer_headers, config_for(:slimmer_headers)
set :slimmer_asset_host, ENV["SLIMMER_ASSET_HOST"]
set :top_results, 4
set :... |
Fix routing_key for admin queue | # frozen_string_literal: true
module RubyRabbitmqJanus
module Rabbit
# @author VAILLANT Jeremy <jeremy.vaillant@dazzl.tv>
# @!attribute [r] correlation
# @return [String] Is a string uniq generated by SecureRandom
#
# Manage properties to message sending in rabbitmq queue
class Propertie
... | # frozen_string_literal: true
module RubyRabbitmqJanus
module Rabbit
# @author VAILLANT Jeremy <jeremy.vaillant@dazzl.tv>
# @!attribute [r] correlation
# @return [String] Is a string uniq generated by SecureRandom
#
# Manage properties to message sending in rabbitmq queue
class Propertie
... |
Add sync directories as example. | set :application, "set your application name here"
set :repository, "set your repository location here"
set :web_root, "/srv/cyt.ch/"
role :web, "your web-server here" # Your HTTP server, Apache/etc
role :app, "your app-server here" # This may be the same as your `Web... | set :application, "set your application name here"
set :repository, "set your repository location here"
set :web_root, "/srv/cyt.ch/"
role :web, "your web-server here" # Your HTTP server, Apache/etc
role :app, "your app-server here" # This may be the same as your `Web... |
Add precision method to Geocoder::Result::Yandex. | require 'geocoder/results/base'
module Geocoder::Result
class Yandex < Base
def coordinates
@data['GeoObject']['Point']['pos'].split(' ').reverse.map(&:to_f)
end
def address(format = :full)
@data['GeoObject']['metaDataProperty']['GeocoderMetaData']['text']
end
def city
if sta... | require 'geocoder/results/base'
module Geocoder::Result
class Yandex < Base
def coordinates
@data['GeoObject']['Point']['pos'].split(' ').reverse.map(&:to_f)
end
def address(format = :full)
@data['GeoObject']['metaDataProperty']['GeocoderMetaData']['text']
end
def city
if sta... |
Fix typo in log output | # encoding: UTF-8
#
# Author:: Tim Smith (<tim@cozy.co>)
# Copyright:: Copyright (c) 2014 Tim Smith
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#... | # encoding: UTF-8
#
# Author:: Tim Smith (<tim@cozy.co>)
# Copyright:: Copyright (c) 2014 Tim Smith
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#... |
Remove deprecated hack from rake task | namespace :js do
desc "Make a js file that will have functions that will return restful routes/urls."
task :routes => :environment do
require "js-routes"
# Hack for actually load the routes (taken from railties console/app.rb)
ActionDispatch::Callbacks.new(lambda {}, false)
JsRoutes.generate!
en... | namespace :js do
desc "Make a js file that will have functions that will return restful routes/urls."
task :routes => :environment do
require "js-routes"
JsRoutes.generate!
end
end
|
Add option for showing DVTPlugInCompatibilityUUID | module XcodeInstall
class Command
class Installed < Command
self.command = 'installed'
self.summary = 'List installed Xcodes.'
def run
installer = XcodeInstall::Installer.new
installer.installed_versions.each do |xcode|
puts "#{xcode.version}\t(#{xcode.path})"
... | module XcodeInstall
class Command
class Installed < Command
self.command = 'installed'
self.summary = 'List installed Xcodes.'
def self.options
[['--uuid', 'Show DVTPlugInCompatibilityUUID of plist.']].concat(super)
end
def initialize(argv)
@uuid = argv.flag?('uuid'... |
Fix tenant site not found | # frozen_string_literal: true
module TenantSite
extend ActiveSupport::Concern
included do
helper_method :tenant_site?
helper_method :current_site
end
def current_site
return default_site unless tenant_site?
Site.find_by(domain: Apartment::Tenant.current.tr('_', '.'))
end
def tenant_site?... | # frozen_string_literal: true
module TenantSite
extend ActiveSupport::Concern
included do
helper_method :tenant_site?
helper_method :current_site
end
def current_site
return default_site unless tenant_site?
Site.find_by(tenant_name: Apartment::Tenant.current)
end
def tenant_site?
Apa... |
Add bundle as a dev dependency | $:.push File.expand_path("../lib", __FILE__)
Gem::Specification.new do |s|
s.name = "chef-handler-slack"
s.version = "0.1.0"
s.authors = ["Derek Smith"]
s.email = ["derek@slack-corp.com"]
s.homepage = "https://github.com/tinyspeck/chef-handler-slack"
s.summary = %q{Chef reports ... | $:.push File.expand_path("../lib", __FILE__)
Gem::Specification.new do |s|
s.name = "chef-handler-slack"
s.version = "0.1.0"
s.authors = ["Derek Smith"]
s.email = ["derek@slack-corp.com"]
s.homepage = "https://github.com/tinyspeck/chef-handler-slack"
s.summary = %q{C... |
Fix tasks displayed in dashboard | class DashboardsController < OrganizationAwareController
def index
@page_title = 'Dashboard'
# Select messages for this user or ones that are for the agency as a whole
@messages = Message.where("organization_id = ? AND to_user_id = ? AND opened_at IS NULL", @organization.id, current_use... | class DashboardsController < OrganizationAwareController
def index
@page_title = 'My Dashboard'
# Select messages for this user or ones that are for the agency as a whole
@messages = Message.where("to_user_id = ? AND opened_at IS NULL", @organization.id, current_user.id).order("created_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.