Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Reduce the interval between geocoding checks | # encoding: utf-8
require 'eventmachine'
require File.expand_path('../../../../../config/environment.rb', __FILE__)
module CartoDB
module AutomaticGeocoder
class Runner
TICK_TIME_IN_SECS = 10
RUN_FOREVER = 0
attr_reader :ticks
def initialize(options = {})
@max_ticks ... | # encoding: utf-8
require 'eventmachine'
require File.expand_path('../../../../../config/environment.rb', __FILE__)
module CartoDB
module AutomaticGeocoder
class Runner
TICK_TIME_IN_SECS = 10
RUN_FOREVER = 0
attr_reader :ticks
def initialize(options = {})
@max_ticks ... |
Check object has hasKey? in group serializer | # Doubtfire will deprecate ActiveModelSerializer in the future.
# Instead, write a serialize method on the
class GroupSerializer < ActiveModel::Serializer
attributes :id, :name, :tutorial_id, :group_set_id, :number, :student_count
def student_count
return object.student_count if object.has_attribute?(:student... | # Doubtfire will deprecate ActiveModelSerializer in the future.
# Instead, write a serialize method on the
class GroupSerializer < ActiveModel::Serializer
attributes :id, :name, :tutorial_id, :group_set_id, :number, :student_count
def student_count
return object.student_count if object.has_attribute?(:student... |
Add 'each' that iterates over all log files | require 'fog/core/collection'
require 'fog/aws/models/rds/log_file'
module Fog
module AWS
class RDS
class LogFiles < Fog::Collection
attribute :rds_id
model Fog::AWS::RDS::LogFile
def all
data = service.describe_db_log_files(rds_id).body['DescribeDBLogFilesResult']['DBLo... | require 'fog/core/collection'
require 'fog/aws/models/rds/log_file'
module Fog
module AWS
class RDS
class LogFiles < Fog::Collection
attribute :filters
attribute :rds_id
model Fog::AWS::RDS::LogFile
def initialize(attributes)
self.filters ||= {}
super
... |
Allow Scanner to work outside a Bundler environment | require "bundler/audit/database"
require "bundler/audit/scanner"
require "bundler/lockfile_parser"
module GovukSecurityAudit
class Scanner < Bundler::Audit::Scanner
def initialize(path=Dir.pwd)
path = File.expand_path(path)
if File.directory?(path)
path = File.join(path, "Gemfile.lock")
... | require "bundler/audit/database"
require "bundler/audit/scanner"
require "bundler/lockfile_parser"
module GovukSecurityAudit
class Scanner < Bundler::Audit::Scanner
def initialize(path=Dir.pwd)
path = File.expand_path(path)
if File.directory?(path)
path = File.join(path, "Gemfile.lock")
... |
Add integration tests for the aws_internet_gateway provider. | require 'spec_helper'
describe Chef::Resource::AwsInternetGateway do
extend AWSSupport
when_the_chef_12_server "exists", organization: 'foo', server_scope: :context do
with_aws "with a VPC and an internet gateway" do
vpc = nil
internet_gateway = nil
before {
vpc = driver.ec2.vpcs.cr... | |
Expand the test for the read scenario | require "spec_helper"
describe "FC082" do
context "with a cookbook with a recipe that sets an attribute with node.set" do
recipe_file "node.set['foo']['bar'] = baz"
it { is_expected.to violate_rule }
end
context "with a cookbook with a recipe that sets an attribute with node.set_unless" do
recipe_fi... | require "spec_helper"
describe "FC082" do
context "with a cookbook with a recipe that sets an attribute with node.set" do
recipe_file "node.set['foo']['bar'] = baz"
it { is_expected.to violate_rule }
end
context "with a cookbook with a recipe that sets an attribute with node.set_unless" do
recipe_fi... |
Use idiomatic naming of memoization. | require "yaml"
module Nutrella
#
# Provides a cache of the most recently used items.
#
class Cache
attr_reader :capacity, :path
def initialize(path, capacity)
@path = path
@capacity = capacity
end
def fetch(key)
value = lookup(key) || yield
write(key, value)
valu... | require "yaml"
module Nutrella
#
# Provides a cache of the most recently used items.
#
class Cache
attr_reader :capacity, :path
def initialize(path, capacity)
@path = path
@capacity = capacity
end
def fetch(key)
value = lookup(key) || yield
write(key, value)
valu... |
Define the variables to be cleaned for testing | module Juicy
class BuildEnvironment
attr_reader :env
def initialize
@env = ENV.to_hash.tap do |env|
%w[RUBYOPT BUNDLE_GEMFILE RACK_ENV MONGOLAB_URI].each do |var|
env[var] = nil
end
env["BUNDLE_CONFIG"] = "/nonexistent"
end
end
def [](k)
env[k]
... | module Juicy
BUILD_SENSITIVE_VARIABLES = %w[RUBYOPT BUNDLE_GEMFILE RACK_ENV MONGOLAB_URI]
class BuildEnvironment
attr_reader :env
def initialize
@env = ENV.to_hash.tap do |env|
BUILD_SENSITIVE_VARIABLES.each do |var|
env[var] = nil
end
env["BUNDLE_CONFIG"] = "/nonexi... |
Revert "Remove IRC logging of door events" | module Door::Loggable
extend ActiveSupport::Concern
included do
has_one :log_entry, as: :loggable
before_create :associate_log_entry
#after_create :spam_irc
end
def public_message
end
private
def associate_log_entry
self.log_entry = build_log_entry
end
def spam_irc
message = p... | module Door::Loggable
extend ActiveSupport::Concern
included do
has_one :log_entry, as: :loggable
before_create :associate_log_entry
after_create :spam_irc
end
def public_message
end
private
def associate_log_entry
self.log_entry = build_log_entry
end
def spam_irc
message = pu... |
Fix issue where data_dump `status` where erroneously `inactive` | require "spec_helper"
describe Devices::Dump do
# Resources that I can't easily instantiate via FactoryBot
SPECIAL = [:points, :sequences, :device]
ADDITIONAL = [:plants, :tool_slots, :generic_pointers]
MODEL_NAMES = Devices::Dump::RESOURCES.without(*SPECIAL).concat(ADDITIONAL)
it "serializes _all_ the ... | require "spec_helper"
describe Devices::Dump do
# Resources that I can't easily instantiate via FactoryBot
SPECIAL = [:points, :sequences, :device]
ADDITIONAL = [:plants, :tool_slots, :generic_pointers]
MODEL_NAMES = Devices::Dump::RESOURCES.without(*SPECIAL).concat(ADDITIONAL)
it "serializes _all_ the ... |
Use Monitor for recursive locking | require "mamiya/version"
require 'thread'
module Mamiya
@chdir_mutex = Thread::Mutex.new
def self.chdir(dir, &block)
@chdir_mutex.synchronize do
Dir.chdir(dir, &block)
end
end
end
| require "mamiya/version"
require 'thread'
module Mamiya
@chdir_monitor = Monitor.new
def self.chdir(dir, &block)
@chdir_monitor.synchronize do
Dir.chdir(dir, &block)
end
end
end
|
Support for embedding YouTube links to particular times | module Onebox
module Engine
class YoutubeOnebox
include Engine
include StandardEmbed
matches_regexp /^https?:\/\/(?:www\.)?(?:youtube\.com|youtu\.be)\/.+$/
def to_html
rewrite_agnostic(append_embed_wmode(raw[:html]))
end
def append_embed_wmode(html)
html.gsub... | module Onebox
module Engine
class YoutubeOnebox
include Engine
include StandardEmbed
matches_regexp /^https?:\/\/(?:www\.)?(?:youtube\.com|youtu\.be)\/.+$/
def to_html
rewrite_agnostic(append_params(raw[:html]))
end
def append_params(html)
result = html.dup
... |
Add test for addition fix | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Schema::Addition do
it "handles duplicate types with cycles" do
duplicate_types_schema = Class.new(GraphQL::Schema)
duplicate_types = 2.times.map {
Class.new(GraphQL::Schema::Object) do
graphql_name "Thing"
field :thi... | |
Use ruby core securerandom as it's removed from latest activesupport | require 'active_support/secure_random'
module ActiveMerchant #:nodoc:
module Utils #:nodoc:
def generate_unique_id
SecureRandom.hex(16)
end
module_function :generate_unique_id
def deprecated(message)
warn(Kernel.caller[1] + message)
end
end
end
| require 'securerandom'
module ActiveMerchant #:nodoc:
module Utils #:nodoc:
def generate_unique_id
SecureRandom.hex(16)
end
module_function :generate_unique_id
def deprecated(message)
warn(Kernel.caller[1] + message)
end
end
end
|
Prepend `/` to notification links. | class Notify
def self.everyone(submission, from, about)
(submission.participants - [from]).each do |to|
new(submission, to, from, about).save
end
end
def self.source(submission, from, about)
new(submission, to, from, about).save
end
attr_reader :submission, :to, :from, :about
def initia... | class Notify
def self.everyone(submission, from, about)
(submission.participants - [from]).each do |to|
new(submission, to, from, about).save
end
end
def self.source(submission, from, about)
new(submission, to, from, about).save
end
attr_reader :submission, :to, :from, :about
def initia... |
Upgrade Reflector.app to v 2.2.0 | cask :v1 => 'reflector' do
version '2.1.0.0'
sha256 'eda358fec24270e823bd46441ab39e434a616752cd0d5f02456871ee1f870af9'
url "http://download.airsquirrels.com/Reflector2/Mac/Reflector-#{version}.dmg"
appcast 'https://updates.airsquirrels.com/Reflector2/Mac/Reflector2.xml'
name 'Reflector 2'
homepage 'http://... | cask :v1 => 'reflector' do
version '2.2.0'
sha256 '2a35b89d7b5181c2a26c9f587b92e6ee9865facce869409aa81f471e2ae0d920'
url "http://download.airsquirrels.com/Reflector2/Mac/Reflector-#{version}.dmg"
appcast 'https://updates.airsquirrels.com/Reflector2/Mac/Reflector2.xml'
name 'Reflector 2'
homepage 'http://ww... |
Add description and summary to gemspec. | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'simple_webmon/version'
Gem::Specification.new do |spec|
spec.name = "simple_webmon"
spec.version = SimpleWebmon::VERSION
spec.authors = ["Mike Admire"]
spec.email ... | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'simple_webmon/version'
Gem::Specification.new do |spec|
spec.name = "simple_webmon"
spec.version = SimpleWebmon::VERSION
spec.authors = ["Mike Admire"]
spec.email ... |
Remove absolute paths from the manifest | if defined?(CompatResource::GEMSPEC)
raise "Already loaded ChefCompat from #{CompatResource::GEMSPEC.require_path}/compat_resource/gemspec.rb. Cannot load a second time from #{__FILE__}"
end
require_relative 'version'
module CompatResource
GEMSPEC = Gem::Specification.new do |s|
# Gem path is cookbook root
... | if defined?(CompatResource::GEMSPEC)
raise "Already loaded ChefCompat from #{CompatResource::GEMSPEC.require_path}/compat_resource/gemspec.rb. Cannot load a second time from #{__FILE__}"
end
require_relative 'version'
module CompatResource
GEMSPEC = Gem::Specification.new do |s|
# Gem path is cookbook root
... |
Mark the failing (boilerplate) test as pending | require 'spec_helper'
describe Roomy do
it 'has a version number' do
expect(Roomy::VERSION).not_to be nil
end
it 'does something useful' do
expect(false).to eq(true)
end
end
| require 'spec_helper'
describe Roomy do
it 'has a version number' do
expect(Roomy::VERSION).not_to be nil
end
xit 'does something useful' do
expect(false).to eq(true)
end
end
|
Add missing columns to Spree::Konbini | class AddGatewayProfileIdsToSpreeKonbinis < ActiveRecord::Migration
def change
add_column :spree_konbinis, :gateway_customer_profile_id, :string
add_column :spree_konbinis, :gateway_payment_profile_id, :string
end
end
| |
Add secret token to dummy app | # Be sure to restart your server when you modify this file.
# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to diction... | |
Return prefecture name instead of region name | class DojosController < ApplicationController
def index
@dojo_data = []
Dojo.all.each do |dojo|
@dojo_data << {
url: dojo.url,
name: dojo.name,
order: dojo.order,
prefecture: dojo.prefecture.region,
linked_text: "<a href='#{dojo.url}'>#{dojo.... | class DojosController < ApplicationController
def index
@dojo_data = []
Dojo.all.each do |dojo|
@dojo_data << {
url: dojo.url,
name: dojo.name,
order: dojo.order,
prefecture: dojo.prefecture.name,
linked_text: "<a href='#{dojo.url}'>#{dojo.na... |
Fix rest_client dependency in gemspec. | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require './lib/cloudbit_client'
Gem::Specification.new do |spec|
spec.name = "cloudbit_client"
spec.version = CloudbitClient::VERSION
spec.authors = ["Brian Kelly"]
spec.emai... | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require './lib/cloudbit_client'
Gem::Specification.new do |spec|
spec.name = "cloudbit_client"
spec.version = CloudbitClient::VERSION
spec.authors = ["Brian Kelly"]
spec.emai... |
Update for Rails 4 compatibility | module Spree
class Gateway::UsaEpay < Gateway
preference :source_key, :string
preference :pin, :string
attr_accessible :preferred_source_key, :preferred_pin, :gateway_payment_profile_id
def provider_class
SpreeUsaEpay::Client
end
def payment_profiles_supported?
true
end
... | module Spree
class Gateway::UsaEpay < Gateway
preference :source_key, :string
preference :pin, :string
def provider_class
SpreeUsaEpay::Client
end
def payment_profiles_supported?
true
end
def create_profile(payment)
amount = (payment.amount * 100).round
creditcar... |
Revert "Fix cookie domain problems by specifying domains manually" | # Be sure to restart your server when you modify this file.
options = if Rails.env.production?
{domain: ['.glowfic.com', '.glowfic-staging.herokuapp.com']}
elsif Rails.env.development?
{domain: '.localhost'}
else
{}
end
Rails.application.config.session_store :cookie_store, key: '_glowfic_constellation_' + Rails... | # Be sure to restart your server when you modify this file.
options = if Rails.env.production?
{domain: 'glowfic.com', tld_length: 2}
elsif Rails.env.development?
{domain: 'localhost', tld_length: 2}
else
{}
end
Rails.application.config.session_store :cookie_store, key: '_glowfic_constellation_' + Rails.env, **... |
Create tests to 'test an answer' feature | require 'rails_helper'
describe "Test an answer", type: :feature, js: true do
let(:user) { create(:user, :teacher) }
let(:exercise) { create(:exercise, user: user) }
let!(:question) { create(:question, exercise: exercise) }
subject(:submit_answer) { click_on "Submeter resposta" }
before do
login_as use... | |
Include DSL and RSpecMatchers into system specs by default | # frozen_string_literal: true
require 'rspec/core'
require 'capybara/dsl'
require 'capybara/rspec/matchers'
require 'capybara/rspec/features'
require 'capybara/rspec/matcher_proxies'
RSpec.configure do |config|
config.include Capybara::DSL, type: :feature
config.include Capybara::RSpecMatchers, type: :feature
c... | # frozen_string_literal: true
require 'rspec/core'
require 'capybara/dsl'
require 'capybara/rspec/matchers'
require 'capybara/rspec/features'
require 'capybara/rspec/matcher_proxies'
RSpec.configure do |config|
config.include Capybara::DSL, type: :feature
config.include Capybara::RSpecMatchers, type: :feature
c... |
Remove stupid comments from experiments | require 'kahuna/event'
require 'kahuna/member_collection'
module Kahuna
class Handler
attr_reader :event, :members
# def self.build
# klass = Class.new(BasicObject) do
# def inspect
# "<handler>"
# end
# klass = self
# define_method(:class) { klass }
# ... | require 'kahuna/event'
require 'kahuna/member_collection'
module Kahuna
class Handler
attr_reader :event, :members
def initialize(data, &block)
@event = Event.new data
unless event.type == 'user'
@members = MemberCollection.new data
end
@action = block_given? ? block : ->(eve... |
Set expiration date to session cookie | # frozen_string_literal: true
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store(
:cookie_store,
key: '_nippo_session',
secure: Rails.env.production?,
)
| # frozen_string_literal: true
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store(
:cookie_store,
key: '_nippo_session',
secure: Rails.env.production?,
expire_after: 30.days,
)
|
Improve method for data load | # 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... | # 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... |
Update Coordinates to use new uppercase constants | class Coordinates
def initialize(window, user)
@window, @user = window, user
@coordinate_text = Gosu::Font.new(@window, Media::Font, 16)
end
def update
@x, @y = @user.x, @user.y
end
def draw
@coordinate_text.draw("#{@x.to_s}, #{@y.to_s}", 416, 300, 1, 1, 1,
Color::... | class Coordinates
def initialize(window, user)
@window, @user = window, user
@coordinate_text = Gosu::Font.new(@window, Media::FONT, 16)
end
def update
@x, @y = @user.x, @user.y
end
def draw
@coordinate_text.draw("#{@x.to_s}, #{@y.to_s}", 416, 300, 1, 1, 1,
Color::... |
Remove warning remeving the method before redefining | require 'abstract_unit'
require 'active_support/subscriber'
class TestSubscriber < ActiveSupport::Subscriber
attach_to :doodle
cattr_reader :events
def self.clear
@@events = []
end
def open_party(event)
events << event
end
private
def private_party(event)
events << event
end
end
# M... | require 'abstract_unit'
require 'active_support/subscriber'
class TestSubscriber < ActiveSupport::Subscriber
attach_to :doodle
cattr_reader :events
def self.clear
@@events = []
end
def open_party(event)
events << event
end
private
def private_party(event)
events << event
end
end
# M... |
Add data type strategy (Tools::DataType) | #
# The DataType strategy uses the data type of any primitive or enum property as the generated data.
#
# This strategy DOES NOT GENERATE VALID DATA agains the given JSON schema
#
module JsonSchema
module Artesano
module Tools
class DataType
def initialize
end
def shape_object(mate... | |
Make sure message does not get sent when no commitee has been selected | class ContactController < ApplicationController
def index
@contact = Contact.new
end
def create
if params[:value].blank? then
contact_params = params[:contact]
mail_array = contact_params[:to_whom] << contact_params[:email]
GroupMailer.anonymous_mail(mail_array, contact_params[:body], conta... | class ContactController < ApplicationController
def index
@contact = Contact.new
end
def create
if params[:value].blank? && !params[:to_whom].blank? then
contact_params = params[:contact]
mail_array = contact_params[:to_whom] << contact_params[:email]
GroupMailer.anonymous_mail(mail_array, ... |
Hide Display Name option choices in profile edit if blank | module Admin::UsersHelper
def get_select(needle, haystack)
return 'selected="selected"' if needle.to_s == haystack.to_s
end
def render_options_for_display_name
options = "<option value='#{@user.login}' #{get_select(@user.name, @user.login)}>#{@user.login}</option>"
options << "<option value='#{@user.... | module Admin::UsersHelper
def get_select(needle, haystack)
return 'selected="selected"' if needle.to_s == haystack.to_s
end
def render_options_for_display_name
options = "<option value='#{@user.login}' #{get_select(@user.name, @user.login)}>#{@user.login}</option>"
options << "<option value='#{@user.... |
Correct `event_host?` with nil check on `@event` | module ApplicationHelper
def admin?
!current_user.nil? and current_user.admin?
end
def event_host?
event_host = nil
unless admin?
else
event_host = EventHost.where("user_id = ? and event_id = ?", current_user.id, @event.id)
end
end
admin? || !event_host.nil?
end
def... | module ApplicationHelper
def admin?
!current_user.nil? and current_user.admin?
end
def event_host?
event_host = nil
unless @event.nil?
unless admin?
event_host = EventHost.where("user_id = ? and event_id = ?", current_user.id, @event.id)
end
end
!@event.nil? && (admin? ||... |
Use tmpdir instead of ./tmp | require "pry"
require "defile"
require "defile/backend_examples"
tmp_path = File.expand_path("tmp", Dir.pwd)
if File.exist?(tmp_path)
raise "temporary path #{tmp_path} already exists, refusing to run tests"
else
RSpec.configure do |config|
config.after :suite do
FileUtils.rm_rf(tmp_path)
end
end
e... | require "pry"
require "defile"
require "defile/backend_examples"
tmp_path = Dir.mktmpdir
at_exit do
FileUtils.remove_entry_secure(tmp_path)
end
Defile.store = Defile::Backend::FileSystem.new(File.expand_path("default_store", tmp_path))
Defile.cache = Defile::Backend::FileSystem.new(File.expand_path("default_cache"... |
Update rake and rspec for CVE-2020-8130 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'kartograph/version'
Gem::Specification.new do |spec|
spec.name = "kartograph"
spec.version = Kartograph::VERSION
spec.authors = ["Robert Ross"]
spec.email = [... | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'kartograph/version'
Gem::Specification.new do |spec|
spec.name = "kartograph"
spec.version = Kartograph::VERSION
spec.authors = ["Robert Ross"]
spec.email = [... |
Fix abilities to allow reading users contributions, likes and dislikes | class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.karma.nil?
user.karma = 0
end
can :read, Post, :status => 'published'
can :read, Audio do |audio|
audio.post.published?
end
can :read, Article
can :read, Comment, :status => ['neutral'... | class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.karma.nil?
user.karma = 0
end
can :read, Post, :status => 'published'
can :read, Audio do |audio|
audio.post.published?
end
can :read, Article
can :read, Comment, :status => ['neutral'... |
Fix error in check_ownership when user isn't signed in | class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :load_user, :load_cart_size
protected
def login_needed
if !user_signed_in?
redirect... | class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :load_user, :load_cart_size
protected
def login_needed
if !user_signed_in?
redirect... |
Load rails environment when precompiling assets | require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
if defined?(Bundler)
Bundler.require(:default, :assets, Rails.env)
end
modu... | require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
if defined?(Bundler)
Bundler.require(:default, :assets, Rails.env)
end
modu... |
Add User References to Session Migration | class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :email
t.string :password_digest
t.references :driver_score
t.references :navigator_score
t.references :organization
t.timestamps
end
end
end
| class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :email
t.string :password_digest
t.integer :driver_score
t.integer :navigator_score
t.references :organization
t.timestamps
end
end
end
|
Create a class which can prepare a swingset with frameworks in a directory | #
module SwingSet
# Will add frameworks to a given swingset
class FrameworkDirectory
def initialize(swingset, framework_path)
@swingset = swingset
add_frameworks_from_path(path)
end
def self.carthage_frameworks(swingset, platform = :ios)
path = File.join('Carthage', 'Build')
if ... | |
Add solution for calulate grade | # Calculate a Grade
# I worked on this challenge [by myself, with: ].
# Your Solution Below | # Calculate a Grade
# I worked on this challenge with: Joe Plonsker.
# Your Solution Below
def get_grade(average)
if average >= 90
return "A"
elsif average >= 80
return "B"
elsif average >= 70
return "C"
elsif average >= 60
return "D"
else
return "F"
end
end |
Use local variable instead of method chain | module JsonTestData
class JsonSchema
attr_accessor :schema
def initialize(schema)
@schema = JSON.parse(schema, symbolize_names: true)
end
def generate_example
@schema.fetch(:type) == "object" ? generate_object(schema).to_json : generate_array(schema).to_json
end
private
de... | module JsonTestData
class JsonSchema
attr_accessor :schema
def initialize(schema)
@schema = JSON.parse(schema, symbolize_names: true)
end
def generate_example
@schema.fetch(:type) == "object" ? generate_object(schema).to_json : generate_array(schema).to_json
end
private
de... |
Add test for other form of section heading | require 'test_helper'
class ProjectTest < Test::Unit::TestCase
# setup for test
def setup
@doc = Asciidoc::Document.new(File.readlines(sample_doc_path(:asciidoc_index)))
end
def test_root_name
assert_equal "AsciiDoc Home Page", @doc.root.name
end
def test_is_section_heading
assert @doc.send(:... | require 'test_helper'
class ProjectTest < Test::Unit::TestCase
# setup for test
def setup
@doc = Asciidoc::Document.new(File.readlines(sample_doc_path(:asciidoc_index)))
end
def test_root_name
assert_equal "AsciiDoc Home Page", @doc.root.name
end
def test_is_section_heading
assert @doc.send(:... |
Add wkhtmltopdf for PDFKit. Useful when you cannot install wkhtmltopdf-binary gem | require 'formula'
class WkhtmltopdfOld < Formula
url 'http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9.tar.bz2'
homepage 'http://code.google.com/p/wkhtmltopdf/'
sha256 'e6311c0d398d50c757d43d34f1f63c4b33010441e97d07e92647542419ab1a8b'
depends_on 'qt'
conflicts_with 'wkhtmltopdf', :because => 'Same... | |
Rename attribute removed_by => removed_by_id | module Travis
module Logs
module Services
class FetchLog
def initialize(database: nil)
@database = database || Travis::Logs.database_connection
end
attr_reader :database
private :database
def run(job_id: nil, id: nil)
return nil if job_id.nil? &&... | module Travis
module Logs
module Services
class FetchLog
def initialize(database: nil)
@database = database || Travis::Logs.database_connection
end
attr_reader :database
private :database
def run(job_id: nil, id: nil)
return nil if job_id.nil? &&... |
Test custom mappings for particular indices. | require "test_helper"
require "multi_json"
require "elasticsearch/search_server"
require "elasticsearch/index_group"
class IndexGroupTest < MiniTest::Unit::TestCase
def setup
@server = Elasticsearch::SearchServer.new(
"http://localhost:9200/",
{
"index" => {
"settings" => "awesomen... | require "test_helper"
require "multi_json"
require "elasticsearch/search_server"
require "elasticsearch/index_group"
class IndexGroupTest < MiniTest::Unit::TestCase
def setup
@server = Elasticsearch::SearchServer.new(
"http://localhost:9200/",
{
"index" => {
"settings" => "awesomen... |
Add rate var for blink example. | require 'bundler/setup'
require 'firmata'
board = Firmata::Board.new('/dev/tty.usbmodemfd13131')
board.connect
pin_number = 3
10.times do
board.digital_write pin_number, Firmata::Board::HIGH
puts '+'
board.delay 0.5
board.digital_write pin_number, Firmata::Board::LOW
puts '-'
board.delay 0.5
end | require 'bundler/setup'
require 'firmata'
board = Firmata::Board.new('/dev/tty.usbmodemfd13131')
board.connect
pin_number = 3
rate = 0.5
10.times do
board.digital_write pin_number, Firmata::Board::HIGH
puts '+'
board.delay rate
board.digital_write pin_number, Firmata::Board::LOW
puts '-'
board.delay ra... |
Migrate Lightroom 5.7.1 from homebrew-cask | cask :v1 => 'adobe-photoshop-lightroom' do
version '5.7.1'
sha256 '155a91e2c90927a05ccaa244a99fed4784fa7cf26d08c634f5f111629f6b0418'
url "http://download.adobe.com/pub/adobe/lightroom/mac/#{version.to_i}.x/Lightroom_#{version.to_i}_LS11_mac_#{version.gsub('.','_')}.dmg"
name 'Adobe Photoshop Lightroom'
homep... | |
Use activerecord `values_for_create` to replace `scope_for_create` | module ActiveRecord
module ActsAs
module QueryMethods
def where!(opts, *rest)
if acting_as? && opts.is_a?(Hash)
if table_name_opts = opts.delete(table_name)
opts = opts.merge(table_name_opts)
end
# Filter out the conditions that should be applied to the `ac... | module ActiveRecord
module ActsAs
module QueryMethods
def where!(opts, *rest)
if acting_as? && opts.is_a?(Hash)
if table_name_opts = opts.delete(table_name)
opts = opts.merge(table_name_opts)
end
# Filter out the conditions that should be applied to the `ac... |
Update WSDL URL and start setting ReturnType | require 'savon'
require 'backport_dig'
require 'byebug'
module Asendia
# Handles communication with Asendia API
class Client
WSDL_URL = 'https://demo0884331.mockable.io/?wsdl'.freeze
attr_reader :username, :password, :live
def initialize(username:, password:, live: false)
@username = username
... | require 'savon'
require 'backport_dig'
require 'byebug'
module Asendia
# Handles communication with Asendia API
class Client
WSDL_URL = 'https://reporting-rfc.asendia.co.uk/Heist/externalCom/webservice.cfc?wsdl'.freeze
attr_reader :username, :password, :live
def initialize(username:, password:, live:... |
Define class methods instead of scopes | require "active_record"
module Authem
class Session < ::ActiveRecord::Base
self.table_name = :authem_sessions
belongs_to :subject, polymorphic: true
scope :by_subject, ->(model){ where(subject_type: model.class.name, subject_id: model.id) }
scope :active, ->{ where(arel_table[:expires_at].gteq(Time.... | require "active_record"
module Authem
class Session < ::ActiveRecord::Base
self.table_name = :authem_sessions
belongs_to :subject, polymorphic: true
before_create do
self.token ||= SecureRandom.hex(40)
self.ttl ||= 30.days
self.expires_at ||= ttl_from_now
end
class << self
... |
Optimize row counts for most common browser widths. | class HomeController < ApplicationController
def index
if current_user
@src_sets = SrcSet.active.most_recent(8)
@src_images = SrcImage.without_image.includes(:src_thumb).owned_by(current_user).active.most_recent(6)
@gend_images = GendImage.without_image.includes(:gend_thumb).owned_by(current_us... | class HomeController < ApplicationController
PER_ROW = 7
def index
if current_user
@src_sets = SrcSet.active.most_recent(PER_ROW)
@src_images = SrcImage.without_image.includes(:src_thumb).owned_by(current_user).active.most_recent(PER_ROW)
@gend_images = GendImage.without_image.includes(:gend... |
Fix scoping issue on params | require "ferrety_ferret/version"
require "httparty"
module Ferrety
class Ferret
attr_accessor :alerts
def initialize(params)
clear_alerts
params = parse(params)
end
private
def parse(params)
if params.is_a?(Hash)
params
else
JSON.parse(params)
en... | require "httparty"
module Ferrety
class Ferret
attr_accessor :alerts
def initialize(params)
clear_alerts
@params = parse(params)
end
private
def parse(params)
if params.is_a?(Hash)
params
else
JSON.parse(params)
end
end
def add_alert(ale... |
Add requiring gems to before_configuration | module Kuroko2
class Engine < ::Rails::Engine
isolate_namespace Kuroko2
end
end
| module Kuroko2
class Engine < ::Rails::Engine
isolate_namespace Kuroko2
config.before_configuration do
require 'kaminari'
require 'chrono'
end
end
end
|
Delete vote when it's set to less than or equal to 0. | module PostVoteMethods
module ClassMethods
def recalculate_score(id=nil)
conds = []
cond_params = []
sql = "UPDATE posts AS p SET score = " +
"(SELECT COALESCE(SUM(GREATEST(?, LEAST(?, score))), 0) FROM post_votes v WHERE v.post_id = p.id) "
cond_params << CONFIG["vote_sum_min"]
... | module PostVoteMethods
module ClassMethods
def recalculate_score(id=nil)
conds = []
cond_params = []
sql = "UPDATE posts AS p SET score = " +
"(SELECT COALESCE(SUM(GREATEST(?, LEAST(?, score))), 0) FROM post_votes v WHERE v.post_id = p.id) "
cond_params << CONFIG["vote_sum_min"]
... |
Fix NPR for assets that are not initialized | class BasicReportRow
attr_accessor :key, :count, :replacement_cost, :id_list
def initialize(key)
self.key = key
self.count = 0
self.replacement_cost = 0
self.id_list = []
end
def add(asset)
self.count += 1
self.replacement_cost += asset.replacement_cost
self.id_list << asse... | class BasicReportRow
attr_accessor :key, :count, :replacement_cost, :id_list
def initialize(key)
self.key = key
self.count = 0
self.replacement_cost = 0
self.id_list = []
end
def add(asset)
self.count += 1
self.replacement_cost += asset.replacement_cost unless asset.replacement... |
Fix missing tagging_counts attribute bringing migration from gem | # This migration comes from acts_as_taggable_on_engine (originally 3)
class AddTaggingsCounterCacheToTags < ActiveRecord::Migration
def self.up
add_column :tags, :taggings_count, :integer, default: 0
ActsAsTaggableOn::Tag.reset_column_information
ActsAsTaggableOn::Tag.find_each do |tag|
ActsAsTagga... | |
Add safeguard for scenarios where supported_currencies is nil | module Spree
module Admin
class PricesController < ResourceController
belongs_to 'spree/product', find_by: :slug
helper_method :supported_currencies_for_all_stores
def create
params.require(:vp).permit!
params[:vp].each do |variant_id, prices|
next unless variant_id
... | module Spree
module Admin
class PricesController < ResourceController
belongs_to 'spree/product', find_by: :slug
helper_method :supported_currencies_for_all_stores
def create
params.require(:vp).permit!
params[:vp].each do |variant_id, prices|
next unless variant_id
... |
Include request headers in payments | module SpreeKomoju
module ControllerHelpers
def permitted_source_attributes
super.push(permitted_komoju_konbini_attributes)
super.push(permitted_komoju_banktransfer_attributes)
super.push(permitted_komoju_pay_easy_attributes)
super.push(permitted_komoju_web_money_attributes)
super.fl... | module SpreeKomoju
module ControllerHelpers
extend ActiveSupport::Concern
included do
before_action :add_request_env_to_payments, only: :update
end
def permitted_source_attributes
super.push(permitted_komoju_konbini_attributes)
super.push(permitted_komoju_banktransfer_attributes)
... |
Print some logs, and actually call the correct method | require 'travis'
require 'travis/pro'
class Arf
class Listener
STATUSES = {
broken: ->(build, _) { build.failed? || build.errored? },
fixed: ->(previous_build, event) { (previous_build.failed? || previous_build.errored?) && event.build.passed? }
}
attr_reader :travis_org
def initializ... | require 'travis'
require 'travis/pro'
class Arf
class Listener
STATUSES = {
broken: ->(build, _) { build.failed? || build.errored? },
fixed: ->(previous_build, event) { (previous_build.failed? || previous_build.errored?) && event.build.passed? }
}
attr_reader :travis_org
def initializ... |
Disable Lita v3 compatibility mode | require "simplecov"
require "coveralls"
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
SimpleCov.start { add_filter "/spec/" }
require "lita-wikipedia"
require "lita/rspec"
| require "simplecov"
require "coveralls"
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
SimpleCov.start { add_filter "/spec/" }
require "lita-wikipedia"
require "lita/rspec"
Lita.version_3_compatibility_mode = false
|
Use an old rake release for 1.9.2 and 1.8.7 | require './lib/syntax/version'
Gem::Specification.new "syntax", Syntax::Version::STRING do |s|
s.summary = "Perform simple syntax highlighting."
s.description = "Syntax is Ruby library for performing simple syntax highlighting."
s.files = Dir["LICENSE", "README.rdoc", "CHANGELOG", "lib/**/*"]
s.author = "Jamis... | require './lib/syntax/version'
Gem::Specification.new "syntax", Syntax::Version::STRING do |s|
s.summary = "Perform simple syntax highlighting."
s.description = "Syntax is Ruby library for performing simple syntax highlighting."
s.files = Dir["LICENSE", "README.rdoc", "CHANGELOG", "lib/**/*"]
s.author = "Jamis... |
Add ox, oj and google-protobuf to tested gems | # frozen_string_literal: true
# Components we want to test
gem 'rails_migrate_mutex'
gem 'puma'
gem 'rack-timeout'
gem 'sidekiq'
gem 'clockwork'
# Ensure that gems with C lib dependencies work
gem 'sqlite3'
gem 'pg'
gem 'mysql2'
gem 'nokogiri'
gem 'sassc'
# Ensure that git works
gem 'currencies', git: 'https://github... | # frozen_string_literal: true
# Components we want to test
gem 'rails_migrate_mutex'
gem 'puma'
gem 'rack-timeout'
gem 'sidekiq'
gem 'clockwork'
# Ensure that gems with C lib dependencies work
gem 'sqlite3'
gem 'pg'
gem 'mysql2'
gem 'nokogiri'
gem 'sassc'
gem 'google-protobuf'
gem 'ox'
gem 'oj'
# Ensure that git work... |
Allow analyzer to fetch external specs | module Pod
class Command
class Dependencies < Command
self.summary = "Show project's dependency graph."
self.description = <<-DESC
Shows the project's dependency graph.
DESC
def self.options
[
['--ignore-lockfile', 'whether the lockfile should be ignored when ca... | module Pod
class Command
class Dependencies < Command
self.summary = "Show project's dependency graph."
self.description = <<-DESC
Shows the project's dependency graph.
DESC
def self.options
[
['--ignore-lockfile', 'whether the lockfile should be ignored when ca... |
Use RangeSentenceParser.invalid? instead of instance method | class RangeSentenceValidator < ActiveModel::EachValidator
# Validates whether the value of the specified attribute is of the correct form for RangeSentenceParser.
#
# Usage:
#
# class AccountingReport
# include ActiveModel::Validations
#
# validates :year_sentence, :range_sentence => true
# ... | class RangeSentenceValidator < ActiveModel::EachValidator
# Validates whether the value of the specified attribute is of the correct form for RangeSentenceParser.
#
# Usage:
#
# class AccountingReport
# include ActiveModel::Validations
#
# validates :year_sentence, :range_sentence => true
# ... |
Add slice/except to parameters class | module SmartApi
class ParamsHandler
Converters = {
integer: ->(v) { Integer(v, 10) },
string: ->(v) { String(v) },
float: ->(v) { Float(v) },
date: ->(v) { Date.parse(v) },
time: ->(v) { Time.parse(v) },
bool: ->(v) { v == true || v == "1" || v == "t" },
}
... | module SmartApi
class ParamsHandler
Converters = {
integer: ->(v) { Integer(v, 10) },
string: ->(v) { String(v) },
float: ->(v) { Float(v) },
date: ->(v) { Date.parse(v) },
time: ->(v) { Time.parse(v) },
bool: ->(v) { v == true || v == "1" || v == "t" },
}
... |
Remove rubygems require. Ohm supports Ruby >=1.9. | # encoding: UTF-8
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../lib"))
begin
require "ruby-debug"
rescue LoadError
end
require "rubygems"
require "cutest"
def silence_warnings
original_verbose, $VERBOSE = $VERBOSE, nil
yield
ensure
$VERBOSE = original_verbose
end unless defined?(silence_... | # encoding: UTF-8
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../lib"))
begin
require "ruby-debug"
rescue LoadError
end
require "cutest"
def silence_warnings
original_verbose, $VERBOSE = $VERBOSE, nil
yield
ensure
$VERBOSE = original_verbose
end unless defined?(silence_warnings)
$VERBOSE... |
Fix the same issue rack-throttle had | module Tassadar
module Server
class Whitelist
def initialize(app, addresses)
@app = app
@whitelist = addresses
end
def call(env)
if white_listed?(env)
@app.call(env)
else
[ 403,
{'Content-Type' => 'text/plain; charset=utf-8'},
... | module Tassadar
module Server
class Whitelist
def initialize(app, addresses)
@app = app
@whitelist = addresses
end
def call(env)
if white_listed?(env)
@app.call(env)
else
[ 403,
{ 'Content-Type' => 'text/plain; charset=utf-8' },
... |
Add from parameter on inbox messages | require 'grape'
require './models'
require './entities'
module Mailbooth
class API < Grape::API
format :json
prefix :api
resource :inboxes do
desc 'Return all inboxes.'
get do
inboxes = Models::Inbox.all
present inboxes.to_a, with: Entities::Inbox
end
route_par... | require 'grape'
require './models'
require './entities'
module Mailbooth
class API < Grape::API
format :json
prefix :api
resource :inboxes do
desc 'Return all inboxes.'
get do
inboxes = Models::Inbox.all
present inboxes.to_a, with: Entities::Inbox
end
route_par... |
Remove all instances of :replace_gem, they're no longer needed | module Gemrat
class Arguments
class UnableToParse < StandardError; end
ATTRIBUTES = [:gems, :gemfile, :replace_gem]
ATTRIBUTES.each { |arg| attr_accessor arg }
def initialize(*args)
self.replace_gem = true
self.arguments = *args
validate
extract_options
end
def ... | module Gemrat
class Arguments
class UnableToParse < StandardError; end
ATTRIBUTES = [:gems, :gemfile]
ATTRIBUTES.each { |arg| attr_accessor arg }
def initialize(*args)
self.arguments = *args
validate
extract_options
end
def gems
gem_names.map do |name|
g... |
Use read_multi for the fetching stage | module Knuckles
module Fetcher
extend self
def name
"fetcher".freeze
end
def call(objects, options)
view = options.fetch(:view)
objects.each do |hash|
key = view.cache_key(hash[:object])
res = Knuckles.cache.read(key)
hash[:key] = key
hash[:cached?... | module Knuckles
module Fetcher
extend self
def name
"fetcher".freeze
end
def call(prepared, options)
results = get_cached(prepared, options.fetch(:view))
prepared.each do |hash|
result = results[hash[:key]]
hash[:cached?] = !result.nil?
hash[:result] = resu... |
Add attr_reader for args in Command. | require 'serf/util/with_options_extraction'
module Serf
##
# A base class for Serf users to implement a Command pattern.
#
# class MyCommand < Serf::Command
# def call
# # Do something w/ @request and @opts
# return nil # e.g. MySerfMessage
# end
# protected
# def req... | require 'serf/util/with_options_extraction'
module Serf
##
# A base class for Serf users to implement a Command pattern.
#
# class MyCommand < Serf::Command
# def call
# # Do something w/ @request and @opts
# return nil # e.g. MySerfMessage
# end
# protected
# def req... |
Add spec to document existing money behaviour | require 'spec_helper'
describe DataTable::DataTable do
let(:row) { ['col1', 2] }
before do
subject << { body: [row] }
end
it 'should generate csv' do
expect(subject.to_csv).to eq 'col1,2'
end
it 'should generate html' do
expect(subject.to_html).to eq(
'<table>'\
'<tbody>'\
... | require 'spec_helper'
describe DataTable::DataTable do
let(:row) { ['col1', 2, Money.new(3)] }
let(:money_class) {
Class.new do
def initialize(dollars)
@dollars = dollars
end
def format
"$#{with_places}"
end
def to_s
with_places
end
def with_... |
Use `model_name.name` for event class namespacing | module Hyrax
# A mixin module intended to provide an interface into creating the paper trail
# of activity on the target model of the mixin.
#
# @see Hyrax::Event
module WithEvents
def stream
Nest.new(event_class)[to_param]
end
# @return [String]
def event_class
self.class.name
... | module Hyrax
# A mixin module intended to provide an interface into creating the paper trail
# of activity on the target model of the mixin.
#
# @see Hyrax::Event
module WithEvents
def stream
Nest.new(event_class)[to_param]
end
# @return [String]
def event_class
model_name.name
... |
Change path to own executables | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'panda_doc/version'
Gem::Specification.new do |spec|
spec.name = "panda_doc"
spec.version = PandaDoc::VERSION
spec.platform = Gem::Platform::RUBY
spec.authors = [... | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'panda_doc/version'
Gem::Specification.new do |spec|
spec.name = "panda_doc"
spec.version = PandaDoc::VERSION
spec.platform = Gem::Platform::RUBY
spec.authors = [... |
Update gem dependencies in gemspec | #encoding: utf-8
Gem::Specification.new do |gem|
gem.name = 'devtools'
gem.version = '0.0.1'
gem.authors = [ 'Markus Schirp' ]
gem.email = [ 'mbj@seonic.net' ]
gem.description = 'A metagem for dm-2 style development'
gem.summary = gem.description
gem.homepage = 'https://github... | #encoding: utf-8
Gem::Specification.new do |gem|
gem.name = 'devtools'
gem.version = '0.0.1'
gem.authors = [ 'Markus Schirp' ]
gem.email = [ 'mbj@seonic.net' ]
gem.description = 'A metagem for dm-2 style development'
gem.summary = gem.description
gem.homepage = 'https://github... |
Use `cf-bosh-local` instead of `cf-stackato-local` for Cloud Foundry tests (--> faster!) | require 'spec/adapter/adapter_spec_helper'
describe Paasal::Adapters::V1::CloudFoundryAdapter do
before do
@endpoint = 'cf-stackato-local'
@api_version = 'v1'
@adapter = load_adapter(@endpoint, @api_version)
@application_region = 'default'
@application_params = { memory: 256.to_i }
end
conte... | require 'spec/adapter/adapter_spec_helper'
describe Paasal::Adapters::V1::CloudFoundryAdapter do
before do
@endpoint = 'cf-bosh-local'
@api_version = 'v1'
@adapter = load_adapter(@endpoint, @api_version)
@application_region = 'default'
@application_params = { memory: 256.to_i }
end
context '... |
Add an actual FFI interface for the library | module Cdistance
extend FFI::Library
ffi_lib FFI::Library::LIBC
attach_function :puts, [ :string ], :int
end
| require 'bundler/setup'
require 'ffi'
module Cdistance
extend FFI::Library
lib_file = File.expand_path('../ext/cdistance/cdistance', File.dirname(__FILE__))
if FFI::Platform.mac?
lib_file << '.bundle'
end
ffi_lib FFI.map_library_name(lib_file)
def self.distance(point1, point2)
geo_point1 = GeoP... |
Use ActiveSupport lazy load hook to initialize ActiveRecord | require "active_record"
require "shibaraku/active_record_ext"
module Shibaraku
end
ActiveRecord::Base.include(Shibaraku::ActiveRecordExt)
| require "active_record"
require "shibaraku/active_record_ext"
module Shibaraku
end
ActiveSupport.on_load :active_record do
ActiveRecord::Base.include(Shibaraku::ActiveRecordExt)
end
|
Fix regexp for cache without expiry | module CacheComment
class CommentFormatter
def initialize key, options
@key = key
@options = (options || {}).symbolize_keys
@time = Time.now
end
def start
comment = ['cached']
comment << @time
comment << 'with key'
comment << @key
if expires_in = @opti... | module CacheComment
class CommentFormatter
def initialize key, options
@key = key
@options = (options || {}).symbolize_keys
@time = Time.now
end
def start
comment = ['cached']
comment << @time
comment << 'with key'
comment << @key
if expires_in = @opti... |
Add notes for the configure block | require "active_support/core_ext"
require 'plugins'
require 'caller'
require 'exceptions'
#
# This middleware is the basis of all tracking via rack middleware.
#
# It allows you to easily create your own tracker and simply plugin it into Rack::Tracker allowing you to gain
# valuable information on the service you are ... | require "active_support/core_ext"
require 'plugins'
require 'caller'
require 'exceptions'
#
# This middleware is the basis of all tracking via rack middleware.
#
# It allows you to easily create your own tracker and simply plugin it into Rack::Tracker allowing you to gain
# valuable information on the service you are ... |
Remove some unecessary test setup | ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'minitest/autorun'
require 'rails/test_help'
require 'rr'
require 'capybara/rails'
require 'clearance/test_unit'
require 'rubygems/package'
require 'shoulda'
require 'helpers/gem_helpers'
I18n.enforce_available_locales ... | ENV["RAILS_ENV"] ||= "test"
require File.expand_path('../../config/environment', __FILE__)
require 'minitest/autorun'
require 'rails/test_help'
require 'rr'
require 'capybara/rails'
require 'clearance/test_unit'
require 'rubygems/package'
require 'shoulda'
require 'helpers/gem_helpers'
I18n.enforce_available_locales... |
Update Silverlight to version 5.1.30317 | class Silverlight < Cask
url 'http://silverlight.dlservice.microsoft.com/download/B/A/9/BA94BEC9-5DBC-4B50-BC2B-046A42399067/30214.00/Silverlight.dmg'
homepage 'http://www.microsoft.com/silverlight/'
version '5.1.30214.0'
sha256 '4b9354d60451b033b4d6695b8d94d8f88663cc8d0b25cebda08b6b4fb0069cba'
install 'Silve... | class Silverlight < Cask
url 'http://silverlight.dlservice.microsoft.com/download/D/6/6/D66CF013-1021-437B-9A65-983871CCB3E6/30317.00/Silverlight.dmg'
homepage 'http://www.microsoft.com/silverlight/'
version '5.1.30317.0'
sha256 'a425c522f84c8c3b2bcfb5f40abab0f8d67733f824be5c0e383819d06f230007'
install 'Silve... |
Add ability to flush per request for local testing. | class ApplicationController < ActionController::Base
protect_from_forgery
end
| class ApplicationController < ActionController::Base
protect_from_forgery
#after_filter :flush_metrics_rails
# manually flush per request
def flush_metrics_rails
Metrics::Rails.flush
end
end
|
Make sure data is loaded before removing file | require 'digest/md5'
require 'yaml'
module Feed2Email
class FeedDataFile
def initialize(uri)
@uri = uri
@dirty = false
end
def uri=(new_uri)
if new_uri != uri
remove_file
mark_dirty
@uri = new_uri
end
end
def sync
open(path, 'w') {|f| f.writ... | require 'digest/md5'
require 'yaml'
module Feed2Email
class FeedDataFile
def initialize(uri)
@uri = uri
@dirty = false
end
def uri=(new_uri)
return if new_uri == uri
data # load data if not already loaded
remove_file
mark_dirty
@uri = new_uri
end
def s... |
Correct syntax for gh markdown | # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'hubdown/version'
Gem::Specification.new do |gem|
gem.name = "hubdown"
gem.version = Hubdown::VERSION
gem.authors = ["jsk"]
gem.email = ["knomedia@gm... | # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'hubdown/version'
Gem::Specification.new do |gem|
gem.name = "hubdown"
gem.version = Hubdown::VERSION
gem.authors = ["jsk"]
gem.email = ["knomedia@gm... |
Update Playback.app to version 1.3.1 | cask :v1 => 'playback' do
version '1.3.0'
sha256 'e161c0589f57f840428e946f3d12301377cdcb9aaba79a5f39c1a5048314b944'
# github.com is the official download host per the vendor homepage
url "https://github.com/mafintosh/playback/releases/download/v#{version}/Playback.app.zip"
appcast 'https://github.com/mafinto... | cask :v1 => 'playback' do
version '1.3.1'
sha256 'bffca6b43363b8a0a511eae6b3376d0bd0fbcf2c04a6d810cf09acbcd087bb38'
# github.com is the official download host per the vendor homepage
url "https://github.com/mafintosh/playback/releases/download/v#{version}/Playback.app.zip"
appcast 'https://github.com/mafinto... |
Use the correct certificate name to sign Mac installer | # The path where the installer will be outputted to
default[:package][:output_dir] = File.expand_path("../../../../dist", __FILE__)
default[:package][:support_dir] = File.expand_path("../../../../support", __FILE__)
# Mac options
default[:package][:mac][:install_location] = "/Applications/Vagrant"
default[:package][:m... | # The path where the installer will be outputted to
default[:package][:output_dir] = File.expand_path("../../../../dist", __FILE__)
default[:package][:support_dir] = File.expand_path("../../../../support", __FILE__)
# Mac options
default[:package][:mac][:install_location] = "/Applications/Vagrant"
default[:package][:m... |
Remove checks on constants that are true. | require 'digest/crc16_ccitt'
module Digest
#
# Implements the CRC16_CCITT algorithm used in QT algorithms.
#
# @author Matthew Bednarski
#
class CRC16QT < CRC16CCITT
FINAL_XOR = 0xffff
REVERSE_CRC_RESULT = true
REVERSE_DATA = true
#
# Updates the CRC16 checksum.
#
# @param [... | require 'digest/crc16_ccitt'
module Digest
#
# Implements the CRC16_CCITT algorithm used in QT algorithms.
#
# @author Matthew Bednarski
#
class CRC16QT < CRC16CCITT
FINAL_XOR = 0xffff
#
# Updates the CRC16 checksum.
#
# @param [String] data
# The data to update the checksum wit... |
Add docs for RSpec extension | require 'resubject'
module Resubject
module RspecHelpers
def self.included(base)
base.instance_eval do
let(:template) do
if defined? ActionView
ActionView::Base.new
else
mock :template
end
end
subject do
described_clas... | require 'resubject'
module Resubject
# RSpec configuration and helpers
#
# This helper automatically creates `subject` and `template`
# variables for RSpec when testing your presenter.
#
# To get this working, create a spec file in `spec/presenters`
# and require `resubject/rspec`. You only need to defin... |
Add some extra comments to explaining everything happening in the code. | # reverse_string.rb
module ReverseString
def self.reverse_string(string)
string.reverse
end
def self.prompt_user
print 'Enter a string to be reversed: '
input_string = gets.chomp
puts self.reverse_string(input_string)
end
end
if __FILE__==$0
ReverseString.prompt_user
end
| # reverse_string.rb
module ReverseString
# basic string reversal, nothing fancy
def self.reverse_string(string)
string.reverse
end
# prompt the user for a string to reverse
def self.prompt_user
print 'Enter a string to be reversed: '
input_string = gets.chomp
puts self.reverse_string(input_... |
Upgrade foodcritic dependency to allow also v2.x | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/guard/foodcritic/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Chris Griego"]
gem.email = ["cgriego@gmail.com"]
gem.description = %q{Guard::Foodcritic automatically runs foodcritic.}
gem.summary = %q{Guard::F... | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/guard/foodcritic/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Chris Griego"]
gem.email = ["cgriego@gmail.com"]
gem.description = %q{Guard::Foodcritic automatically runs foodcritic.}
gem.summary = %q{Guard::F... |
Fix brew audit: sourceforge.io url preferred | class Unfs3 < Formula
desc "User-space NFSv3 server"
homepage "http://unfs3.sourceforge.net"
url "https://downloads.sourceforge.net/project/unfs3/unfs3/0.9.22/unfs3-0.9.22.tar.gz"
sha256 "482222cae541172c155cd5dc9c2199763a6454b0c5c0619102d8143bb19fdf1c"
devel do
url "https://github.com/derfian/unfs3.git"... | class Unfs3 < Formula
desc "User-space NFSv3 server"
homepage "https://unfs3.sourceforge.io"
url "https://downloads.sourceforge.net/project/unfs3/unfs3/0.9.22/unfs3-0.9.22.tar.gz"
sha256 "482222cae541172c155cd5dc9c2199763a6454b0c5c0619102d8143bb19fdf1c"
devel do
url "https://github.com/derfian/unfs3.git"... |
Fix spec & and specs | require 'spec_helper'
RSpec.describe FlexibleConfig::Overview do
subject(:instance) { described_class.new }
specify { expect(subject.call).to be_an Hash }
describe "example category" do
subject { instance.call }
let :expected_output do
"subcategory.wrapped_yaml | | " \... | require 'spec_helper'
RSpec.describe FlexibleConfig::Overview do
subject(:instance) { described_class.new }
specify { expect(subject.call).to be_an Hash }
describe "example category" do
subject { instance.call }
let :expected_output do
"another_sub.short_syntax | | " \... |
Support for being called as delayed job and having a proper request_context. | require 'delayed_job'
module LogStasher
module Delayed
class Plugin < ::Delayed::Plugin
callbacks do |lifecycle|
lifecycle.before(:invoke_job) do |job, *args, &block|
::LogStasher.request_context[:request_id] = job.id
::LogStasher.source = "Delayed::Job"
# perhaps handl... | |
Verify that the exit status won't overflow. | require_relative '../lib/uspec'
extend Uspec
def capture
readme, writeme = IO.pipe
pid = fork do
$stdout.reopen writeme
readme.close
yield
end
writeme.close
output = readme.read
Process.waitpid(pid)
output
end
spec 'catches errors' do
output = capture do
spec 'exception' do
ra... | require_relative '../lib/uspec'
extend Uspec
def capture
readme, writeme = IO.pipe
pid = fork do
$stdout.reopen writeme
readme.close
yield
end
writeme.close
output = readme.read
Process.waitpid(pid)
output
end
spec 'catches errors' do
output = capture do
spec 'exception' do
ra... |
Add Proxy Settings to HTTP connections. | class HttpService < Versioneye::Service
def self.fetch_response url, timeout = 60
uri = URI.parse url
http = Net::HTTP.new uri.host, uri.port
http.read_timeout = timeout # in seconds
if uri.port == 443
http.use_ssl = true
end
path = uri.path
query = uri.query
http.get("#{path}... | class HttpService < Versioneye::Service
def self.fetch_response url, timeout = 60
env = Settings.instance.environment
proxy_addr = GlobalSetting.get env, 'proxy_addr'
proxy_port = GlobalSetting.get env, 'proxy_port'
proxy_user = GlobalSetting.get env, 'proxy_user'
proxy_pass = GlobalSetting.get ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.