Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix `url` stanza comment for Polar WebSync Software. | cask 'polar-websync' do
version '2.8.2'
sha256 '287230ee323cca9887f31e448cbac759c770448e25c31c164b87f69bb3ead9b9'
url "https://www.polarpersonaltrainer.com/downloads/websync_#{version}.dmg"
name 'Polar WebSync Software'
homepage 'https://www.polar.com/us-en/support/downloads/Polar_WebSync_Software'
license... | cask 'polar-websync' do
version '2.8.2'
sha256 '287230ee323cca9887f31e448cbac759c770448e25c31c164b87f69bb3ead9b9'
# polarpersonaltrainer.com was verified as official when first introduced to the cask
url "https://www.polarpersonaltrainer.com/downloads/websync_#{version}.dmg"
name 'Polar WebSync Software'
h... |
Fix AD time interval parsing | module LDAP::Model
module AD
# Difference in seconds between the UNIX Epoch (1970-01-01)
# and the Active Directory Epoch (1601-01-01)
EPOCH_OFFSET = 11644477200
def self.now
(Time.now.to_i + EPOCH_OFFSET) * 10_000_000
end
# number of nanosec / 100, i.e. 10 times the number of microsec... | require 'active_support/core_ext/time/zones'
module LDAP::Model
module AD
# Difference in seconds between the UNIX Epoch (1970-01-01)
# and the Active Directory Epoch (1601-01-01)
EPOCH_OFFSET = Time.utc(1601).to_i
def self.now
((utc.now.to_f - EPOCH_OFFSET) * 10_000_000).to_i
end
# n... |
Check if Rails responds to application before calling it | module Opbeat
# @api private
class Filter
MASK = '[FILTERED]'.freeze
def initialize config
@config = config
@params = rails_filters || config.filter_parameters
end
attr_reader :config
def apply data, opts = {}
case data
when String
apply_to_string data, opts =... | module Opbeat
# @api private
class Filter
MASK = '[FILTERED]'.freeze
def initialize config
@config = config
@params = rails_filters || config.filter_parameters
end
attr_reader :config
def apply data, opts = {}
case data
when String
apply_to_string data, opts =... |
Decrease default batch size to 100. | # encoding: utf-8
class ParallelBatch < ActiveRecord::Base
#####################
### Class methods ###
#####################
def self.find_or_create!
first || create!
# When starting many batches at the same time we are pretty sure to get a MySQL
# error reporting a duplicated entry. That's why we ar... | # encoding: utf-8
class ParallelBatch < ActiveRecord::Base
#####################
### Class methods ###
#####################
def self.find_or_create!
first || create!
# When starting many batches at the same time we are pretty sure to get a MySQL
# error reporting a duplicated entry. That's why we ar... |
Make sure and require the needed helpers | module MetaCon
module Loaders
class RVM
include MetaCon::Loaders::Helpers
include MetaCon::CLIHelpers
def self.ensure(dep, state, proj, v=true)
kind = dep.shift
if kind == 'ruby'
vstr = dep[0].downcase=='head' ? 'ruby-head' : dep.join('-')
switch_ruby(vstr)
... | module MetaCon
module Loaders
class RVM
require 'metacon/loaders/helpers'
include MetaCon::Loaders::Helpers
include MetaCon::CLIHelpers
def self.ensure(dep, state, proj, v=true)
kind = dep.shift
if kind == 'ruby'
vstr = dep[0].downcase=='head' ? 'ruby-head' : dep.... |
Update rubocop requirement from ~> 0.76.0 to ~> 0.77.0 | # frozen_string_literal: true
lib = File.expand_path("lib", __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "tar/version"
Gem::Specification.new do |spec|
spec.name = "tar"
spec.version = Tar::VERSION
spec.authors = ["Andrew Haines"]
spec.email = ["andrew@haines.org.nz"]
spec... | # frozen_string_literal: true
lib = File.expand_path("lib", __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "tar/version"
Gem::Specification.new do |spec|
spec.name = "tar"
spec.version = Tar::VERSION
spec.authors = ["Andrew Haines"]
spec.email = ["andrew@haines.org.nz"]
spec... |
Use stub instead of File.open. Don't create needless file. | require 'spec_helper'
require 'tumblfetch/cli'
describe Tumblfetch::CLI, '#version' do
it 'should print correct version' do
output = capture(:stdout) { subject.version }
expect(output).to include Tumblfetch::VERSION
end
end
describe Tumblfetch::CLI, '#init' do
let(:output) { capture(:stdout) { subject.i... | require 'spec_helper'
require 'tumblfetch/cli'
describe Tumblfetch::CLI, '#version' do
it 'should print correct version' do
output = capture(:stdout) { subject.version }
expect(output).to include Tumblfetch::VERSION
end
end
describe Tumblfetch::CLI, '#init' do
let(:output) { capture(:stdout) { subject.i... |
Make view data use a normalized to lexicon count density. | require "pp"
hash = Marshal.load(File.binread(".andrey"))
outer_count = hash.keys.count
inner_count = 0
hash.each do |key,value|
value.each do |key2, value2|
inner_count += value2
end
end
puts "words in lexicon #{outer_count}"
puts "total transitions #{inner_count}"
require "andreymarkov/markov_table"
x = M... | require "pp"
hash = Marshal.load(File.binread(".andrey"))
outer_count = hash.keys.count
inner_count = 0
hash.each do |key,value|
value.each do |key2, value2|
inner_count += value2
end
end
puts "words in lexicon #{outer_count}"
puts "total transitions #{inner_count}"
require "andreymarkov/markov_table"
x = M... |
Set initial version number to 0.1.0. | Pod::Spec.new do |s|
s.name = "UIAlertController+Show"
s.version = "1.0.0"
s.summary = "Show UIAlertControllers from anywhere."
s.description = <<-DESC
Light-weight extension to UIAlertController to add show method for presenting Alerts / Action Sheets from anywhere
... | Pod::Spec.new do |s|
s.name = "UIAlertController+Show"
s.version = "0.1.0"
s.summary = "Show UIAlertControllers from anywhere."
s.description = <<-DESC
Light-weight extension to UIAlertController to add show method for presenting Alerts / Action Sheets from anywhere
... |
Improve CaseEquality's message a bit | # encoding: utf-8
module Rubocop
module Cop
module Style
# This cop checks for uses of the case equality operator(===).
class CaseEquality < Cop
MSG = 'Avoid the use of the case equality operator(===).'
def on_send(node)
_receiver, method_name, *_args = *node
add... | # encoding: utf-8
module Rubocop
module Cop
module Style
# This cop checks for uses of the case equality operator(===).
class CaseEquality < Cop
MSG = 'Avoid the use of the case equality operator `===`.'
def on_send(node)
_receiver, method_name, *_args = *node
ad... |
Add logic to check to see if input is valid | require 'pry'
require 'sinatra/base'
require_relative 'lib/tictactoe_rules'
require_relative 'lib/tictactoe_board'
require_relative 'lib/comp_player'
require_relative 'lib/web_game_engine'
class TicTacToe < Sinatra::Base
enable :sessions
set :session_secret, "My session secret"
get '/' do
session.clear
... | require 'pry'
require 'sinatra/base'
require_relative 'lib/tictactoe_rules'
require_relative 'lib/tictactoe_board'
require_relative 'lib/comp_player'
require_relative 'lib/web_game_engine'
class TicTacToe < Sinatra::Base
enable :sessions
set :session_secret, "My session secret"
get '/' do
session.clear
... |
Remove unwanted diary entry in the afternoon | # frozen_string_literal: true
# Use this file to easily define all of your cron jobs.
#
# It's helpful, but not entirely necessary to understand cron before proceeding.
# http://en.wikipedia.org/wiki/Cron
# Example:
#
set :output, './log/cron.log'
%w[6:05 9:05 13:05 18:05 23:05 3:05].each do |time|
every :day, at:... | # frozen_string_literal: true
# Use this file to easily define all of your cron jobs.
#
# It's helpful, but not entirely necessary to understand cron before proceeding.
# http://en.wikipedia.org/wiki/Cron
# Example:
#
set :output, './log/cron.log'
%w[6:05 9:05 13:05 18:05 23:05].each do |time|
every :day, at: time... |
Remove explicit dev version dependency. | # -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
require 'guard/cucumber/version'
Gem::Specification.new do |s|
s.name = 'guard-cucumber'
s.version = Guard::CucumberVersion::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ['Michael Kessler']
s.email = ['mich... | # -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
require 'guard/cucumber/version'
Gem::Specification.new do |s|
s.name = 'guard-cucumber'
s.version = Guard::CucumberVersion::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ['Michael Kessler']
s.email = ['mich... |
Replace deprecated File.exists? method with File.exist? | # Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
| # Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
|
Change default search operator from OR to AND. | class SearchController < ApplicationController
INDECES = {
'issues' => { boost: 5 },
'parties' => { boost: 3.5 },
'representatives' => { boost: 2 },
'promises' => { boost: 1 },
'propositions' => { boost: 1 },
'parliament_issues' => { boost: 1 },
... | class SearchController < ApplicationController
INDECES = {
'issues' => { boost: 5 },
'parties' => { boost: 3.5 },
'representatives' => { boost: 2 },
'promises' => { boost: 1 },
'propositions' => { boost: 1 },
'parliament_issues' => { boost: 1 },
... |
Test out enumerations. Looks like no laziness in 1.9.3 | clock = Enumerator.new { |y| loop { y << Time.now.to_f } }
const = Enumerator.new { |y| loop { y << 1 } }
limited = (0..10).to_enum
enums = [clock, const, limited]
loop do
begin
nexts = enums.map { |e| e.next }
puts nexts.inspect
sleep 1
rescue StopIteration
break
end
end
| |
Update to use plain version 3 api, no minor version. SDK-194 | # Copyright (C) 2008-2011 AMEE UK Ltd. - http://www.amee.com
# Released as Open Source Software under the BSD 3-Clause license. See LICENSE.txt for details.
AMEE_API_VERSION = '3.3'
require 'amee/v3/meta_helper'
require 'amee/v3/collection'
require 'amee/v3/connection'
require 'amee/v3/item_definition'
require 'amee/... | # Copyright (C) 2008-2011 AMEE UK Ltd. - http://www.amee.com
# Released as Open Source Software under the BSD 3-Clause license. See LICENSE.txt for details.
AMEE_API_VERSION = '3'
require 'amee/v3/meta_helper'
require 'amee/v3/collection'
require 'amee/v3/connection'
require 'amee/v3/item_definition'
require 'amee/v3... |
Allow data-fp-option-multiple to be specified in the options hash | module Filepicker
module Rails
module FormBuilder
def filepicker_field(method, options = {})
input_options = {
'data-fp-apikey' =>
::Rails.application.config.filepicker_rails.api_key,
'data-fp-button-text' => options.fetch(:button_text, "Pick File"),
'data-... | module Filepicker
module Rails
module FormBuilder
def filepicker_field(method, options = {})
input_options = {
'data-fp-apikey' =>
::Rails.application.config.filepicker_rails.api_key,
'data-fp-button-text' => options.fetch(:button_text, "Pick File"),
'data-... |
Add unit tests to task model. | require 'test_helper'
class TasksTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| require 'test_helper'
class TasksTest < ActiveSupport::TestCase
test "should not create a task without name" do
task = Task.create
assert_not task.save
end
test "should create a task with a true status" do
task = Task.create name: 'my test task'
task.save
assert task.status
task.... |
Change to relax dev deps | lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'tty/tree/version'
Gem::Specification.new do |spec|
spec.name = "tty-tree"
spec.version = TTY::Tree::VERSION
spec.authors = ["Piotr Murach"]
spec.email = [""]
spec.summary ... | lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'tty/tree/version'
Gem::Specification.new do |spec|
spec.name = "tty-tree"
spec.version = TTY::Tree::VERSION
spec.authors = ["Piotr Murach"]
spec.email = ["me@piotrmurach.com"... |
Raise error when file not found | require 'thor'
require 'yaml'
class LastHit
class Cli < Thor
CONFIG_PATH = '~/last_hit.yml'
include Thor::Actions
class << self
def load_config(path)
config = YAML.load_file(File.expand_path(path))
Configure.set(config)
end
end
desc 'init', 'Create config file for l... | require 'thor'
require 'yaml'
class LastHit
class FileNotFound < StandardError; end
class Cli < Thor
CONFIG_PATH = '~/last_hit.yml'
include Thor::Actions
class << self
def load_config(path)
fail(FileNotFound, 'Config file not found')
config = YAML.load_file(File.expand_path(pat... |
Use user ID to avoid nil errors on to_param | class UserDecorator < ApplicationDecorator
delegate_all
def email
object.try :email || "No Email"
end
def email_tag
mail_to email, "Get in touch with #{first_name}"
end
def first_name
object.name.split(" ").first
end
def image
object.try(:image) or asset_path("default_avatar.jpg")
... | class UserDecorator < ApplicationDecorator
delegate_all
def email
object.try :email || "No Email"
end
def email_tag
mail_to email, "Get in touch with #{first_name}"
end
def first_name
object.name.split(" ").first
end
def image
object.try(:image) or asset_path("default_avatar.jpg")
... |
Allow flatten as argument for Dragonfly encode | # frozen_string_literal: true
require "dragonfly_svg"
# Logger
Dragonfly.logger = Rails.logger
# Add model functionality
if defined?(ActiveRecord::Base)
ActiveRecord::Base.extend Dragonfly::Model
ActiveRecord::Base.extend Dragonfly::Model::Validations
end
| # frozen_string_literal: true
require "dragonfly_svg"
# Logger
Dragonfly.logger = Rails.logger
# Add model functionality
if defined?(ActiveRecord::Base)
ActiveRecord::Base.extend Dragonfly::Model
ActiveRecord::Base.extend Dragonfly::Model::Validations
end
# Dragonfly 1.4.0 only allows `quality` as argument to `e... |
Comment out call to jhead for the moment, since it requires a saved version of the file on disk. | require 'RMagick'
module Airbrush
module Processors
module Image
class Rmagick < ImageProcessor
before_filter :purify_image
# after_filter :ensure_rgb_profile
def resize(image, width, height)
img = load(image)
img.change_geometry("#{width}x#{height}") { ... | require 'RMagick'
module Airbrush
module Processors
module Image
class Rmagick < ImageProcessor
before_filter :purify_image
# after_filter :ensure_rgb_profile
def resize(image, width, height)
img = load(image)
img.change_geometry("#{width}x#{height}") { ... |
Use Most Recent Watchman Version | # Must correspond to a valid release here https://github.com/facebook/watchman/releases
default['watchman']['version'] = 'v3.0.0'
| # Must correspond to a valid release here https://github.com/facebook/watchman/releases
default['watchman']['version'] = 'v3.7.0'
|
Store the current user in the thread to allow us to capture that in various models | class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :authenticate_user!, :unless => :devise_controller?
protected
def authenticate_inviter!
authenticate_user! and current_user.role == 'superuser'
end
end
| class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :authenticate_user!, :unless => :devise_controller?
before_filter :set_current_user_in_thread, :if => :user_signed_in?
protected
def set_current_user_in_thread
Thread.current[:current_user] = current_user
en... |
Remove figs dependency from test env | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Load the figs variables before the rest of the bundle
# so we can use env vars in other gems
require 'figs'
# Don't run this initializer on travis.
Figs.load(stage: Rails.env) unless ENV['TRAVIS']
# Require the gems listed in Gemfile, including any ... | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Load the figs variables before the rest of the bundle
# so we can use env vars in other gems
unless Rails.env.test?
require 'figs'
Figs.load(stage: Rails.env)
end
# Require the gems listed in Gemfile, including any gems
# you've limited to :test... |
Update Zotero cask version to 4.0.17. | class Zotero < Cask
url 'http://download.zotero.org/standalone/4.0.16/Zotero-4.0.16.dmg'
homepage 'http://www.zotero.org/'
version '4.0.16'
sha1 '461752e20adb669471063b5ea1c573037d73ada3'
link 'Zotero.app'
end
| class Zotero < Cask
url 'http://download.zotero.org/standalone/4.0.17/Zotero-4.0.17.dmg'
homepage 'http://www.zotero.org/'
version '4.0.17'
sha1 '470365f88714d72a3ef99d4fb3be8b1cdf881d5d'
link 'Zotero.app'
end
|
Add OSX back into podspec file | Pod::Spec.new do |s|
s.name = 'WebViewProxy'
s.version = '0.2.5'
s.summary = 'A standalone iOS & OSX class for intercepting and proxying HTTP requests (e.g. from a Web View)'
s.homepage = 'https://github.com/marcuswestin/WebViewProxy'
s.license = { :type => 'MIT', :file => 'LICENSE'... | Pod::Spec.new do |s|
s.name = 'WebViewProxy'
s.version = '0.2.6'
s.summary = 'A standalone iOS & OSX class for intercepting and proxying HTTP requests (e.g. from a Web View)'
s.homepage = 'https://github.com/marcuswestin/WebViewProxy'
s.license = { :type => 'MIT', :file => 'LICENSE'... |
Upgrade IntelliJ CE EAP to version 14 (build 138.777). | class IntellijIdeaCommunityEap < Cask
url 'http://download.jetbrains.com/idea/ideaIC-135.863.dmg'
homepage 'https://www.jetbrains.com/idea/index.html'
version '135.863'
sha256 '623aac77c3fea84ca6677d5777f7c1c72e3cd5b0ba680d3a465452767e78db89'
link 'IntelliJ IDEA 13 CE EAP.app'
end
| class IntellijIdeaCommunityEap < Cask
url 'http://download.jetbrains.com/idea/ideaIC-138.777.dmg'
homepage 'https://www.jetbrains.com/idea/index.html'
version '138.777'
sha256 '9614d8055051dc418bce905587c33b3d30e164d1eb873d3716b613627a2c52a2'
link 'IntelliJ IDEA 14 CE EAP.app'
end
|
Upgrade Safari Tab Switching to v1.2.7 | class Safaritabswitching < Cask
version '1.2.6'
sha256 'd2823ec2327c5b5e2602876749f6c6ef352cfe7b5498158cc46c5610f6bf9b69'
url "https://github.com/rs/SafariTabSwitching/releases/download/#{version}/Safari.Tab.Switching-#{version}.pkg"
homepage 'https://github.com/rs/SafariTabSwitching'
license :oss
pkg "Sa... | class Safaritabswitching < Cask
version '1.2.7'
sha256 'cda2d24dd7f273d5e26bf3ee32c1e711ebf28c0c44c619fa9f4e7f8efea488ca'
url "https://github.com/rs/SafariTabSwitching/releases/download/#{version}/Safari.Tab.Switching-#{version}.zip"
homepage 'https://github.com/rs/SafariTabSwitching'
license :oss
pkg "Sa... |
Join the name if it's a place | module Geo
class Extractor
def initialize(result)
@result = result
end
def extracted
{
id: result.fetch('_id'),
name: name,
latitude: source.fetch('latitude'),
longitude: source.fetch('longitude'),
type: result.fetch('_type')
}
end
def se... | module Geo
class Extractor
def initialize(result)
@result = result
end
def extracted
{
id: result.fetch('_id'),
name: name,
latitude: source.fetch('latitude'),
longitude: source.fetch('longitude'),
type: type
}
end
def self.to_proc
... |
Add a factory to generate our test github user. | require 'factory_girl'
Factory.define :user do |u|
u.name 'Test User'
u.email 'user@test.com'
u.password 'please'
end
Factory.define :signup do |s|
s.email "test@email.com"
s.contact "true"
end
| require 'factory_girl'
# NOTE: this file does not automatically reload in Rails server. Use load() or restart the server.
Factory.define :user do |u|
u.name 'Test User'
u.email 'user@test.com'
u.password 'please'
end
Factory.define :github_user, :class => User do |u|
# This user doesnt have a username or ema... |
Make list of gem files more specific about file types. | spec = Gem::Specification.new do |s|
s.name = "songkick-oauth2-provider"
s.version = "0.10.0"
s.summary = "Simple OAuth 2.0 provider toolkit"
s.author = "James Coglan"
s.email = "james@songkick.com"
s.homepage = "http://www.songkick.com"
s.... | spec = Gem::Specification.new do |s|
s.name = "songkick-oauth2-provider"
s.version = "0.10.0"
s.summary = "Simple OAuth 2.0 provider toolkit"
s.author = "James Coglan"
s.email = "james@songkick.com"
s.homepage = "http://www.songkick.com"
s.... |
Add power_down and hero_info test | require './hero'
describe Hero do
it "has a capitalize name" do
hero = Hero.new 'mike'
expect(hero.name).to eq 'Mike' # hero.name == 'Mike'
end
it "can power up" do
hero = Hero.new 'mike'
expect(hero.power_up).to eq 110
end
end | require './hero'
describe Hero do
it "has a capitalize name" do
hero = Hero.new 'mike'
expect(hero.name).to eq 'Mike' # hero.name == 'Mike'
end
it "can power up" do
hero = Hero.new 'mike'
expect(hero.power_up).to eq 110
end
it "can power down" do
hero = Hero.new 'mike'
expect(hero.power_down).to... |
Change gemspec.homepage to github repo url | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require 'log4r/version'
# Removed dependency on rake because of error when running `bundle install --deployment`
# There was a LoadError while evaluating log4r.gemspec:
# no such file to load -- rake from
# vendor/bundle/ruby/1.8/bundler/... | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require 'log4r/version'
# Removed dependency on rake because of error when running `bundle install --deployment`
# There was a LoadError while evaluating log4r.gemspec:
# no such file to load -- rake from
# vendor/bundle/ruby/1.8/bundler/... |
Change winelist method to accurately reflect wines for accepted users | class Event < ActiveRecord::Base
has_many :event_wines
has_many :wine_bringers, through: :event_wines
has_many :wines, through: :event_wines
belongs_to :creator, class_name: "User", foreign_key: "user_id"
validates :name, presence: true
validates :location, presence: true
validates :date, presence: true... | class Event < ActiveRecord::Base
has_many :event_wines
has_many :wine_bringers, through: :event_wines
has_many :wines, through: :event_wines
belongs_to :creator, class_name: "User", foreign_key: "user_id"
validates :name, presence: true
validates :location, presence: true
validates :date, presence: true... |
Add a safe file name method | class AssetFile < ActiveRecord::Base
attr_protected :id
belongs_to :account
scope :with_query, lambda { |s| where('name LIKE ? OR file_name LIKE ?', "%#{s}%", "%#{s}%") }
def datastore
return nil unless file
@datastore ||= file.app.datastore
end
def object_url(opts = {})
expires... | class AssetFile < ActiveRecord::Base
attr_protected :id
belongs_to :account
scope :with_query, lambda { |s| where('name LIKE ? OR file_name LIKE ?', "%#{s}%", "%#{s}%") }
def datastore
return nil unless file
@datastore ||= file.app.datastore
end
def object_url(opts = {})
expires... |
Add method comments to `Production::Concat` source | module Calyx
module Production
class Concat
EXPRESSION = /(\{[A-Za-z0-9_@\.]+\})/.freeze
START_TOKEN = '{'.freeze
END_TOKEN = '}'.freeze
DEREF_TOKEN = '.'.freeze
def self.parse(production, registry)
expansion = production.split(EXPRESSION).map do |atom|
if atom.is_... | module Calyx
module Production
class Concat
EXPRESSION = /(\{[A-Za-z0-9_@\.]+\})/.freeze
START_TOKEN = '{'.freeze
END_TOKEN = '}'.freeze
DEREF_TOKEN = '.'.freeze
# Parses an interpolated string into fragments combining terminal strings
# and non-terminal rules.
#
#... |
Fix issue with in-document links | require 'middleman-core/renderers/redcarpet'
class TechDocsHTMLRenderer < Middleman::Renderers::MiddlemanRedcarpetHTML
include Redcarpet::Render::SmartyPants
def image(link, *args)
%(<a href="#{link}" target="_blank" rel="noopener noreferrer">#{super}</a>)
end
def table(header, body)
%(<div class="ta... | require 'middleman-core/renderers/redcarpet'
class TechDocsHTMLRenderer < Middleman::Renderers::MiddlemanRedcarpetHTML
include Redcarpet::Render::SmartyPants
def image(link, *args)
%(<a href="#{link}" target="_blank" rel="noopener noreferrer">#{super}</a>)
end
def table(header, body)
%(<div class="ta... |
Delete patch route for users | Rails.application.routes.draw do
mount RedactorRails::Engine => '/redactor_rails'
resources :snippets
get '/signup', to: 'users#new'
post '/signup', to: 'users#create', as: 'new_sign_up'
patch 'stories/:id/upvote', to: 'votes#upvote', as: 'vote_up'
delete '/vote/:id', to: 'votes#destroy', as: 'vote_delete... | Rails.application.routes.draw do
mount RedactorRails::Engine => '/redactor_rails'
resources :snippets
get '/signup', to: 'users#new'
post '/signup', to: 'users#create', as: 'new_sign_up'
patch 'stories/:id/upvote', to: 'votes#upvote', as: 'vote_up'
delete '/vote/:id', to: 'votes#destroy', as: 'vote_delete... |
Add forgotten attr_accessor to inventory_filename | module VagrantPlugins
module Vai
class Config < Vagrant.plugin("2", :config)
attr_accessor :inventory_dir
attr_accessor :groups
def initialize
@inventory_dir = UNSET_VALUE
@inventory_filename = UNSET_VALUE
@groups = UNSET_VALUE
end
def... | module VagrantPlugins
module Vai
class Config < Vagrant.plugin("2", :config)
attr_accessor :inventory_dir
attr_accessor :inventory_filename
attr_accessor :groups
def initialize
@inventory_dir = UNSET_VALUE
@inventory_filename = UNSET_VALUE
@groups ... |
Add test files to gemspec explicitly | # -*- encoding: utf-8 -*-
Gem::Specification.new do |gem|
gem.name = "rubyapi"
gem.authors = ["Kim Burgestrand"]
gem.email = ["kim@burgestrand.se"]
gem.summary = %q{Access help to the Ruby C library from FFI}
gem.license = "Simplified BSD License"
gem.homepage = "ht... | # -*- encoding: utf-8 -*-
Gem::Specification.new do |gem|
gem.name = "rubyapi"
gem.authors = ["Kim Burgestrand"]
gem.email = ["kim@burgestrand.se"]
gem.summary = %q{Access help to the Ruby C library from FFI}
gem.license = "Simplified BSD License"
gem.homepage = "ht... |
Add ability to hold content in Resource container. | require 'base64'
require 'digest'
module Percy
class Client
# A simple data container object used to pass data to create_snapshot.
class Resource
attr_accessor :sha
attr_accessor :resource_url
attr_accessor :is_root
attr_accessor :mimetype
def initialize(sha, resource_url, opt... | require 'base64'
require 'digest'
module Percy
class Client
# A simple data container object used to pass data to create_snapshot.
class Resource
attr_accessor :sha
attr_accessor :resource_url
attr_accessor :is_root
attr_accessor :mimetype
attr_accessor :content
def init... |
Use build-essential instead of build_essential | node.set['build_essential']['compile_time'] = true
include_recipe 'build-essential'
node['augeas']['packages'].each do |package_name|
package package_name do
action :nothing
end.run_action(:install)
end
chef_gem 'ruby-augeas' do
action :install
end
| node.set['build-essential']['compile_time'] = true
include_recipe 'build-essential'
node['augeas']['packages'].each do |package_name|
package package_name do
action :nothing
end.run_action(:install)
end
chef_gem 'ruby-augeas' do
action :install
end
|
Change Simple.new to be fully namespaced for understandability's sake | require 'spec_helper'
require 'i18n/core_ext'
module I18n
module Backend
RSpec.describe Base do
# Since #load_erb is a protected method, this spec tests the
# interface that calls it: #load_translations
describe '#load_translations' do
let(:translations) do
I18n.backend.instan... | require 'spec_helper'
require 'i18n/core_ext'
module I18n
module Backend
RSpec.describe Base do
# Since #load_erb is a protected method, this spec tests the
# interface that calls it: #load_translations
describe '#load_translations' do
let(:translations) do
I18n.backend.instan... |
Update rspec requirement from = 3.9.0 to = 3.10.0 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ibge/version'
Gem::Specification.new do |spec|
spec.authors = ["Bruno Arueira"]
spec.email = ["contato@brunoarueira.com"]
spec.description = %q{Unofficial gem with a bunch o... | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ibge/version'
Gem::Specification.new do |spec|
spec.authors = ["Bruno Arueira"]
spec.email = ["contato@brunoarueira.com"]
spec.description = %q{Unofficial gem with a bunch o... |
Break if the site begins returning bad data | require "open-uri"
require "json"
# Return a MongoDB-ready hash from a V&A url
def get_object_hash(url)
raw_data = get_json(url)
if raw_data.nil?
return {"_id" => url, "download_error" => true}
else
return fix_fields(raw_data)
end
end
# Retrieve and parse V&A JSON into a hash
def get_json(url)
begin
object... | require "open-uri"
require "json"
# Return a MongoDB-ready hash from a V&A url
def get_object_hash(url)
raw_data = get_json(url)
if raw_data.nil?
return {"_id" => url, "download_error" => true}
else
return fix_fields(raw_data)
end
end
# Retrieve and parse V&A JSON into a hash
def get_json(url)
begin
object... |
Add SourceSuggestions tab to admin interface | ActiveAdmin.register SourceSuggestion do
permit_params :source_id, :user_id, :gene_name, :disease_name, :variant_name, :initial_comment, :status
filter :gene_name
filter :disease_name
filter :variant_name
filter :initial_comment
filter :status, as: :select, collection: ['new', 'curated', 'rejected']
filt... | |
Update podspec for MR 2.3.0-beta.1 | Pod::Spec.new do |s|
s.name = 'MagicalRecord'
s.version = '2.2'
s.license = 'MIT'
s.summary = 'Super Awesome Easy Fetching for Core Data 1!!!11!!!!1!.'
s.homepage = 'http://github.com/magicalpanda/MagicalRecord'
s.author = { 'Saul Mora' => 'saul@magicalpanda.com' }
s.source = { :git => 'https:/... | Pod::Spec.new do |s|
s.name = 'MagicalRecord'
s.version = '2.3.0-beta.1'
s.license = 'MIT'
s.summary = 'Super Awesome Easy Fetching for Core Data 1!!!11!!!!1!.'
s.homepage = 'http://github.com/magicalpanda/MagicalRecord'
s.author = { 'Saul Mora' => 'saul@magicalpanda.com' }
s.source = { :git =>... |
Remove trailing space from a filter generated line | module Compath
class YamlFormatter
attr_accessor :yaml
def initialize(yaml)
@yaml = yaml
end
def format
formatters.each do |formatter|
self.yaml = formatter.call(yaml)
end
yaml
end
def formatters
@formatters ||= [
remove_trailing_space_formatter... | module Compath
class YamlFormatter
attr_accessor :yaml
def initialize(yaml)
@yaml = yaml
end
def format
formatters.each do |formatter|
self.yaml = formatter.call(yaml)
end
yaml
end
def formatters
@formatters ||= [
remove_trailing_space_formatter... |
Make action pack dependency optional | Gem::Specification.new do |s|
s.name = "graphql-client"
s.version = "0.0.18"
s.summary = "GraphQL Client"
s.description = "???"
s.homepage = "https://github.com/github/graphql-client"
s.license = "MIT"
s.files = Dir["README.md", "LICENSE", "lib/**/*.rb"]
# TODO: Make Rails dependencies optional
s.ad... | Gem::Specification.new do |s|
s.name = "graphql-client"
s.version = "0.0.18"
s.summary = "GraphQL Client"
s.description = "???"
s.homepage = "https://github.com/github/graphql-client"
s.license = "MIT"
s.files = Dir["README.md", "LICENSE", "lib/**/*.rb"]
s.add_dependency "activesupport", ">= 3.0", "< ... |
Update Guard dependency to ~> 2.0 | # encoding: utf-8
$:.push File.expand_path('../lib', __FILE__)
require 'guard/test/version'
Gem::Specification.new do |s|
s.name = 'guard-test'
s.version = Guard::TestVersion::VERSION
s.platform = Gem::Platform::RUBY
s.license = 'MIT'
s.author = 'Rémy Coutable'
s.email = 'remy@... | # encoding: utf-8
$:.push File.expand_path('../lib', __FILE__)
require 'guard/test/version'
Gem::Specification.new do |s|
s.name = 'guard-test'
s.version = Guard::TestVersion::VERSION
s.platform = Gem::Platform::RUBY
s.license = 'MIT'
s.author = 'Rémy Coutable'
s.email = 'remy@... |
Fix require for old Ruby | require_relative 'lib/jquery-cdn/version'
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'jquery-cdn'
s.version = JqueryCdn::VERSION
s.summary = 'Best way to use latest jQuery in Ruby app'
s.files = `git ls-files`.split("\n")
s.require_path = 'lib'
s.... | require File.expand_path('../lib/jquery-cdn/version', __FILE__)
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'jquery-cdn'
s.version = JqueryCdn::VERSION
s.summary = 'Best way to use latest jQuery in Ruby app'
s.files = `git ls-files`.split("\n")
s.requi... |
Add bugsnag to API side of things | module ExercismAPI
module Routes
class Core < Sinatra::Application
use Bugsnag::Rack
configure do
set :root, ExercismAPI::ROOT
end
before do
content_type 'application/json', charset: 'utf-8'
end
helpers do
def require_key
unless params[:key]... | module ExercismAPI
module Routes
class Core < Sinatra::Application
use Bugsnag::Rack
configure do
set :root, ExercismAPI::ROOT
enable :raise_errors
end
configure :production do
disable :show_exceptions
end
configure :development do
enable :sho... |
Read stderr if stdout was empty and exit_code != 0 | require 'json'
require 'open3'
module SimCtl
class Executor
class << self
def execute(command)
command = command.flatten.join(' ')
$stderr.puts command if ENV['SIMCTL_DEBUG']
Open3.popen3(command) do |stdin, stdout, stderr, result|
output = stdout.read
raise Stan... | require 'json'
require 'open3'
module SimCtl
class Executor
class << self
def execute(command)
command = command.flatten.join(' ')
$stderr.puts command if ENV['SIMCTL_DEBUG']
Open3.popen3(command) do |stdin, stdout, stderr, result|
output = stdout.read
if result.... |
Add helper method for stripping whitespace off env variables | module Gitlab
class Util
class << self
def get_env(key)
ENV[key]&.strip
end
def set_env(key, value)
ENV[key] = value&.strip
end
def set_env_if_missing(key, value)
ENV[key] ||= value&.strip
end
end
end
end
| |
Add encoding and collation to the db creation. | #
# Cookbook Name:: gitlab
# Recipe:: database_mysql
#
mysql = node['mysql']
gitlab = node['gitlab']
# 5.Database
include_recipe "mysql::server"
include_recipe "database::mysql"
mysql_connection = {
:host => 'localhost',
:username => 'root',
:password => mysql['server_root_password']
}
## Create a user for Gi... | #
# Cookbook Name:: gitlab
# Recipe:: database_mysql
#
mysql = node['mysql']
gitlab = node['gitlab']
# 5.Database
include_recipe "mysql::server"
include_recipe "database::mysql"
mysql_connection = {
:host => 'localhost',
:username => 'root',
:password => mysql['server_root_password']
}
## Create a user for Gi... |
Use line item ship address to create the subscriptions | module Spree
Order.class_eval do
has_many :subscription
def subscription_products
products.subscribable
end
def check_subscriptions!
line_items.map do |li|
if li.product.subscription?
sp = li.product
subscription = find_subscription(user, sp)
if sub... | module Spree
Order.class_eval do
has_many :subscription
def subscription_products
products.subscribable
end
def check_subscriptions!
line_items.map do |li|
if li.product.subscription?
sp = li.product
subscription = find_subscription(user, sp)
if sub... |
Switch to the new version tag. | #
# Author:: Noah Kantrowitz <noah@coderanger.net>
#
# Copyright 2014, Balanced, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | #
# Author:: Noah Kantrowitz <noah@coderanger.net>
#
# Copyright 2014, Balanced, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... |
Fix arguments warnings of `ERB.new` on ruby 3.1 | require 'ec2ssh/ec2_instances'
require 'erb'
require 'stringio'
module Ec2ssh
class Builder
def initialize(container)
@container = container
safe_level = nil
erb_trim_mode = '%-'
@host_lines_erb = ERB.new @container.host_line, safe_level, erb_trim_mode
end
def build_host_lines
... | require 'ec2ssh/ec2_instances'
require 'erb'
require 'stringio'
module Ec2ssh
class Builder
def initialize(container)
@container = container
@host_lines_erb = ERB.new @container.host_line, trim_mode: '%-'
end
def build_host_lines
out = StringIO.new
aws_keys.each do |name, key|
... |
Drop item, type, and invoice value in default LineItem factory. | FactoryGirl.define do
factory :line_item do
quantity "9.99"
price "9.99"
code "MyString"
title "MyString"
description "MyString"
item nil
type ""
invoice nil
end
end
| FactoryGirl.define do
factory :line_item do
quantity "9.99"
price "9.99"
code "MyString"
title "MyString"
description "MyString"
end
end
|
Add attribute "code" to Semester | module KOSapiClient
module Entity
class Semester < BaseEntity
map_data :end_date, Time
map_data :name, MLString
map_data :start_date, Time
end
end
end
| module KOSapiClient
module Entity
class Semester < BaseEntity
map_data :code
map_data :end_date, Time
map_data :name, MLString
map_data :start_date, Time
end
end
end
|
Update podspec so hpple files are included | Pod::Spec.new do |s|
s.name = 'Pluck'
s.version = '0.1'
s.summary = 'Library for grabbing data from OEmbed (and OEmbed-ish) sites'
s.license = 'MIT'
s.homepage = 'https://github.com/zachwaugh/pluck'
s.author = {'Zach Waugh' => 'zwaugh@gmail.com'}
s.source = {:git => ... | Pod::Spec.new do |s|
s.name = 'Pluck'
s.version = '0.1.1'
s.summary = 'Library for grabbing data from OEmbed (and OEmbed-ish) sites'
s.license = 'MIT'
s.homepage = 'https://github.com/zachwaugh/pluck'
s.author = {'Zach Waugh' => 'zwaugh@gmail.com'}
s.source = {:git =... |
Add Test namespace with cleaning to specs | # encoding: utf-8
require 'pathname'
SPEC_ROOT = root = Pathname(__FILE__).dirname
if RUBY_ENGINE == 'ruby' && ENV['COVERAGE'] == 'true'
require 'yaml'
rubies = YAML.load(File.read(SPEC_ROOT.join('../.travis.yml')))['rvm']
latest_mri = rubies.select { |v| v =~ /\A\d+\.\d+.\d+\z/ }.max
if RUBY_VERSION == lat... | # encoding: utf-8
require 'pathname'
SPEC_ROOT = root = Pathname(__FILE__).dirname
if RUBY_ENGINE == 'ruby' && ENV['COVERAGE'] == 'true'
require 'yaml'
rubies = YAML.load(File.read(SPEC_ROOT.join('../.travis.yml')))['rvm']
latest_mri = rubies.select { |v| v =~ /\A\d+\.\d+.\d+\z/ }.max
if RUBY_VERSION == lat... |
Print AR and Arel versions when starting tests | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
#
require 'simplecov'
SimpleCov.start
require 'byebug'
require 'chrono_model'
require 'support/connection'
require 'support/matchers/schema'
require 'support/matchers/table'
require 'support/matchers/column'
require 'support/matchers/index'
require '... | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
#
require 'simplecov'
SimpleCov.start
require 'byebug'
require 'chrono_model'
require 'support/connection'
require 'support/matchers/schema'
require 'support/matchers/table'
require 'support/matchers/column'
require 'support/matchers/index'
require '... |
Read CPU flags from /proc/cpuinfo | module LinuxCPUs
OPTIMIZATION_FLAGS = {
:penryn => '-march=core2 -msse4.1',
:core2 => '-march=core2',
:core => '-march=prescott',
}.freeze
def optimization_flags; OPTIMIZATION_FLAGS; end
# Linux supports x86 only, and universal archs do not apply
def arch_32_bit; :i386; end
def arch_64_bit; :x8... | module LinuxCPUs
OPTIMIZATION_FLAGS = {
:penryn => '-march=core2 -msse4.1',
:core2 => '-march=core2',
:core => '-march=prescott',
}.freeze
def optimization_flags; OPTIMIZATION_FLAGS; end
# Linux supports x86 only, and universal archs do not apply
def arch_32_bit; :i386; end
def arch_64_bit; :x8... |
Make sure a user can't tag a package multiple times with the same tag name | # == Schema Information
#
# Table name: tagging
#
# id :integer not null, primary key
# user_id :integer
# package_id :integer
# tag :string(255)
# created_at :datetime
# updated_at :datetime
#
class Tagging < ActiveRecord::Base
belongs_to :user
belongs_to :package
belongs_to :tag... | # == Schema Information
#
# Table name: tagging
#
# id :integer not null, primary key
# user_id :integer
# package_id :integer
# tag :string(255)
# created_at :datetime
# updated_at :datetime
#
class Tagging < ActiveRecord::Base
belongs_to :user
belongs_to :package
belongs_to :tag... |
Increase limit for facebook requests | require 'forwardable'
require 'mechanize'
require_relative 'crawler'
class ShortCrawler < Crawler
extend Forwardable
def_delegators :@extractor,
:initial_urls, :next_page, :blocks, :news, :comments
PAGES_LIMIT = 50
def all_blocks
all_start_pages = initial_urls.map { |url| @agent.get(url) }.flatten
... | require 'forwardable'
require 'mechanize'
require_relative 'crawler'
class ShortCrawler < Crawler
extend Forwardable
def_delegators :@extractor,
:initial_urls, :next_page, :blocks, :news, :comments
PAGES_LIMIT = 100
def all_blocks
all_start_pages = initial_urls.map { |url| @agent.get(url) }.flatten
... |
Add rspec 2.99 specific logic | class DebugExceptionsJson
module RSpec
module Hook
def self.included(base)
base.instance_eval do
after do |example|
# For RSpec2 compatibility
if ::RSpec::Core::Version::STRING.split('.').first == "3"
example.metadata[:response] = example.instance_exec... | class DebugExceptionsJson
module RSpec
module Hook
def self.included(base)
base.instance_eval do
after do |example|
# For RSpec2 compatibility
if ::RSpec::Core::Version::STRING.start_with?("3.") || ::RSpec::Core::Version::STRING.start_with?("2.99")
exa... |
Remove a `require` from an autoloaded file | # frozen_string_literal: true
require 'thredded/html_pipeline/at_mention_filter'
module Thredded
class AtNotificationExtractor
def initialize(post)
@post = post
end
# @return [Array<Thredded.user_class>]
def run
view_context = Thredded::ApplicationController.new.view_context
# Do no... | # frozen_string_literal: true
module Thredded
class AtNotificationExtractor
def initialize(post)
@post = post
end
# @return [Array<Thredded.user_class>]
def run
view_context = Thredded::ApplicationController.new.view_context
# Do not highlight @-mentions at first, because:
# *... |
Add speaker and talk css to asset initializer | # Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path
# Precompile additional ... | # Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path
# Precompile additional ... |
Patch CanCan deprecated keyword arguments | module CanCanUnauthorizedMessage
# Fix deprecated syntax calling I18n#translate (using keyword args) without using **
def unauthorized_message(action, subject)
keys = unauthorized_message_keys(action, subject)
variables = {:action => action.to_s}
variables[:subject] = (subject.class == Class ? subject :... | |
Load niceql in the test environment So useful for debugging! | # frozen_string_literal: true
require "bundler/setup"
require "pry"
require_relative "../../lib/active_record_where_assoc"
require "active_support"
require_relative "database_setup"
require_relative "schema"
require_relative "models"
module TestHelpers
def self.condition_value_result_for(*source_associations)
... | # frozen_string_literal: true
require "bundler/setup"
require "pry"
require_relative "../../lib/active_record_where_assoc"
require "active_support"
require_relative "database_setup"
require_relative "schema"
require_relative "models"
require "niceql"
module TestHelpers
def self.condition_value_result_for(*source... |
Add a cumulus_bond test recipe | #
# Cookbook Name:: cumulus-test
# Recipe:: bonds
#
# Copyright 2015, Cumulus Networks
#
# All rights reserved - Do Not Redistribute
#
cumulus_bond 'bond0' do
slaves ['swp1-2', 'swp4']
clag_id 42
end
| |
Allow cross origin requests during development | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module DormManagement
class Application < Rails::Application
# Settings in config/environments/* tak... | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module DormManagement
class Application < Rails::Application
# Settings in config/environments/* tak... |
Add HttpLog gem and configuration. |
if defined?(::Bundler)
global_gemset = ENV['GEM_PATH'].split(':').grep(/ruby.*@global/).first
$LOAD_PATH.concat(Dir.glob("#{global_gemset}/gems/*/lib")) if
global_gemset
end
require 'awesome_print'
require 'pry'
require 'pry-byebug'
|
if defined?(::Bundler)
global_gemset = ENV['GEM_PATH'].split(':').grep(/ruby.*@global/).first
$LOAD_PATH.concat(Dir.glob("#{global_gemset}/gems/*/lib")) if
global_gemset
end; nil
require 'awesome_print'
require 'pry'
require 'pry-byebug'
require 'httplog'
HttpLog.configure do |config|
# Enable or disable all... |
Use paths relative to rspec-rails directory in template | $LOAD_PATH.unshift(File.expand_path('../../../lib', __FILE__))
require 'rspec/rails/version'
gem 'rspec-rails', :path => File.expand_path('../../../', __FILE__)
| $LOAD_PATH.unshift(File.expand_path('../lib', __FILE__))
require 'rspec/rails/version'
gem 'rspec-rails', :path => File.expand_path('../', __FILE__)
|
Add spec for exception handling inside ensure block. | require File.dirname(__FILE__) + '/../spec_helper'
require File.dirname(__FILE__) + '/fixtures/ensure'
describe "The ensure keyword" do
it "executes as a result of a throw within it's block" do
i = []
catch(:exit) do
begin
i << :begin
throw :exit
ensure
i << :ensure
... | require File.dirname(__FILE__) + '/../spec_helper'
require File.dirname(__FILE__) + '/fixtures/ensure'
describe "The ensure keyword" do
it "executes as a result of a throw within it's block" do
i = []
catch(:exit) do
begin
i << :begin
throw :exit
ensure
i << :ensure
... |
Update to latest image server version | require 'net/http'
require 'uri'
require 'open-uri'
require 'fileutils'
module ImageServer
class Installer
attr_reader :configuration
def self.install(configuration = ImageServer.configuration)
new(configuration).install
end
def initialize(configuration = ImageServer.configuration)
@con... | require 'net/http'
require 'uri'
require 'open-uri'
require 'fileutils'
module ImageServer
class Installer
attr_reader :configuration
def self.install(configuration = ImageServer.configuration)
new(configuration).install
end
def initialize(configuration = ImageServer.configuration)
@con... |
Remove dep on jruby-openssl; move rspec and rake to dev deps. | # -*- encoding: utf-8 -*-i
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
Gem::Specification.new do |s|
s.name = "cg_role_client"
s.version = "0.5.63"
s.platform = Gem::Platform::RUBY
s.authors = ["CG Labs"]
s.email = ["eng@commongroundpublishing.com"]
... | # -*- encoding: utf-8 -*-i
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
Gem::Specification.new do |s|
s.name = "cg_role_client"
s.version = "0.5.63"
s.platform = Gem::Platform::RUBY
s.authors = ["CG Labs"]
s.email = ["eng@commongroundpublishing.com"]
... |
Write fucking ugly render paragraph method | module ElementsHelper
def render_elements(elements)
elements.each do |element|
partial = find_element_partial(element) ? element.tag : "element"
concat(render(:partial => "elements/#{partial}", :locals => { :element => element }))
end
nil
end
def find_element_partial(element)
@partial... | module ElementsHelper
def render_elements(elements)
elements.each do |element|
partial = find_element_partial(element) ? element.tag : "element"
concat(render(:partial => "elements/#{partial}", :locals => { :element => element }))
end
nil
end
def render_paragraph(element)
# TODO: WR... |
Include multicam stuff by default | require 'kamelopard/classes'
require 'kamelopard/helpers'
require 'kamelopard/geocode'
require 'kamelopard/function'
require 'kamelopard/function_paths'
| require 'kamelopard/classes'
require 'kamelopard/helpers'
require 'kamelopard/geocode'
require 'kamelopard/function'
require 'kamelopard/function_paths'
require 'kamelopard/multicam'
|
Set standard log level to warn | #!/usr/bin/env ruby
require 'chef'
class Chef::Recipe
def from_string(string)
self.instance_eval(string, 'sandwich', 1)
end
end
$client = nil
def rebuild_node
Chef::Config[:solo] = true
$client = Chef::Client.new
$client.run_ohai
$client.build_node
end
def run_chef
rebuild_node
Chef::Log.level =... | #!/usr/bin/env ruby
require 'chef'
class Chef::Recipe
def from_string(string)
self.instance_eval(string, 'sandwich', 1)
end
end
$client = nil
def rebuild_node
Chef::Config[:solo] = true
$client = Chef::Client.new
$client.run_ohai
$client.build_node
end
def run_chef
rebuild_node
run_context = Che... |
Revert "Don't need Faraday middleware at the moment" | $:.push File.expand_path('../lib', __FILE__)
require 'filmbuff/version'
Gem::Specification.new do |s|
s.name = 'filmbuff'
s.version = FilmBuff::VERSION
s.authors = ['Kristoffer Sachse']
s.email = ['hello@kristoffer.is']
s.homepage = 'https://github.com/sachse/filmbuff'
s.summary ... | $:.push File.expand_path('../lib', __FILE__)
require 'filmbuff/version'
Gem::Specification.new do |s|
s.name = 'filmbuff'
s.version = FilmBuff::VERSION
s.authors = ['Kristoffer Sachse']
s.email = ['hello@kristoffer.is']
s.homepage = 'https://github.com/sachse/filmbuff'
s.summary ... |
Use File.join to require examples | require 'end_view'
Dir["#{__FILE__}/../examples/*.rb"].each { |f| require f }
describe EndView do
it 'renders a simple template' do
expect(Foo.new.render).to eq("\n\nHello World\n")
end
it 'renders an inherited template' do
expect(Bar.new.render).to eq("\n\nHello Porridge\n")
end
it 'renders from ... | require 'end_view'
Dir[File.join(__FILE__, '..', 'examples', '*.rb')].each { |f| require f }
describe EndView do
it 'renders a simple template' do
expect(Foo.new.render).to eq("\n\nHello World\n")
end
it 'renders an inherited template' do
expect(Bar.new.render).to eq("\n\nHello Porridge\n")
end
it... |
Make sure we get what we expect. | require 'org.torquebox.torquebox-messaging-client'
class Something
include TorqueBox::Messaging::Backgroundable
always_background :foo
def initialize
@foreground = TorqueBox::Messaging::Queue.new("/queues/foreground")
@background = TorqueBox::Messaging::Queue.new("/queues/background")
end
def foo
... | require 'org.torquebox.torquebox-messaging-client'
class Something
include TorqueBox::Messaging::Backgroundable
always_background :foo
def initialize
@foreground = TorqueBox::Messaging::Queue.new("/queues/foreground")
@background = TorqueBox::Messaging::Queue.new("/queues/background")
end
def foo
... |
Add rest-client to list of chef_gem dependencies | #
# Cookbook Name:: et_fog
# Recipe:: default
#
# Copyright (C) 2013 EverTrue, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... | #
# Cookbook Name:: et_fog
# Recipe:: default
#
# Copyright (C) 2013 EverTrue, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... |
Add support for calculating appcast checkpoint from URLs. | module Hbc
class CLI
class InternalAppcastCheckpoint < InternalUseBase
def self.run(*args)
calculate = args.include? "--calculate"
cask_tokens = cask_tokens_from(args)
raise CaskUnspecifiedError if cask_tokens.empty?
appcask_checkpoint(cask_tokens, calculate)
end
... | module Hbc
class CLI
class InternalAppcastCheckpoint < InternalUseBase
def self.run(*args)
calculate = args.include? "--calculate"
cask_tokens = cask_tokens_from(args)
raise CaskUnspecifiedError if cask_tokens.empty?
if cask_tokens.all? { |t| t =~ %r{^https?://} && t !~ /\.r... |
Use :delete instead of :delete_records | module VestalVersions
# Adds the ability to "reset" (or hard revert) a versioned ActiveRecord::Base instance.
module Reset
extend ActiveSupport::Concern
# Adds the instance methods required to reset an object to a previous version.
module InstanceMethods
# Similar to +revert_to!+, the +reset_to!+... | module VestalVersions
# Adds the ability to "reset" (or hard revert) a versioned ActiveRecord::Base instance.
module Reset
extend ActiveSupport::Concern
# Adds the instance methods required to reset an object to a previous version.
module InstanceMethods
# Similar to +revert_to!+, the +reset_to!+... |
Fix frontend routing in dev | module MnoEnterprise
module Frontend
class Engine < ::Rails::Engine
isolate_namespace MnoEnterprise
# Add assets
config.assets.precompile += %w( mno_enterprise/application_lib.js )
# To be able to load lib/mno_enterprise/concerns/...
config.autoload_paths += Dir["#{config.root}/lib... | module MnoEnterprise
module Frontend
class Engine < ::Rails::Engine
isolate_namespace MnoEnterprise
# Add assets
config.assets.precompile += %w( mno_enterprise/application_lib.js )
# To be able to load lib/mno_enterprise/concerns/...
config.autoload_paths += Dir["#{config.root}/lib... |
Add binary search in ruby | def binary_search(array, num)
low = 0
high = array.size - 1
while low <= high
mid = (low + high) / 2
if (array[mid] == num)
return true
elsif array[mid] < num
low = mid + 1
else
high = mid - 1
end
end
return false
end
# test
puts binary_search([4, 5, 9, 88, 104, 203, 501, 670], 5) | |
Include collection name into metrics name | DependencyDetection.defer do
@name = :moped
depends_on do
defined?(::Moped) and not NewRelic::Control.instance['disable_moped']
end
executes do
NewRelic::Agent.logger.debug 'Installing Moped instrumentation'
end
executes do
Moped::Node.class_eval do
def process_with_newrelic_trace(opera... | DependencyDetection.defer do
@name = :moped
depends_on do
defined?(::Moped) and not NewRelic::Control.instance['disable_moped']
end
executes do
NewRelic::Agent.logger.debug 'Installing Moped instrumentation'
end
executes do
Moped::Node.class_eval do
def process_with_newrelic_trace(opera... |
Use `ActiveSupport.on_load` to extend ActionController and ActionView. | require 'rails'
require 'action_controller'
require 'active_support/all'
require 'rucaptcha/rucaptcha'
require 'rucaptcha/version'
require 'rucaptcha/configuration'
require 'rucaptcha/controller_helpers'
require 'rucaptcha/view_helpers'
require 'rucaptcha/cache'
require 'rucaptcha/engine'
module RuCaptcha
class << s... | require 'rails'
require 'action_controller'
require 'active_support/all'
require 'rucaptcha/rucaptcha'
require 'rucaptcha/version'
require 'rucaptcha/configuration'
require 'rucaptcha/controller_helpers'
require 'rucaptcha/view_helpers'
require 'rucaptcha/cache'
require 'rucaptcha/engine'
module RuCaptcha
class << s... |
Fix method name cannot be setting's key | module RailsSettings
class CachedSettings < Settings
after_commit :rewrite_cache, on: %i(create update)
def rewrite_cache
Rails.cache.write("rails_settings_cached:#{var}", value)
end
after_commit :expire_cache, on: %i(destroy)
def expire_cache
Rails.cache.delete("rails_settings_cached... | module RailsSettings
class CachedSettings < Settings
after_commit :rewrite_cache, on: %i(create update)
def rewrite_cache
Rails.cache.write("rails_settings_cached:#{var}", value)
end
after_commit :expire_cache, on: %i(destroy)
def expire_cache
Rails.cache.delete("rails_settings_cached... |
Remove one more instance of old requirement | require 'rspec/rails/extensions/active_record/base'
# Adds a custom matcher to RSpec to make it easier to make sure your email
# column is valid.
#
# class Person
# include ActiveModel::Validations
#
# validates_as_email :email
#
# def initialize(attributes = {})
# @attributes = attributes
# end... | # Adds a custom matcher to RSpec to make it easier to make sure your email
# column is valid.
#
# class Person
# include ActiveModel::Validations
#
# validates_as_email :email
#
# def initialize(attributes = {})
# @attributes = attributes
# end
#
# def email
# @attributes[:email]
# ... |
Change from spermy to gt or = for railties dependency | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'threejs-rails/version'
Gem::Specification.new do |spec|
spec.name = "threejs-rails"
spec.version = Threejs::Rails::VERSION
spec.authors = ["Marvin Danig"]
spec.email ... | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'threejs-rails/version'
Gem::Specification.new do |spec|
spec.name = "threejs-rails"
spec.version = Threejs::Rails::VERSION
spec.authors = ["Marvin Danig"]
spec.email ... |
Revert "Allow rackspace connections further up the chain" | require 'vcr'
require 'webmock/cucumber'
WebMock.disable_net_connect!(:allow => 'lon.auth.api.rackspacecloud.com')
VCR.configure do |c|
# Automatically filter all secure details that are stored in the environment
ignore_env = %w(
SHLVL RUNLEVEL GUARD_NOTIFY DRB COLUMNS USER LOGNAME
LINES ITERM_PROFILE TOD... | require 'vcr'
require 'webmock/cucumber'
VCR.configure do |c|
# Automatically filter all secure details that are stored in the environment
ignore_env = %w(
SHLVL RUNLEVEL GUARD_NOTIFY DRB COLUMNS USER LOGNAME
LINES ITERM_PROFILE TODO AUTOFEATURE RAILS_ENV
)
(ENV.keys - ignore_env).select { |x| x =~ /\A... |
Fix a deprecation warning of simpleCov | require 'bacon'
require 'bacon/colored_output'
require 'simplecov'
require 'coveralls'
SimpleCov.start do
self.formatter = SimpleCov::Formatter::MultiFormatter[
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
# Exclude the testsuite itself.
add_filter "/test/"
end
require 'ast... | require 'bacon'
require 'bacon/colored_output'
require 'simplecov'
require 'coveralls'
SimpleCov.start do
self.formatter = SimpleCov::Formatter::MultiFormatter.new([
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
])
# Exclude the testsuite itself.
add_filter "/test/"
end
requir... |
Update createing post spec with new validations/passing | require 'rails_helper.rb'
feature 'Save valid posts only' do
def attempt_to_post_with (options={})
options[:title] ||= "My valid post"
options[:content] ||= 'My valid post content'
visit '/posts/new'
fill_in 'Title', with: options[:title]
fill_in 'Content', with: options[:content]
click_butto... | require 'rails_helper.rb'
feature 'Save valid posts only' do
def attempt_to_post_with (options={})
options[:title] ||= "My valid post"
options[:content] ||= 'My valid post content'
visit '/posts/new'
fill_in 'Title', with: options[:title]
fill_in 'Content', with: options[:content]
click_butto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.