Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Modify fix to include prefix. | Document.record_timestamps = false
documents = Document.where("body like '%whitehall.staging%'")
documents.each do |document|
fixed_body = document.body.gsub(/whitehall\.staging/, "whitehall.preview")
document.update_attribute(:body, fixed_body)
puts "Updated document #{document.id}"
end | Document.record_timestamps = false
documents = Document.where("body like '%whitehall.preview.alphagov.co.uk/admin%'")
documents.each do |document|
fixed_body = document.body.gsub(/whitehall\.preview\.alphagov\.co\.uk\/admin/, "whitehall.preview.alphagov.co.uk/#{Whitehall.router_prefix}/admin")
document.update_attribute(:body, fixed_body)
puts "Updated document #{document.id}"
end |
Add memoization to methods generated by `setting` DSL | require 'ostruct'
module Twigg
# Simple OpenStruct subclass with some methods overridden in order to provide
# more detailed feedback in the event of a misconfiguration, or to provide
# reasonable default values.
#
# For example, we override `#repositories_directory` so that we can report to
# the user that:
#
# - the setting is missing from the configuration file
# - the setting does not point at a directory
#
# We override `#bind` so that we can supply a reasonable default when the
# configuration file has no value set.
class Settings < OpenStruct
class << self
# DSL method which creates a reader for the setting `name`. If the
# configuration file does not contain a value for the setting, return
# `options[:default]` from the `options` hash.
def setting(name, options = {})
define_method name do
self.[](name) || options[:default]
end
end
end
setting :bind, default: '0.0.0.0'
def repositories_directory
@repositories_directory ||= self.[](__method__).tap do |dir|
raise ArgumentError, "#{__method__} not set" unless dir
raise ArgumentError, "#{__method__} not a directory" unless File.directory?(dir)
end
end
end
end
| require 'ostruct'
module Twigg
# Simple OpenStruct subclass with some methods overridden in order to provide
# more detailed feedback in the event of a misconfiguration, or to provide
# reasonable default values.
#
# For example, we override `#repositories_directory` so that we can report to
# the user that:
#
# - the setting is missing from the configuration file
# - the setting does not point at a directory
#
# We override `#bind` so that we can supply a reasonable default when the
# configuration file has no value set.
class Settings < OpenStruct
class << self
# DSL method which creates a reader for the setting `name`. If the
# configuration file does not contain a value for the setting, return
# `options[:default]` from the `options` hash.
def setting(name, options = {})
define_method name do
value = instance_variable_get("@#{name}")
return value if value
instance_variable_set("@#{name}", self.[](name) || options[:default])
end
end
end
setting :bind, default: '0.0.0.0'
def repositories_directory
@repositories_directory ||= self.[](__method__).tap do |dir|
raise ArgumentError, "#{__method__} not set" unless dir
raise ArgumentError, "#{__method__} not a directory" unless File.directory?(dir)
end
end
end
end
|
Correct matcher actions causing ChefSpec failures | if defined?(ChefSpec)
def create_elasticsearch(resource_name)
ChefSpec::Matchers::ResourceMatcher.new(:elasticsearch, :create, resource_name)
end
def delete_elasticsearch(resource_name)
ChefSpec::Matchers::ResourceMatcher.new(:elasticsearch, :delete, resource_name)
end
end
| if defined?(ChefSpec)
def install_elasticsearch(resource_name)
ChefSpec::Matchers::ResourceMatcher.new(:elasticsearch, :install, resource_name)
end
def remove_elasticsearch(resource_name)
ChefSpec::Matchers::ResourceMatcher.new(:elasticsearch, :remove, resource_name)
end
end
|
Add initial fixtures for CI builds | Gitlab::Seeder.quiet do
project = Project.first
commits = project.repository.commits('master', nil, 10)
commits_sha = commits.map { |commit| commit.raw.id }
ci_commits = commits_sha.map do |sha|
project.ensure_ci_commit(sha)
end
ci_commits.each do |ci_commit|
ci_commit.create_builds('master', nil, User.first)
end
end
| |
Add support for validating IPv6 address | module ParsleySimpleForm
module Validators
module IPAddress
def initialize(options)
@parsley_name = 'ipaddress'
super
end
def validate_each(record, attribute, value)
record.errors[attribute] << (options[:message] || 'is not a valid IP address') unless value =~ Resolv::IPv4::Regex
end
def attribute_validate(*args)
options = args.extract_options!
options[:message] = :invalid
type = options[:validate].options[:type]
{ 'parsley-ipaddress': type, 'parsley-ipaddress-message': parsley_error_message(options) }
end
end
end
end
module ActiveRecord
module Validations
class IpaddressValidator < ActiveModel::EachValidator
include ParsleySimpleForm::Validators::IPAddress
end
end
end
| module ParsleySimpleForm
module Validators
module IPAddress
def initialize(options)
@parsley_name = 'ipaddress'
super
end
def validate_each(record, attribute, value)
case options[:type]
when :ipv4
record.errors[attribute] << (options[:message] || 'is not a valid IP address') unless value =~ Resolv::IPv4::Regex
when :ipv6
record.errors[attribute] << (options[:message] || 'is not a valid IP address') unless value =~ Resolv::IPv6::Regex
else
record.errors[attribute] << (options[:message] || 'is not a valid IP address')
end
end
def attribute_validate(*args)
options = args.extract_options!
options[:message] = :invalid
type = options[:validate].options[:type]
{ 'parsley-ipaddress': type, 'parsley-ipaddress-message': parsley_error_message(options) }
end
end
end
end
module ActiveRecord
module Validations
class IpaddressValidator < ActiveModel::EachValidator
include ParsleySimpleForm::Validators::IPAddress
end
end
end
|
Use single quotes for uninterpolated strings | require "tmpdir"
module Bosh::Director
class TarGzipper
include Bosh::RunsCommands
SourceNotFound = Class.new(RuntimeError)
SourceNotAbsolute = Class.new(RuntimeError)
def compress(sources, dest)
source_paths = [*sources].map { |s| Pathname.new(s) }
source_paths.each do |source|
unless source.exist?
raise SourceNotFound.new("The source directory #{source} could not be found.")
end
unless source.absolute?
raise SourceNotAbsolute.new("The source directory #{source} is not an absolute path.")
end
end
Dir.mktmpdir("bosh_tgz") do |filename|
source_paths.each do |source_path|
FileUtils.cp_r(source_path, filename)
end
sh "tar -z -c -f #{dest} #{filename}"
end
end
end
end
| require 'tmpdir'
module Bosh::Director
class TarGzipper
include Bosh::RunsCommands
SourceNotFound = Class.new(RuntimeError)
SourceNotAbsolute = Class.new(RuntimeError)
def compress(sources, dest)
source_paths = [*sources].map { |s| Pathname.new(s) }
source_paths.each do |source|
unless source.exist?
raise SourceNotFound.new("The source directory #{source} could not be found.")
end
unless source.absolute?
raise SourceNotAbsolute.new("The source directory #{source} is not an absolute path.")
end
end
Dir.mktmpdir('bosh_tgz') do |filename|
source_paths.each do |source_path|
FileUtils.cp_r(source_path, filename)
end
sh "tar -z -c -f #{dest} #{filename}"
end
end
end
end
|
Add RESTful route for new social networks | require 'twitter'
#Twitter Services
get '/twitter-authenticate' do
get_twitter_info
end
get '/twitter-authentication-return' do
get_twitter_access_token
store_twitter_access_token
redirect "/users/#{session[:user_id]}"
end
get '/test-tweet' do
twitter_media_upload("This is something, I swear:", "https://dl.dropboxusercontent.com/s/ephkiagrqgfc0y4/IMG_8489.JPG?raw=1")
redirect "/users/#{session[:user_id]}"
end
| require 'twitter'
get '/destinations/new' do
erb :'destinations/new'
end
#Twitter Services
get '/twitter-authenticate' do
get_twitter_info
end
get '/twitter-authentication-return' do
get_twitter_access_token
store_twitter_access_token
redirect "/users/#{session[:user_id]}"
end
get '/test-tweet' do
twitter_media_upload("This is something, I swear:", "https://dl.dropboxusercontent.com/s/ephkiagrqgfc0y4/IMG_8489.JPG?raw=1")
redirect "/users/#{session[:user_id]}"
end
|
Delete show action in therapists_controller | class PatientsController < ApplicationController
def index
therapist = Therapist.find(session[:therapist_id])
@patients = Patient.all
end
def create
therapist = Therapist.find(session[:therapist_id])
patient = therapist.patients.new(patients_params)
if patient.save
redirect_to root_path
else
set_error("Failed to register patient.")
redirect_to root_path
end
end
def new
end
# def show
# therapist = Therapist.find(session[:therapist_id])
# patient = therapist.patients.new(params[:patient])
# if patient.save
# redirect_to "/"
# else
# set_error("Failed to register patient.")
# redirect_to "/"
# end
# end
def edit
@patient = Patient.find(params[:id])
end
def update
patient = Patient.find(params[:patient][:id])
patient.update(params[:patient])
if patient.save
redirect_to root_path
else
set_error("Failed to update patient.")
redirect_to root_path
end
end
def patients_params
params.require(:patient).permit(:first_name, :last_name, :birthday, :gender, :height, :weight, :email)
end
end
| class PatientsController < ApplicationController
def index
therapist = Therapist.find(session[:therapist_id])
@patients = Patient.all
end
def create
therapist = Therapist.find(session[:therapist_id])
patient = therapist.patients.new(patients_params)
if patient.save
redirect_to root_path
else
set_error("Failed to register patient.")
redirect_to root_path
end
end
def new
end
def edit
@patient = Patient.find(params[:id])
end
def update
patient = Patient.find(params[:patient][:id])
patient.update(params[:patient])
if patient.save
redirect_to root_path
else
set_error("Failed to update patient.")
redirect_to root_path
end
end
def patients_params
params.require(:patient).permit(:first_name, :last_name, :birthday, :gender, :height, :weight, :email)
end
end
|
Add byebug as development dependency | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'drawing_tool/version'
Gem::Specification.new do |spec|
spec.name = "drawing_tool"
spec.version = DrawingTool::VERSION
spec.authors = ["Christian Rojas"]
spec.email = ["christianrojasgar@gmail.com"]
spec.summary = %q{Drawing Tool - Coding Challenge.}
spec.description = %q{Simple console version of a drawing program.}
spec.homepage = "https://github.com/christianrojas/drawing_tool"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency 'terminal-table', '~> 1.4.5'
spec.add_dependency "thor", "~> 0.19.1"
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.2.0"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'drawing_tool/version'
Gem::Specification.new do |spec|
spec.name = "drawing_tool"
spec.version = DrawingTool::VERSION
spec.authors = ["Christian Rojas"]
spec.email = ["christianrojasgar@gmail.com"]
spec.summary = %q{Drawing Tool - Coding Challenge.}
spec.description = %q{Simple console version of a drawing program.}
spec.homepage = "https://github.com/christianrojas/drawing_tool"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency 'terminal-table', '~> 1.4.5'
spec.add_dependency "thor", "~> 0.19.1"
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.2.0"
spec.add_development_dependency "byebug"
end
|
Resolve merge conflict by keeping driver tests in controller. | class ResponsesController < ApplicationController
before_action :set_response, only: [:edit, :update, :destroy]
def new
@response = Response.new
end
def create
question = Question.find(params[:question_id])
response = Response.new(content: response_params[:content], user_id: session[:current_user])
if response.save
question.responses << response
redirect_to response.question
else
render :new
end
end
def edit
end
def update
if @response.update(response_params)
redirect_to @response.question
else
render :edit
end
end
def destroy
question = @response.question
@response.destroy
redirect_to question
end
def up_vote
response = Response.find(params[:id])
end
private
def set_response
@response = Response.find(params[:id])
end
def response_params
params.require(:response).permit(:content)
end
end
| class ResponsesController < ApplicationController
before_action :set_response, only: [:edit, :update, :destroy]
def new
@response = Response.new
end
def create
question = Question.find(params[:question_id])
response = Response.new(content: response_params[:content], user_id: session[:current_user])
if response.save
question.responses << response
redirect_to response.question
else
render :new
end
end
def edit
end
def update
if @response.update(response_params)
redirect_to @response.question
else
render :edit
end
end
def destroy
question = @response.question
@response.destroy
redirect_to question
end
def up_vote
puts "=" * 50
puts params
puts "=" * 50
@response = Response.find(params[:id])
# @response.add_vote
render text: @response.votes.count
end
private
def set_response
@response = Response.find(params[:id])
end
def response_params
params.require(:response).permit(:content)
end
end
|
Change create action in sessions controller to set user by email | class SessionsController < ApplicationController
def new
end
def create
@user = User.find_by(username: session_params[:username])
if @user && @user.authenticate(session_params[:password])
session[:user_id] = @user.id
redirect_to root_path
else
redirect_to :back
end
end
def destroy
session.clear
reset_session
redirect_to root_path
end
private
def session_params
params.require(:session).permit(:email, :password)
end
end
| class SessionsController < ApplicationController
def new
end
def create
@user = User.find_by(email: session_params[:email])
if @user && @user.authenticate(session_params[:password])
session[:user_id] = @user.id
redirect_to root_path
else
redirect_to :back
end
end
def destroy
session.clear
reset_session
redirect_to root_path
end
private
def session_params
params.require(:session).permit(:email, :password)
end
end
|
Add spec for many more than one interpolation in XssLoggerCheck | require "spec_helper"
module Scanny::Checks
describe XssLoggerCheck do
before :each do
@runner = Scanny::Runner.new(XssLoggerCheck.new)
@warning_message = "Assigning request parameters into logger can lead to XSS issues."
@issue = Scanny::Issue.new("scanned_file.rb", 1, :low, @warning_message, 79)
end
it "reports \"logger(params[:password])\" correctly" do
@runner.should check("logger(params[:password])").with_issue(@issue)
end
it "reports \"logger(\"\#{interpolation}\")\" correctly" do
@runner.should check('logger("#{interpolation}")').with_issue(@issue)
end
end
end
| require "spec_helper"
module Scanny::Checks
describe XssLoggerCheck do
before :each do
@runner = Scanny::Runner.new(XssLoggerCheck.new)
@warning_message = "Assigning request parameters into logger can lead to XSS issues."
@issue = Scanny::Issue.new("scanned_file.rb", 1, :low, @warning_message, 79)
end
it "reports \"logger(params[:password])\" correctly" do
@runner.should check("logger(params[:password])").with_issue(@issue)
end
it "reports \"logger(\"\#{interpolation}\")\" correctly" do
@runner.should check('logger("#{i1} and #{i1}")').with_issue(@issue)
@runner.should check('logger("#{interpolation}")').with_issue(@issue)
end
end
end
|
Add option to generate json result from CLI | require 'thor'
require 'nasdaq_scraper'
module NasdaqScraper
module Cli
class Application < Thor
desc 'scrape [URL]', 'Scrape the [URL] for NASDAQ index'
def scrape(url)
data = NasdaqScraper::scrape_url(url)
puts data.to_str
end
end
end
end | require 'thor'
require 'nasdaq_scraper'
module NasdaqScraper
module Cli
class Application < Thor
desc 'scrape [URL]', 'Scrape the [URL] for NASDAQ index'
method_option :json, :type => :boolean, :description => 'Generate JSON result', :default => false
def scrape(url)
data = NasdaqScraper::scrape_url(url)
if options[:json]
puts data.to_json
else
puts data.to_str
end
end
end
end
end |
Clean up the .gemspec a bit. | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/rake/arduino/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Jacob Buys"]
gem.email = ["wjbuys@gmail.com"]
gem.summary = %q{Flexible build system for Arduino projects.}
gem.description = %q{rake-arduino allows you to easily build Arduino sketches using Rake.}
gem.homepage = "https://github.com/wjbuys/rake-arduino"
gem.license = "MIT"
gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
gem.files = `git ls-files`.split("\n")
gem.name = "rake-arduino"
gem.require_paths = ["lib"]
gem.version = Rake::Arduino::VERSION
gem.add_dependency "rake"
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/rake/arduino/version', __FILE__)
Gem::Specification.new do |gem|
gem.platform = Gem::Platform::RUBY
gem.name = "rake-arduino"
gem.version = Rake::Arduino::VERSION
gem.summary = %q{Flexible build system for Arduino projects.}
gem.description = %q{rake-arduino allows you to easily build Arduino sketches using Rake.}
gem.author = "Jacob Buys"
gem.email = "wjbuys@gmail.com"
gem.homepage = "https://github.com/wjbuys/rake-arduino"
gem.license = "MIT"
gem.files = Dir["{lib,examples}/**/*", "MIT-LICENSE", "README.md"]
gem.require_path = "lib"
gem.add_dependency "rake"
end
|
Remove log_status method as it doesn't log | require "alephant/broker/errors/invalid_cache_key"
require "alephant/logger"
require "aws-sdk"
require "ostruct"
require "date"
module Alephant
module Broker
module Response
class Base
include Logger
attr_reader :content, :headers, :status
STATUS_CODE_MAPPING = {
200 => "ok",
404 => "Not found",
500 => "Error retrieving content"
}
def initialize(status = 200, content_type = "text/html")
@content = STATUS_CODE_MAPPING[status]
@headers = { "Content-Type" => content_type }
@headers.merge!(Broker.config[:headers]) if Broker.config.has_key?(:headers)
@status = status
log_status
setup
end
protected
def setup; end
private
def log_status
add_no_cache_headers if status != 200
end
def add_no_cache_headers
headers.merge!(
"Cache-Control" => "no-cache, must-revalidate",
"Pragma" => "no-cache",
"Expires" => Date.today.prev_year.httpdate
)
log
end
def log
logger.metric "BrokerResponse#{status}"
end
end
end
end
end
| require "alephant/broker/errors/invalid_cache_key"
require "alephant/logger"
require "aws-sdk"
require "ostruct"
require "date"
module Alephant
module Broker
module Response
class Base
include Logger
attr_reader :content, :headers, :status
STATUS_CODE_MAPPING = {
200 => "ok",
404 => "Not found",
500 => "Error retrieving content"
}
def initialize(status = 200, content_type = "text/html")
@content = STATUS_CODE_MAPPING[status]
@headers = { "Content-Type" => content_type }
@headers.merge!(Broker.config[:headers]) if Broker.config.has_key?(:headers)
@status = status
add_no_cache_headers if status != 200
setup
end
protected
def setup; end
private
def add_no_cache_headers
headers.merge!(
"Cache-Control" => "no-cache, must-revalidate",
"Pragma" => "no-cache",
"Expires" => Date.today.prev_year.httpdate
)
log
end
def log
logger.metric "BrokerResponse#{status}"
end
end
end
end
end
|
Disable api key creation. No such model for now. | a = ApiKey.create(app_id: "tariff-web")
a.access_token = "86c337686edc492184c5e9869c27a0b1"
a.save
| # a = ApiKey.create(app_id: "tariff-web")
# a.access_token = "86c337686edc492184c5e9869c27a0b1"
# a.save
|
Add instructions for history dump. | #!/usr/bin/env ruby
dir = File.dirname(__FILE__) + '/../lib'
$LOAD_PATH << dir unless $LOAD_PATH.include?(dir)
require 'rubygems'
require 'currentcost/meter'
require 'optparse'
# Command-line options
options = {:port => '/dev/ttyS0'}
OptionParser.new do |opts|
opts.on("-p", "--serial_port SERIAL_PORT", "serial port") do |p|
options[:port] = p
end
end.parse!
# A simple observer class which will receive updates from the meter
class HistoryObserver
def update(xml)
if xml.include?('<hist>')
puts xml
end
end
end
# Create meter
meter = CurrentCost::Meter.new(options[:port], :cc128 => true)
# Create observer
observer = HistoryObserver.new
# Register observer with meter
meter.protocol.add_observer(observer)
# Wait a while, let things happen
sleep(60)
# Close the meter object to stop it receiving data
meter.close
| #!/usr/bin/env ruby
dir = File.dirname(__FILE__) + '/../lib'
$LOAD_PATH << dir unless $LOAD_PATH.include?(dir)
require 'rubygems'
require 'currentcost/meter'
require 'optparse'
# Instructions!
puts "Hold down the DOWN and OK buttons for a few seconds, then release..."
# Command-line options
options = {:port => '/dev/ttyS0'}
OptionParser.new do |opts|
opts.on("-p", "--serial_port SERIAL_PORT", "serial port") do |p|
options[:port] = p
end
end.parse!
# A simple observer class which will receive updates from the meter
class HistoryObserver
def update(xml)
if xml.include?('<hist>')
puts xml
$stdout.flush
end
end
end
# Create meter
meter = CurrentCost::Meter.new(options[:port], :cc128 => true)
# Create observer
observer = HistoryObserver.new
# Register observer with meter
meter.protocol.add_observer(observer)
# Wait a while, let things happen
sleep(60)
# Close the meter object to stop it receiving data
meter.close
|
Fix branch parsing in staging task |
def stage branch, options={}
branches = `git branch`.split("\n")
current_branch = branches.find { |b| b.first == '*' }.split.last.to_sym
changes = `git status -s`.rstrip
unless changes.empty?
puts 'You have pending changes, which will not be deployed!'.red
puts changes.blue
print 'Do you wish to continue? (yN) '
case STDIN.getc.downcase
when 'y'
puts 'Continuing...'
else
puts 'Deployment aborted'.red
return
end
`git stash save -a`
puts 'Changes saved'
end
unless branch == current_branch
puts "Switching to branch [#{branch}]"
`git checkout #{branch}`
end
merge_source = options.fetch :merge, nil
unless merge_source.nil?
puts "Merge [#{merge_source}] to [#{branch}]"
`git merge #{merge_source}`
`git push`
end
puts "Deploying to #{branch} stage".green
`git push sg-#{branch} #{branch}:master`
unless branch == current_branch
puts "Switching back to branch [#{current_branch}]"
`git checkout #{current_branch}`
end
unless changes.empty?
`git stash pop`
puts 'Changes restored'
end
puts "Deployment to #{branch} done".green
end
namespace :stage do
desc "Deploy to development stage"
task :dev do
stage :dev
end
desc "Deploy to production stage"
task :prod do
#TODO rename prod to master to comply w/ new dev rules
stage :prod, merge: :dev
end
end
|
def stage branch, options={}
branches = `git branch`.split "\n"
current_branch = branches.find { |b| b[0] == '*' }.split.last.to_sym
changes = `git status -s`.rstrip
unless changes.empty?
puts 'You have pending changes, which will not be deployed!'.red
puts changes.blue
print 'Do you wish to continue? (yN) '
case STDIN.getc.downcase
when 'y'
puts 'Continuing...'
else
puts 'Deployment aborted'.red
return
end
`git stash save -a`
puts 'Changes saved'
end
unless branch == current_branch
puts "Switching to branch [#{branch}]"
`git checkout #{branch}`
end
merge_source = options.fetch :merge, nil
unless merge_source.nil?
puts "Merge [#{merge_source}] to [#{branch}]"
`git merge #{merge_source}`
`git push`
end
puts "Deploying to #{branch} stage".green
`git push sg-#{branch} #{branch}:master`
unless branch == current_branch
puts "Switching back to branch [#{current_branch}]"
`git checkout #{current_branch}`
end
unless changes.empty?
`git stash pop`
puts 'Changes restored'
end
puts "Deployment to #{branch} done".green
end
namespace :stage do
desc "Deploy to development stage"
task :dev do
stage :dev
end
desc "Deploy to production stage"
task :prod do
#TODO rename prod to master to comply w/ new dev rules
stage :prod, merge: :dev
end
end
|
Expand the changes test to include document | require 'spec_helper'
describe RiverNotifications do
before(:each) do
ActiveRecord::Base.add_observer RiverNotifications.instance
end
after(:each) do
ActiveRecord::Base.observers = []
end
describe "create" do
it "publishes the post without no diff" do
Pebblebed::River.any_instance.should_receive(:publish) do |arg|
arg[:event].should eq :create
arg[:uid].should_not be nil
arg[:attributes].should_not be nil
arg[:changed_attributes].should be nil
end
Post.create!(:canonical_path => 'this.that')
end
end
describe "update" do
it "publishes the post with a diff" do
p = Post.create!(:canonical_path => 'this.that')
p.published = true
Pebblebed::River.any_instance.should_receive(:publish) do |arg|
arg[:event].should eq :update
arg[:uid].should_not be nil
arg[:attributes].should_not be nil
arg[:changed_attributes][:published].should eq [nil, true]
end
p.save!
end
end
end
| require 'spec_helper'
describe RiverNotifications do
before(:each) do
ActiveRecord::Base.add_observer RiverNotifications.instance
end
after(:each) do
ActiveRecord::Base.observers = []
end
describe "create" do
it "publishes the post without no diff" do
Pebblebed::River.any_instance.should_receive(:publish) do |arg|
arg[:event].should eq :create
arg[:uid].should_not be nil
arg[:attributes].should_not be nil
arg[:changed_attributes].should be nil
end
Post.create!(:canonical_path => 'this.that')
end
end
describe "update" do
it "publishes the post with a diff" do
p = Post.create!(:canonical_path => 'this.that', :document => {:text => 'blipp'})
p.published = true
p.document = {:text => 'jumped over the lazy dog'}
Pebblebed::River.any_instance.should_receive(:publish) do |arg|
arg[:event].should eq :update
arg[:uid].should_not be nil
arg[:attributes].should_not be nil
arg[:changed_attributes][:published].should eq [nil, true]
arg[:changed_attributes][:document].should eq [{:text=>"blipp"}, {:text=>"jumped over the lazy dog"}]
end
p.save!
end
end
end
|
Add error handling to TwilioTextMessenger class | class TwilioTextMessenger
attr_reader :message, :recipient
def initialize(message, recipient)
@message = message
@recipient = recipient
end
def call
client = Twilio::REST::Client.new
client.messages.create({
from: ENV['TWILIO_PHONE_NUMBER'],
to: recipient,
body: message
})
end
end
| class TwilioTextMessenger
attr_reader :message, :recipient
def initialize(message, recipient)
@message = message
@recipient = recipient
end
def call
begin
client = Twilio::REST::Client.new
client.messages.create({
from: ENV['TWILIO_PHONE_NUMBER'],
to: recipient,
body: message
})
rescue
puts 'Invalid number'
end
end
end
|
Add homepage to gemspec and update file manifests to use git | # encoding: UTF-8
require File.expand_path('../lib/plucky/version', __FILE__)
Gem::Specification.new do |s|
s.name = 'plucky'
s.homepage = 'http://github.com/jnunemaker/plucky'
s.summary = 'Thin layer over the ruby driver that allows you to quickly grab hold of your data (pluck it!).'
s.require_path = 'lib'
s.authors = ['John Nunemaker']
s.email = ['nunemaker@gmail.com']
s.version = Plucky::Version
s.platform = Gem::Platform::RUBY
s.files = Dir.glob("{bin,lib,test}/**/*") + %w[LICENSE README.rdoc UPGRADES]
s.add_dependency 'mongo', '~> 1.5'
end | # encoding: UTF-8
require File.expand_path('../lib/plucky/version', __FILE__)
Gem::Specification.new do |s|
s.name = 'plucky'
s.homepage = 'http://github.com/jnunemaker/plucky'
s.summary = 'Thin layer over the ruby driver that allows you to quickly grab hold of your data (pluck it!).'
s.require_path = 'lib'
s.homepage = 'http://jnunemaker.github.com/plucky/'
s.authors = ['John Nunemaker']
s.email = ['nunemaker@gmail.com']
s.version = Plucky::Version
s.platform = Gem::Platform::RUBY
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_dependency 'mongo', '~> 1.5'
end
|
Add /usr/local/bin path, fix multiplots | class GnuplotMate
def path
possible_paths = [ENV["TM_GNUPLOT"], `which gnuplot`, "/opt/local/bin/gnuplot", "/sw/bin/gnuplot"]
possible_paths.select { |x| x && File.exist?(x) }.first
end
def self.run
g = GnuplotMate.new
g.run_plot_in_aquaterm(STDIN.read)
end
def run_plot_in_aquaterm(data)
# Delete term lines, change output lines to "term aqua" in order to show plots in Aquaterm
data.gsub!(/^\s+set term.*$/, "")
plotnum = 0;
data.gsub!(/^set output.*$/, "set term aqua #{plotnum += 1}")
execute data
end
def execute(script)
IO.popen(path, 'w') do |plot|
plot.puts script
end
end
end | class GnuplotMate
def path
possible_paths = [ENV["TM_GNUPLOT"], `which gnuplot`, "/opt/local/bin/gnuplot", "/sw/bin/gnuplot", "/usr/local/bin/gnuplot"]
possible_paths.select { |x| x && File.exist?(x) }.first
end
def self.run
g = GnuplotMate.new
g.run_plot_in_aquaterm(STDIN.read)
end
def run_plot_in_aquaterm(data)
# Delete term lines, change output lines to "term aqua" in order to show plots in Aquaterm
data.gsub!(/^\s+set term.*$/, "")
plotnum = 0;
data.gsub!(/^set output.*$/) { "set term aqua #{plotnum += 1}" }
puts data
execute data
end
def execute(script)
IO.popen(path, 'w') do |plot|
plot.puts script
end
end
end
|
Make the dependency on static less annoying. | SmartAnswers::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
end
| SmartAnswers::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
config.slimmer.asset_host = ENV["STATIC_DEV"] || Plek.new("preview").find("assets")
end
|
Fix spec in compare gpa spec | require 'spec_helper'
module CodeclimateCi
describe CompareGpa do
let(:codeclimate_ci) { CodeclimateCi::CompareGpa.new('repo11', 'token1') }
before do
allow_any_instance_of(ApiRequester).to receive(:branch_info)
.and_return(
'last_snapshot' => { 'gpa' => 3 }
)
end
context 'when branch is analyzed' do
before { allow_any_instance_of(GetGpa).to receive(:gpa).and_return(1) }
it 'should not be worse' do
expect(codeclimate_ci.worse?('master')).to be_falsey
end
end
end
end
| require 'spec_helper'
module CodeclimateCi
describe CompareGpa do
let(:codeclimate_ci) { CodeclimateCi::CompareGpa.new('repo11', 'token1') }
before do
allow_any_instance_of(ApiRequester).to receive(:branch_info).with('master')
.and_return(
'last_snapshot' => { 'gpa' => 3 }
)
allow_any_instance_of(ApiRequester).to receive(:branch_info).with('another_branch')
.and_return(
'last_snapshot' => { 'gpa' => 2 }
)
end
context 'when branch is analyzed' do
it 'should not be worse' do
expect(codeclimate_ci.worse?('another_branch')).to be_truthy
end
end
end
end
|
Use VCR for Twilio Service Integration Test | require "rails_helper"
RSpec.feature 'SMS notifications', :type => :feature do
let(:password) { 'asdfasdf' }
let(:admin) { create :admin, :password => password }
let!(:tournament) { create :tournament }
let!(:round_one) { create :round, tournament: tournament }
let!(:attendee_one) { create :ga_attendee_one }
let!(:attendee_two) { create :ga_attendee_two }
let!(:game_appointment_one) { create :game_appointment, round: round_one, attendee_one: attendee_one, attendee_two: attendee_two }
before(:each) do
visit new_user_session_path(year: admin.year)
fill_in 'Email', with: admin.email
fill_in 'Password', with: password
click_button 'Sign in'
click_link 'SMS Notifications'
expect(page).to have_selector 'h2', :text => 'SMS Notifications'
end
context 'signed in admin user' do
it 'can send sms notifications for a round game appointments' do
click_link "Rounds"
click_link "Show"
click_button "Send SMS Notifications"
expect(page).to have_content '2 notifications sent'
end
scenario 'allows a file upload of attendee game pairing data'
scenario 'matches data from the upload to attendee phone numbers with sms_plans'
scenario 'allows admin to preview the SMS message to be sent'
scenario 'allows sms receivers to turn off future sms notifications'
end
end
| require "rails_helper"
RSpec.feature 'SMS notifications', :type => :feature do
let(:password) { 'asdfasdf' }
let(:admin) { create :admin, :password => password }
let!(:tournament) { create :tournament }
let!(:round_one) { create :round, tournament: tournament }
let!(:attendee_one) { create :ga_attendee_one }
let!(:attendee_two) { create :ga_attendee_two }
let!(:game_appointment_one) { create :game_appointment, round: round_one, attendee_one: attendee_one, attendee_two: attendee_two }
before(:each) do
visit new_user_session_path(year: admin.year)
fill_in 'Email', with: admin.email
fill_in 'Password', with: password
click_button 'Sign in'
click_link 'SMS Notifications'
expect(page).to have_selector 'h2', :text => 'SMS Notifications'
end
context 'signed in admin user' do
it 'can send sms notifications for a round game appointments', :vcr do
click_link "Rounds"
click_link "Show"
click_button "Send SMS Notifications"
expect(page).to have_content '2 notifications sent'
end
scenario 'allows a file upload of attendee game pairing data'
scenario 'matches data from the upload to attendee phone numbers with sms_plans'
scenario 'allows admin to preview the SMS message to be sent'
scenario 'allows sms receivers to turn off future sms notifications'
end
end
|
Allow for modification of passed control_col option | # frozen_string_literal: true
class MarkdownTextareaCell < FormCellBase
attribute :name, mandatory: true, description: "The textarea's name attribute."
attribute :form, mandatory: true, description: 'A Rails form object.'
attribute :value, description: "The textarea's content."
attribute :rows, description: 'Number of rows.'
attribute :label, description: 'A label for the form input.'
private
def textarea
form.text_area options[:name], textarea_opts
end
def textarea_opts
opts = {
skip_label: true,
rows: options[:rows] || 10,
control_col: 'col-sm-12',
label_col: '',
data: { toggle: 'markdown', target: "##{preview_id}" }
}
opts[:value] = options[:value] if options[:value]
opts
end
def form_group
form.__send__(:form_group_builder, name, label: label) do
yield.html_safe
end
end
def preview_id
"markdown_textarea_preview_#{name_param}"
end
def edit_id
"markdown_textarea_edit_#{name_param}"
end
end
| # frozen_string_literal: true
class MarkdownTextareaCell < FormCellBase
attribute :name, mandatory: true, description: "The textarea's name attribute."
attribute :form, mandatory: true, description: 'A Rails form object.'
attribute :value, description: "The textarea's content."
attribute :rows, description: 'Number of rows.'
attribute :label, description: 'A label for the form input.'
private
def textarea
form.text_area options[:name], textarea_opts
end
def textarea_opts
opts = {
skip_label: true,
rows: options[:rows] || 10,
control_col: 'col-sm-12'.dup,
label_col: '',
data: { toggle: 'markdown', target: "##{preview_id}" }
}
opts[:value] = options[:value] if options[:value]
opts
end
def form_group
form.__send__(:form_group_builder, name, label: label) do
yield.html_safe
end
end
def preview_id
"markdown_textarea_preview_#{name_param}"
end
def edit_id
"markdown_textarea_edit_#{name_param}"
end
end
|
Test monk install actually installs libs in .gems. | require File.expand_path("helper", File.dirname(__FILE__))
prepare do
FileUtils.rm_rf(TARGET)
end
test "installs the gems listed in the manifest" do
monk("init #{TARGET} --skeleton git://github.com/cyx/empty.git")
FileUtils.cd(TARGET) do
monk("install")
assert `gem list` =~ /batch/
assert `gem list` =~ /cutest/
end
end
| |
Update Rails to version 2.3.8. | # Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
config.gem 'mongo_mapper'
config.gem 'bcrypt-ruby', :lib => 'bcrypt'
config.frameworks -= [:active_record]
config.time_zone = 'Amsterdam'
end
| # Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.8' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
config.gem 'mongo_mapper'
config.gem 'bcrypt-ruby', :lib => 'bcrypt'
config.frameworks -= [:active_record]
config.time_zone = 'Amsterdam'
end
|
Make generator less noisy in spec output | require 'spec_helper'
require 'rails/generators'
require 'redlock'
feature 'Creating a new Work', :workflow do
before do
Rails::Generators.invoke('hyrax:work', ['Catapult'], destination_root: Rails.root)
load "#{EngineCart.destination}/app/models/catapult.rb"
load "#{EngineCart.destination}/app/controllers/hyrax/catapults_controller.rb"
load "#{EngineCart.destination}/app/actors/hyrax/actors/catapult_actor.rb"
load "#{EngineCart.destination}/app/forms/hyrax/catapult_form.rb"
load "#{EngineCart.destination}/config/initializers/hyrax.rb"
load "#{EngineCart.destination}/config/routes.rb"
load "app/helpers/hyrax/url_helper.rb"
end
after do
Rails::Generators.invoke('hyrax:work', ['Catapult'], behavior: :revoke, destination_root: Rails.root)
end
it 'catapults should behave like generic works' do
expect(Hyrax.config.curation_concerns).to include Catapult
expect(defined? Hyrax::Actors::CatapultActor).to eq 'constant'
expect(defined? Hyrax::CatapultsController).to eq 'constant'
expect(defined? Hyrax::CatapultForm).to eq 'constant'
end
end
| require 'spec_helper'
require 'rails/generators'
require 'redlock'
feature 'Creating a new Work', :workflow do
before do
Rails::Generators.invoke('hyrax:work', ['Catapult', '--quiet'], destination_root: Rails.root)
load "#{EngineCart.destination}/app/models/catapult.rb"
load "#{EngineCart.destination}/app/controllers/hyrax/catapults_controller.rb"
load "#{EngineCart.destination}/app/actors/hyrax/actors/catapult_actor.rb"
load "#{EngineCart.destination}/app/forms/hyrax/catapult_form.rb"
load "#{EngineCart.destination}/config/initializers/hyrax.rb"
load "#{EngineCart.destination}/config/routes.rb"
load "app/helpers/hyrax/url_helper.rb"
end
after do
Rails::Generators.invoke('hyrax:work', ['Catapult', '--quiet'], behavior: :revoke, destination_root: Rails.root)
end
it 'catapults should behave like generic works' do
expect(Hyrax.config.curation_concerns).to include Catapult
expect(defined? Hyrax::Actors::CatapultActor).to eq 'constant'
expect(defined? Hyrax::CatapultsController).to eq 'constant'
expect(defined? Hyrax::CatapultForm).to eq 'constant'
end
end
|
Use string for hash keys | module WebPay
class Customer < Entity
install_class_operations :create, :retrieve, :all
attr_accessor :updated_attributes
def self.path
'/customers'
end
def initialize(attributes)
@updated_attributes = {}
super(attributes)
end
def []=(key, value)
send("#{key}=", value)
end
def [](key)
send(key)
end
[:description, :card, :email].each do |attr|
define_method("#{attr}=") do |value|
@updated_attributes[attr] = value
end
define_method("#{attr}") do
@updated_attributes[attr] || @attributes[attr]
end
end
def save
update_attributes(WebPay.client.post(path, @updated_attributes))
@updated_attributes = {}
self
end
def delete
response = WebPay.client.delete(path)
response['deleted']
end
def path
"/customers/#{id}"
end
end
end
| module WebPay
class Customer < Entity
install_class_operations :create, :retrieve, :all
attr_accessor :updated_attributes
def self.path
'/customers'
end
def initialize(attributes)
@updated_attributes = {}
super(attributes)
end
def []=(key, value)
send("#{key}=", value)
end
def [](key)
send(key)
end
[:description, :card, :email].each do |attr|
define_method("#{attr}=") do |value|
@updated_attributes[attr.to_s] = value
end
define_method("#{attr}") do
@updated_attributes[attr.to_s] || @attributes[attr.to_s]
end
end
def save
update_attributes(WebPay.client.post(path, @updated_attributes))
@updated_attributes = {}
self
end
def delete
response = WebPay.client.delete(path)
response['deleted']
end
def path
"/customers/#{id}"
end
end
end
|
Add code comments to gemspec | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'xcode/install/version'
Gem::Specification.new do |spec|
spec.name = 'xcode-install'
spec.version = XcodeInstall::VERSION
spec.authors = ['Boris Bügling']
spec.email = ['boris@icculus.org']
spec.summary = 'Xcode installation manager.'
spec.description = 'Download, install and upgrade Xcodes with ease.'
spec.homepage = 'https://github.com/neonichu/xcode-install'
spec.license = 'MIT'
spec.required_ruby_version = '>= 2.0.0'
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_dependency 'claide', '>= 0.9.1', '< 1.1.0'
spec.add_dependency 'fastlane', '>= 2.1.0', '< 3.0.0'
spec.add_development_dependency 'bundler', '~> 1.7'
spec.add_development_dependency 'rake', '~> 10.0'
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'xcode/install/version'
Gem::Specification.new do |spec|
spec.name = 'xcode-install'
spec.version = XcodeInstall::VERSION
spec.authors = ['Boris Bügling']
spec.email = ['boris@icculus.org']
spec.summary = 'Xcode installation manager.'
spec.description = 'Download, install and upgrade Xcodes with ease.'
spec.homepage = 'https://github.com/neonichu/xcode-install'
spec.license = 'MIT'
spec.required_ruby_version = '>= 2.0.0'
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
# CLI parsing
spec.add_dependency 'claide', '>= 0.9.1', '< 1.1.0'
# contains spaceship, which is used for auth and dev portal interactions
spec.add_dependency 'fastlane', '>= 2.1.0', '< 3.0.0'
spec.add_development_dependency 'bundler', '~> 1.7'
spec.add_development_dependency 'rake', '~> 10.0'
end
|
Change CLAide dependency to allow 1.0.x versions | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'xcode/install/version'
Gem::Specification.new do |spec|
spec.name = 'xcode-install'
spec.version = XcodeInstall::VERSION
spec.authors = ['Boris Bügling']
spec.email = ['boris@icculus.org']
spec.summary = 'Xcode installation manager.'
spec.description = 'Download, install and upgrade Xcodes with ease.'
spec.homepage = 'https://github.com/neonichu/xcode-install'
spec.license = 'MIT'
spec.required_ruby_version = '>= 2.0.0'
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_dependency 'claide', '~> 0.9.1'
# spec.add_dependency 'spaceship', '>= 0.16.0', '< 1.0.0'
spec.add_dependency 'spaceship', '= 0.15.1'
spec.add_development_dependency 'bundler', '~> 1.7'
spec.add_development_dependency 'rake', '~> 10.0'
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'xcode/install/version'
Gem::Specification.new do |spec|
spec.name = 'xcode-install'
spec.version = XcodeInstall::VERSION
spec.authors = ['Boris Bügling']
spec.email = ['boris@icculus.org']
spec.summary = 'Xcode installation manager.'
spec.description = 'Download, install and upgrade Xcodes with ease.'
spec.homepage = 'https://github.com/neonichu/xcode-install'
spec.license = 'MIT'
spec.required_ruby_version = '>= 2.0.0'
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_dependency 'claide', '>= 0.9.1', '< 1.1.0'
# spec.add_dependency 'spaceship', '>= 0.16.0', '< 1.0.0'
spec.add_dependency 'spaceship', '= 0.15.1'
spec.add_development_dependency 'bundler', '~> 1.7'
spec.add_development_dependency 'rake', '~> 10.0'
end
|
Handle the situation when the comments of answer is nil, Expertiza should still ba able to append an empty string as comments. | class TextField < TextResponse
def complete(count, answer = nil)
html = if self.type == 'TextField' and self.break_before == true
'<li>'
else
''
end
html += '<label for="responses_' + count.to_s + '">' + self.txt + '</label>'
html += '<input id="responses_' + count.to_s + '_score" name="responses[' + count.to_s + '][score]" type="hidden" value="">'
html += '<input id="responses_' + count.to_s + '_comments" label=' + self.txt + ' name="responses[' + count.to_s + '][comment]" size=' + self.size.to_s + ' type="text"'
html += 'value="' + answer.comments unless answer.nil?
html += '">'
html += '<BR/><BR/>' if self.type == 'TextField' and self.break_before == false
html.html_safe
end
def view_completed_question(count, answer)
if self.type == 'TextField' and self.break_before == true
html = '<b>' + count.to_s + ". " + self.txt + "</b>"
html += ' '
html += answer.comments
html += '<BR/><BR/>' if Question.exists?(answer.question_id + 1) && Question.find(answer.question_id + 1).break_before == true
else
html = self.txt
html += answer.comments
html += '<BR/><BR/>'
end
html.html_safe
end
end
| class TextField < TextResponse
def complete(count, answer = nil)
html = if self.type == 'TextField' and self.break_before == true
'<li>'
else
''
end
html += '<label for="responses_' + count.to_s + '">' + self.txt + '</label>'
html += '<input id="responses_' + count.to_s + '_score" name="responses[' + count.to_s + '][score]" type="hidden" value="">'
html += '<input id="responses_' + count.to_s + '_comments" label=' + self.txt + ' name="responses[' + count.to_s + '][comment]" size=' + self.size.to_s + ' type="text"'
html += 'value="' + answer.comments.to_s unless answer.nil?
html += '">'
html += '<BR/><BR/>' if self.type == 'TextField' and self.break_before == false
html.html_safe
end
def view_completed_question(count, answer)
if self.type == 'TextField' and self.break_before == true
html = '<b>' + count.to_s + ". " + self.txt + "</b>"
html += ' '
html += answer.comments.to_s
html += '<BR/><BR/>' if Question.exists?(answer.question_id + 1) && Question.find(answer.question_id + 1).break_before == true
else
html = self.txt
html += answer.comments
html += '<BR/><BR/>'
end
html.html_safe
end
end
|
Add basic specs for database provider. | require 'spec_helper'
provider_class = Puppet::Type.type(:database).provider(:mysql)
describe provider_class do
subject { provider_class }
let(:root_home) { '/root' }
let(:defaults_file) { '--defaults-file=/root/.my.cnf' }
let(:raw_databases) do
<<-SQL_OUTPUT
information_schema
mydb
mysql
performance_schema
test
SQL_OUTPUT
end
let(:parsed_databases) { ['information_schema', 'mydb', 'mysql', 'performance_schema', 'test'] }
before :each do
@resource = Puppet::Type::Database.new(
{ :charset => 'utf8', :name => 'new_database' }
)
@provider = provider_class.new(@resource)
Facter.stubs(:value).with(:root_home).returns(root_home)
Puppet::Util.stubs(:which).with("mysql").returns("/usr/bin/mysql")
subject.stubs(:which).with("mysql").returns("/usr/bin/mysql")
subject.stubs(:defaults_file).returns('--defaults-file=/root/.my.cnf')
end
describe 'self.instances' do
it 'returns an array of databases' do
subject.stubs(:mysql).with([defaults_file, "-NBe", "show databases"]).returns(raw_databases)
databases = subject.instances.collect {|x| x.name }
parsed_databases.should match_array(databases)
end
end
describe 'create' do
it 'makes a user' do
subject.expects(:mysql).with([defaults_file, '-NBe', "create database `#{@resource[:name]}` character set #{@resource[:charset]}"])
@provider.create
end
end
describe 'destroy' do
it 'removes a user if present' do
subject.expects(:mysqladmin).with([defaults_file, '-f', 'drop', "#{@resource[:name]}"])
@provider.destroy
end
end
describe 'charset' do
it 'returns a charset' do
subject.expects(:mysql).with([defaults_file, '-NBe', "show create database `#{@resource[:name]}`"]).returns('mydbCREATE DATABASE `mydb` /*!40100 DEFAULT CHARACTER SET utf8 */')
@provider.charset.should == 'utf8'
end
end
describe 'charset=' do
it 'changes the charset' do
subject.expects(:mysql).with([defaults_file, '-NBe', "alter database `#{@resource[:name]}` CHARACTER SET blah"]).returns('0')
@provider.charset=('blah')
end
end
describe 'exists?' do
it 'checks if user exists' do
subject.expects(:mysql).with([defaults_file, '-NBe', "show databases"]).returns('information_schema\nmydb\nmysql\nperformance_schema\ntest')
@provider.exists?
end
end
describe 'self.defaults_file' do
it 'sets --defaults-file' do
File.stubs(:file?).with('#{root_home}/.my.cnf').returns(true)
@provider.defaults_file.should == '--defaults-file=/root/.my.cnf'
end
end
end
| |
Enable Bullet for all specs, not just feature specs. | # Test group helpers for killing N+1 queries.
module Bullet::TestGroupHelpers
def self.extended(group)
return if [:feature].include?(group.metadata[:type])
group.around(:each) do |example|
Bullet.profile(&example)
end
end
end
RSpec.configure do |config|
config.extend Bullet::TestGroupHelpers
end
| |
Fix bad param in test | # coding: utf-8
require File.expand_path("../../../test_helper", __FILE__)
# :stopdoc:
class Admin::AliasesControllerTest < ActionController::TestCase
def setup
super
create_administrator_session
use_ssl
end
test "destroy person alias" do
person = FactoryGirl.create(:person)
person_alias = person.aliases.create!(:name => "Alias")
delete :destroy, :id => person_alias.to_param, :person_id => person_alias.person.to_param, :format => "js"
assert_response :success
assert !Alias.exists?(person_alias.id), "alias"
end
test "destroy team alias" do
team = FactoryGirl.create(:team)
team_alias = team.aliases.create!(:name => "Alias")
delete :destroy, :id => team_alias.to_param, :persoteam_id => team_alias.team.to_param, :format => "js"
assert_response :success
assert !Alias.exists?(team_alias.id), "alias"
end
end
| # coding: utf-8
require File.expand_path("../../../test_helper", __FILE__)
# :stopdoc:
class Admin::AliasesControllerTest < ActionController::TestCase
def setup
super
create_administrator_session
use_ssl
end
test "destroy person alias" do
person = FactoryGirl.create(:person)
person_alias = person.aliases.create!(:name => "Alias")
delete :destroy, :id => person_alias.to_param, :person_id => person_alias.person.to_param, :format => "js"
assert_response :success
assert !Alias.exists?(person_alias.id), "alias"
end
test "destroy team alias" do
team = FactoryGirl.create(:team)
team_alias = team.aliases.create!(:name => "Alias")
delete :destroy, :id => team_alias.to_param, :team_id => team_alias.team.to_param, :format => "js"
assert_response :success
assert !Alias.exists?(team_alias.id), "alias"
end
end
|
Remove unused argument in Currency.native | module Stellar
Currency.class_eval do
def self.native(amount)
new(:native)
end
def self.iso4217(code, issuer)
raise ArgumentError, "Bad :issuer" unless issuer.is_a?(KeyPair)
ici = ISOCurrencyIssuer.new({currency_code:code, issuer:issuer.public_key})
new(:iso4217, ici)
end
end
end | module Stellar
Currency.class_eval do
def self.native
new(:native)
end
def self.iso4217(code, issuer)
raise ArgumentError, "Bad :issuer" unless issuer.is_a?(KeyPair)
ici = ISOCurrencyIssuer.new({currency_code:code, issuer:issuer.public_key})
new(:iso4217, ici)
end
end
end |
Fix for Ruby 1.8 and etc. | require 'nerv/version'
class Nerv
DEFAULT_SEPARATOR = '_'.freeze
class << self
def prefix(keys_prefix, separator = DEFAULT_SEPARATOR)
regexp = /^#{keys_prefix}#{separator}/
pairs = ENV.map { |k, v| [k.gsub(regexp, ''), v] if k =~ regexp }
.compact
.flatten
Hash[*pairs]
end
def [](keys_prefix)
prefix(keys_prefix)
end
end
end
| require 'nerv/version'
class Nerv
DEFAULT_SEPARATOR = '_'.freeze
class << self
def prefix(keys_prefix, separator = DEFAULT_SEPARATOR)
regexp = /^#{keys_prefix}#{separator}/
pairs = ENV.map { |k, v| [k.gsub(regexp, ''), v] if k =~ regexp }
Hash[*pairs.compact.flatten]
end
def [](keys_prefix)
prefix(keys_prefix)
end
end
end
|
Revert "add step method to Member model (for multi-page form)" | class Member < ActiveRecord::Base
belongs_to :club
has_many :cards
# TODO: validations
validates :sex, :inclusion => {:in => %w(m f)}
attr_writer :step
def step
@step ||= 0
end
end
| class Member < ActiveRecord::Base
belongs_to :club
has_many :cards
# TODO: validations
validates :sex, :inclusion => {:in => %w(m f)}
end
|
Remove extra Digest::SHA2.digest method to fix Digest::SHA2.hexdigest issue | require_relative '../../../spec_helper'
require_relative '../sha256/shared/constants'
describe "Digest::SHA2#hexdigest" do
it "returns a SHA256 hexdigest by default" do
cur_digest = Digest::SHA2.new
cur_digest.hexdigest.should == SHA256Constants::BlankHexdigest
# add something to check that the state is reset later
cur_digest << "test"
cur_digest.hexdigest(SHA256Constants::Contents).should == SHA256Constants::Hexdigest
# second invocation is intentional, to make sure there are no side-effects
cur_digest.hexdigest(SHA256Constants::Contents).should == SHA256Constants::Hexdigest
# after all is done, verify that the digest is in the original, blank state
cur_digest.hexdigest.should == SHA256Constants::BlankHexdigest
end
end
describe "Digest::SHA2.hexdigest" do
it "returns a SHA256 hexdigest by default" do
Digest::SHA2.hexdigest(SHA256Constants::Contents).should == SHA256Constants::Hexdigest
# second invocation is intentional, to make sure there are no side-effects
Digest::SHA2.hexdigest(SHA256Constants::Contents).should == SHA256Constants::Hexdigest
Digest::SHA2.hexdigest("").should == SHA256Constants::BlankHexdigest
end
end
| |
Add form types for backward compatibility | require 'dry/core/deprecations'
Dry::Core::Deprecations.warn('Form types were renamed to Params', tag: :'dry-types')
module Dry
module Types
container.keys.grep(/^params\./).each do |key|
next if key == 'params.integer'
register(key.sub('params.', 'form.'), container[key])
end
register('form.int', self['params.integer'])
end
end
| |
Add Yardoc for ::Enumerable extensions | require "hamster/list"
module Enumerable
def to_list
# use destructive operations to build up a new list, like Common Lisp's NCONC
# this is a very fast way to build up a linked list
list = tail = Hamster::Sequence.allocate
each do |item|
new_node = Hamster::Sequence.allocate
new_node.instance_variable_set(:@head, item)
tail.instance_variable_set(:@tail, new_node)
tail = new_node
end
tail.instance_variable_set(:@tail, Hamster::EmptyList)
list.tail
end
end | require "hamster/list"
# Ruby's built-in `Enumerable` module.
# @see http://www.ruby-doc.org/core/Enumerable.html
module Enumerable
# Return a new {Hamster::List} populated with the items in this `Enumerable` object.
# @return [List]
def to_list
# use destructive operations to build up a new list, like Common Lisp's NCONC
# this is a very fast way to build up a linked list
list = tail = Hamster::Sequence.allocate
each do |item|
new_node = Hamster::Sequence.allocate
new_node.instance_variable_set(:@head, item)
tail.instance_variable_set(:@tail, new_node)
tail = new_node
end
tail.instance_variable_set(:@tail, Hamster::EmptyList)
list.tail
end
end |
Make sure migrations are run with Bundler gems. | require 'active_record'
require 'logger'
require 'yaml'
require 'uri'
config_path = File.join(File.dirname(__FILE__), 'config.yaml')
if File.exists?(config_path)
CONFIG = YAML.load_file(config_path)
env = ENV['RACK_ENV'] || 'development'
db_params = CONFIG['DATABASE_PARAMS'][env]
ActiveRecord::Base.establish_connection(db_params)
elsif ENV['DATABASE_URL'] # for Heroku
db = URI.parse(ENV['DATABASE_URL'])
ActiveRecord::Base.establish_connection({
:adapter => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
:host => db.host,
:port => db.port,
:username => db.user,
:password => db.password,
:database => db.path[1..-1],
:encoding => 'utf8',
})
else
raise "No #{config_path} and no ENV[DATABASE_URL]"
end
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Migration.verbose = true
if ARGV[0] == 'rollback'
ActiveRecord::Migrator.rollback("db/migrate")
else
ActiveRecord::Migrator.migrate("db/migrate")
end
| require 'rubygems'
require 'bundler'
Bundler.setup
require 'active_record'
require 'logger'
require 'yaml'
require 'uri'
config_path = File.join(File.dirname(__FILE__), 'config.yaml')
if File.exists?(config_path)
CONFIG = YAML.load_file(config_path)
env = ENV['RACK_ENV'] || 'development'
db_params = CONFIG['DATABASE_PARAMS'][env]
ActiveRecord::Base.establish_connection(db_params)
elsif ENV['DATABASE_URL'] # for Heroku
db = URI.parse(ENV['DATABASE_URL'])
ActiveRecord::Base.establish_connection({
:adapter => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
:host => db.host,
:port => db.port,
:username => db.user,
:password => db.password,
:database => db.path[1..-1],
:encoding => 'utf8',
})
else
raise "No #{config_path} and no ENV[DATABASE_URL]"
end
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Migration.verbose = true
if ARGV[0] == 'rollback'
ActiveRecord::Migrator.rollback("db/migrate")
else
ActiveRecord::Migrator.migrate("db/migrate")
end
|
Update and add dev dependencies. | # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'tty/version'
Gem::Specification.new do |gem|
gem.name = "tty"
gem.version = TTY::VERSION
gem.authors = ["Piotr Murach"]
gem.email = [""]
gem.description = %q{Toolbox for developing CLI clients}
gem.summary = %q{Toolbox for developing CLI clients}
gem.homepage = "http://github.com/peter-murach/tty"
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_development_dependency 'rspec'
gem.add_development_dependency 'rake'
gem.add_development_dependency 'yard'
gem.add_development_dependency 'benchmark_suite'
end
| # -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'tty/version'
Gem::Specification.new do |gem|
gem.name = "tty"
gem.version = TTY::VERSION
gem.authors = ["Piotr Murach"]
gem.email = [""]
gem.description = %q{Toolbox for developing CLI clients}
gem.summary = %q{Toolbox for developing CLI clients}
gem.homepage = "http://github.com/peter-murach/tty"
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_development_dependency 'rspec', '~> 2.14'
gem.add_development_dependency 'rake', '~> 10.1'
gem.add_development_dependency 'yard', '~> 0.8'
gem.add_development_dependency 'benchmark_suite'
gem.add_development_dependency 'bundler'
gem.add_development_dependency 'yard', '~> 0.8'
gem.add_development_dependency 'simplecov', '~> 0.7.1'
gem.add_development_dependency 'coveralls', '~> 0.6.7'
end
|
Add project to load path | require 'active_record'
require 'yaml'
require 'rspec/rails/model_mocks'
require_relative '../models/widget'
db_config = YAML::load(File.open('db/config.yml'))
ActiveRecord::Base.establish_connection(db_config['test'])
RSpec.configure do |config|
config.around(:each) do |ex|
x = proc do
ex.call
raise ActiveRecord::Rollback
end
ActiveRecord::Base.transaction(&x)
end
config.order = 'random'
end
| $:<< File.join(File.dirname(__FILE__), '..')
require 'active_record'
require 'yaml'
require 'rspec/rails/model_mocks'
require 'models/widget'
db_config = YAML::load(File.open('db/config.yml'))
ActiveRecord::Base.establish_connection(db_config['test'])
RSpec.configure do |config|
config.around(:each) do |ex|
x = proc do
ex.call
raise ActiveRecord::Rollback
end
ActiveRecord::Base.transaction(&x)
end
config.order = 'random'
end
|
Add a regression test for friendship removal | require 'test_helper'
require 'integration/concerns/authentication'
require 'support/web_mocking'
class FriendshipsTest < ActionDispatch::IntegrationTest
include Authentication
before do
@user = FactoryGirl.create(:user)
@friend = FactoryGirl.create(:user)
login_as @user
visit profile_path(@friend)
end
it "creates friendships from target users' profile" do
click_link "agregar #{@friend.username} a tu lista de amigos"
assert_content "Agregado #{@friend.username} como amigo"
end
end
| require 'test_helper'
require 'integration/concerns/authentication'
require 'support/web_mocking'
class FriendshipsTest < ActionDispatch::IntegrationTest
include Authentication
before do
@user = FactoryGirl.create(:user)
@friend = FactoryGirl.create(:user)
login_as @user
visit profile_path(@friend)
end
it "creates friendships from target users' profile" do
click_link "agregar #{@friend.username} a tu lista de amigos"
assert_content "Agregado #{@friend.username} como amigo"
end
it "destroys friendships from target users' profile" do
click_link "agregar #{@friend.username} a tu lista de amigos"
click_link "eliminar #{@friend.username} de tu lista de amigos"
assert_content "Eliminado #{@friend.username} como amigo"
end
end
|
Fix open-ending version of 'ruby-filemagic' | $LOAD_PATH.unshift File.expand_path('../lib', __FILE__)
require 'ooxml_parser/version'
Gem::Specification.new do |s|
s.name = 'ooxml_parser'
s.version = OoxmlParser::Version::STRING
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.0'
s.authors = ['Pavel Lobashov', 'Roman Zagudaev']
s.summary = 'OoxmlParser Gem'
s.description = 'Parse OOXML files (docx, xlsx, pptx)'
s.email = ['shockwavenn@gmail.com', 'rzagudaev@gmail.com']
s.files = `git ls-files lib LICENSE.txt README.md`.split($RS)
s.add_runtime_dependency('nokogiri', '~> 1.6')
s.add_runtime_dependency('ruby-filemagic')
s.add_runtime_dependency('rubyzip', '~> 1.1')
s.homepage = 'http://rubygems.org/gems/ooxml_parser'
s.license = 'AGPL-3.0'
end
| $LOAD_PATH.unshift File.expand_path('../lib', __FILE__)
require 'ooxml_parser/version'
Gem::Specification.new do |s|
s.name = 'ooxml_parser'
s.version = OoxmlParser::Version::STRING
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.0'
s.authors = ['Pavel Lobashov', 'Roman Zagudaev']
s.summary = 'OoxmlParser Gem'
s.description = 'Parse OOXML files (docx, xlsx, pptx)'
s.email = ['shockwavenn@gmail.com', 'rzagudaev@gmail.com']
s.files = `git ls-files lib LICENSE.txt README.md`.split($RS)
s.add_runtime_dependency('nokogiri', '~> 1.6')
s.add_runtime_dependency('ruby-filemagic', '~> 0.1')
s.add_runtime_dependency('rubyzip', '~> 1.1')
s.homepage = 'http://rubygems.org/gems/ooxml_parser'
s.license = 'AGPL-3.0'
end
|
Add podspec. Useful to have when doing local mods. | Pod::Spec.new do |s|
s.name = 'FMDB'
s.version = '2.0'
s.summary = 'A Cocoa / Objective-C wrapper around SQLite.'
s.homepage = 'https://github.com/ccgus/fmdb'
s.license = 'MIT'
s.author = { 'August Mueller' => 'gus@flyingmeat.com' }
s.source = { :git => 'https://github.com/ccgus/fmdb.git' }
s.source_files = FileList['src/FM*.{h,m}'].exclude(/fmdb\.m/)
s.library = 'sqlite3'
end
| |
Add known attributes to PDC::V1::Product | module PDC::V1
class Product < PDC::Base
end
end
| module PDC::V1
class Product < PDC::Base
attributes :name, :short, :active, :product_versions, :internal
end
end
|
Set config to remove deprecation warning | require_relative "boot"
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 OpenSplitTime
class Application < Rails::Application
# Initialize configuration defaults for a specific Rails version.
config.load_defaults 6.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
config.time_zone = "UTC"
config.autoload_paths += %W[#{config.root}/lib]
config.autoload_paths += Dir[File.join(Rails.root, "lib", "core_ext", "**/*.rb")].each { |l| require l }
config.exceptions_app = routes
config.action_mailer.delivery_job = "ActionMailer::MailDeliveryJob"
end
end
| require_relative "boot"
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 OpenSplitTime
class Application < Rails::Application
# Initialize configuration defaults for a specific Rails version.
config.load_defaults 6.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
config.time_zone = "UTC"
config.autoload_paths += %W[#{config.root}/lib]
config.autoload_paths += Dir[File.join(Rails.root, "lib", "core_ext", "**/*.rb")].each { |l| require l }
config.exceptions_app = routes
config.action_mailer.delivery_job = "ActionMailer::MailDeliveryJob"
config.active_support.remove_deprecated_time_with_zone_name = true
end
end
|
Fix homepage to use SSL in Munki Cask | cask :v1 => 'munki' do
version '2.1.1.2352'
sha256 'd2287454a1b3aa66ef49e41a34dfa55cfffd45d3e00de5d2288b3fd7ced2e42c'
url "https://github.com/munki/munki/releases/download/v#{version}/munkitools-#{version}.pkg"
appcast 'https://github.com/munki/munki/releases.atom'
name 'Munki'
homepage 'http://munki.github.io/munki/'
license :apache
pkg "munkitools-#{version}.pkg"
uninstall :pkgutil => 'com.googlecode.munki.*'
end
| cask :v1 => 'munki' do
version '2.1.1.2352'
sha256 'd2287454a1b3aa66ef49e41a34dfa55cfffd45d3e00de5d2288b3fd7ced2e42c'
url "https://github.com/munki/munki/releases/download/v#{version}/munkitools-#{version}.pkg"
appcast 'https://github.com/munki/munki/releases.atom'
name 'Munki'
homepage 'https://www.munki.org/munki/'
license :apache
pkg "munkitools-#{version}.pkg"
uninstall :pkgutil => 'com.googlecode.munki.*'
end
|
Rename f to file, use descriptive names | module Henshin
# Compresses a set of files into one big ol' ugly file.
#
# @example
#
# compressed = Compressor.new(files)
# compressed.compress #=> "..."
#
class Compressor
# @param files [Array<File>]
def initialize(files=[])
@files = files
end
def join
@files.map {|f| f.text }.join("\n")
end
# @return [String] The text of the given files joined together.
def compress
join
end
end
end
| module Henshin
# Compresses a set of files into one big ol' ugly file.
#
# @example
#
# compressed = Compressor.new(files)
# compressed.compress #=> "..."
#
class Compressor
# @param files [Array<File>]
def initialize(files=[])
@files = files
end
def join
@files.map {|file| file.text }.join("\n")
end
# @return [String] The text of the given files joined together.
def compress
join
end
end
end
|
Add link in display purchase helper (p91) | module InvoicesHelper
def display_purchase(invoice)
unless invoice.purchase.nil?
invoice.purchase.description
else
"(no Purchase set)"
end
end
end
| module InvoicesHelper
def display_purchase(invoice)
unless invoice.purchase.nil?
link_to invoice.purchase.description, invoice.purchase
else
"(no Purchase set)"
end
end
end
|
Handle reminder without calendar item (test) | class RemindersController < MyplaceonlineController
def footer_items_show
super + [
{
title: I18n.t("myplaceonline.reminders.calendar_item"),
link: calendar_calendar_item_path(@obj.calendar_item.calendar, @obj.calendar_item),
icon: "calendar"
},
]
end
def use_bubble?
true
end
def bubble_text(obj)
Myp.display_date_short_year(obj.start_time, User.current_user)
end
def self.param_names
[
:start_time,
:reminder_name,
:reminder_threshold_amount,
:reminder_threshold_type,
:expire_amount,
:expire_type,
:repeat_amount,
:repeat_type,
:max_pending,
:notes,
]
end
protected
def insecure
true
end
def sorts
["reminders.start_time DESC"]
end
def obj_params
params.require(:reminder).permit(RemindersController.param_names)
end
end
| class RemindersController < MyplaceonlineController
def footer_items_show
if !@obj.calendar_item.nil?
super + [
{
title: I18n.t("myplaceonline.reminders.calendar_item"),
link: calendar_calendar_item_path(@obj.calendar_item.calendar, @obj.calendar_item),
icon: "calendar"
},
]
else
super
end
end
def use_bubble?
true
end
def bubble_text(obj)
Myp.display_date_short_year(obj.start_time, User.current_user)
end
def self.param_names
[
:start_time,
:reminder_name,
:reminder_threshold_amount,
:reminder_threshold_type,
:expire_amount,
:expire_type,
:repeat_amount,
:repeat_type,
:max_pending,
:notes,
]
end
protected
def insecure
true
end
def sorts
["reminders.start_time DESC"]
end
def obj_params
params.require(:reminder).permit(RemindersController.param_names)
end
end
|
Fix coverage for satisfication of module requirements | require 'spec_helper'
describe Henson::Source::Generic do
let(:instance) { Henson::Source::Generic.new }
it "can be instantiated" do
instance.should_not be_nil
end
it "requires subclasses implement fetch!" do
lambda {
instance.fetch!
}.should raise_error(NotImplementedError)
end
it "requires subclasses implement versions" do
lambda {
instance.versions
}.should raise_error(NotImplementedError)
end
end | require 'spec_helper'
describe Henson::Source::Generic do
let(:source) { Henson::Source::Generic.new }
it "can be instantiated" do
source.should_not be_nil
end
it "requires subclasses implement fetch!" do
lambda {
source.fetch!
}.should raise_error(NotImplementedError)
end
it "requires subclasses implement versions" do
lambda {
source.versions
}.should raise_error(NotImplementedError)
end
context "satisfies?" do
let(:requirement) { Gem::Requirement.new '~> 1.0.0' }
it "returns true if any version satisfies the requirement" do
source.stubs(:versions).returns(['0.8', '1.0.11'])
source.satisfies?(requirement).should be_true
end
it "returns false if no version satisfies the requirement" do
source.stubs(:versions).returns(['0.8', '1.6.0'])
source.satisfies?(requirement).should be_false
end
end
end |
Add refresh_fulfillment and update_fulfillment methods | module Spree
class Fulfillment
class Provider
def services
raise NotImplementedError, "#services is not supported by #{self.class.name}."
end
def can_fulfill?(package)
raise NotImplementedError, "#can_fulfill? is not yet supported by #{self.class.name}."
end
def estimate_cost(package, service)
raise NotImplementedError, "#package_estimate is not supported by #{self.class.name}."
end
def estimate_delivery_date(package, service, ship_date)
raise NotImplementedError, "#estimate_delivery_date is not supported by #{self.class.name}."
end
def fulfill(shipment, service=nil)
raise NotImplementedError, "#fulfill is not supported by #{self.class.name}."
end
def cancel_fulfillment(fulfillment)
raise NotImplementedError, "#cancel_fulfillment is not yet supported by #{self.class.name}."
end
def update_inventory_levels(variants=nil)
raise NotImplementedError, "#update_inventory_levels is not yet supported by #{self.class.name}."
end
end
end
end | module Spree
class Fulfillment
class Provider
def services
raise NotImplementedError, "#services is not supported by #{self.class.name}."
end
def can_fulfill?(package)
raise NotImplementedError, "#can_fulfill? is not yet supported by #{self.class.name}."
end
def estimate_cost(package, service)
raise NotImplementedError, "#package_estimate is not supported by #{self.class.name}."
end
def estimate_delivery_date(package, service, ship_date)
raise NotImplementedError, "#estimate_delivery_date is not supported by #{self.class.name}."
end
def fulfill(shipment, service=nil)
raise NotImplementedError, "#fulfill is not supported by #{self.class.name}."
end
def refresh_fulfillment(fulfillment)
raise NotImplementedError, "#refresh_fulfillment is not yet supported by #{self.class.name}."
end
def update_fulfillment(fulfillment)
raise NotImplementedError, "#update_fulfillment is not yet supported by #{self.class.name}."
end
def cancel_fulfillment(fulfillment)
raise NotImplementedError, "#cancel_fulfillment is not yet supported by #{self.class.name}."
end
def update_inventory_levels(variants=nil)
raise NotImplementedError, "#update_inventory_levels is not yet supported by #{self.class.name}."
end
end
end
end |
Correct readme file name in gemspec | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "iso639_config/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "iso639_config"
s.version = Iso639Config::VERSION
s.authors = ["Doug Emery"]
s.email = ["doug@emeryit.com"]
# s.homepage = "TODO"
s.summary = "Rails pages to configure ISO 639.2 language selection options for Rails applications."
s.description = "Rails pages to configure ISO 639.2 language selection options for Rails applications."
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"]
s.add_dependency "rails", "~> 3.1"
s.add_dependency "iso-639"
# s.add_dependency "jquery-rails"
s.add_development_dependency "rails", "~> 3.1"
s.add_development_dependency "sqlite3"
s.add_development_dependency "rspec-rails"
s.add_development_dependency "capybara"
s.add_development_dependency "guard-rspec"
s.add_development_dependency "guard-spork"
s.add_development_dependency "foreman"
s.add_development_dependency "thin"
s.add_development_dependency "factory_girl_rails"
end
| $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "iso639_config/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "iso639_config"
s.version = Iso639Config::VERSION
s.authors = ["Doug Emery"]
s.email = ["doug@emeryit.com"]
# s.homepage = "TODO"
s.summary = "Rails pages to configure ISO 639.2 language selection options for Rails applications."
s.description = "Rails pages to configure ISO 639.2 language selection options for Rails applications."
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"]
s.add_dependency "rails", "~> 3.1"
s.add_dependency "iso-639"
# s.add_dependency "jquery-rails"
s.add_development_dependency "rails", "~> 3.1"
s.add_development_dependency "sqlite3"
s.add_development_dependency "rspec-rails"
s.add_development_dependency "capybara"
s.add_development_dependency "guard-rspec"
s.add_development_dependency "guard-spork"
s.add_development_dependency "foreman"
s.add_development_dependency "thin"
s.add_development_dependency "factory_girl_rails"
end
|
Add Nokogiri as a dependency. | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'kosmos/version'
Gem::Specification.new do |spec|
spec.name = "kosmos"
spec.version = Kosmos::VERSION
spec.authors = ["Ulysse Carion"]
spec.email = ["ulyssecarion@gmail.com"]
spec.summary = %q{TODO: Write a short summary. Required.}
spec.description = %q{TODO: Write a longer description. Optional.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "rubyzip"
spec.add_dependency "rugged"
spec.add_dependency "httparty"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'kosmos/version'
Gem::Specification.new do |spec|
spec.name = "kosmos"
spec.version = Kosmos::VERSION
spec.authors = ["Ulysse Carion"]
spec.email = ["ulyssecarion@gmail.com"]
spec.summary = %q{TODO: Write a short summary. Required.}
spec.description = %q{TODO: Write a longer description. Optional.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "rubyzip"
spec.add_dependency "rugged"
spec.add_dependency "httparty"
spec.add_dependency "nokogiri"
end
|
Add an active scope to CloudDatabaseFlavor | class CloudDatabaseFlavor < ApplicationRecord
include NewWithTypeStiMixin
acts_as_miq_taggable
belongs_to :ext_management_system, :foreign_key => :ems_id, :class_name => "ManageIQ::Providers::CloudManager"
has_many :cloud_databases
virtual_total :total_cloud_databases, :cloud_databases
default_value_for :enabled, true
end
| class CloudDatabaseFlavor < ApplicationRecord
include NewWithTypeStiMixin
acts_as_miq_taggable
belongs_to :ext_management_system, :foreign_key => :ems_id, :class_name => "ManageIQ::Providers::CloudManager"
has_many :cloud_databases
virtual_total :total_cloud_databases, :cloud_databases
default_value_for :enabled, true
scope :active, -> { where(:enabled => true) }
end
|
Add workaround for NoMethodError in gem package | require "gosu"
require "rhythmmml/scene"
module Rhythmmml
class Game < Gosu::Window
attr_reader :mml, :options, :scenes
def initialize(mml, options={})
super(640, 480, false)
self.caption = "Rhythmmml"
@mml = mml
@options = options
@scenes = []
@scenes << Scene::Title.new(self)
end
def update
current_scene.update
end
def draw
current_scene.draw
end
def button_down(id)
case id
when Gosu::KbEscape
close
else
current_scene.button_down(id)
end
end
private
def current_scene
@scenes[0]
end
end
end
| require "gosu"
require "gosu/swig_patches"
require "gosu/patches"
require "rhythmmml/scene"
module Rhythmmml
class Game < Gosu::Window
attr_reader :mml, :options, :scenes
def initialize(mml, options={})
super(640, 480, false)
self.caption = "Rhythmmml"
@mml = mml
@options = options
@scenes = []
@scenes << Scene::Title.new(self)
end
def update
current_scene.update
end
def draw
current_scene.draw
end
def button_down(id)
case id
when Gosu::KbEscape
close
else
current_scene.button_down(id)
end
end
private
def current_scene
@scenes[0]
end
end
end
|
Bump dry-schema to >= 0.5.0 | # frozen_string_literal: true
require File.expand_path('lib/dry/validation/version', __dir__)
Gem::Specification.new do |spec|
spec.name = 'dry-validation'
spec.version = Dry::Validation::VERSION
spec.authors = ['Piotr Solnica']
spec.email = ['piotr.solnica@gmail.com']
spec.summary = 'Validation library'
spec.homepage = 'https://dry-rb.org/gems/dry-validation'
spec.license = 'MIT'
spec.files = Dir['CHANGELOG.md', 'LICENSE', 'README.md', 'lib/**/*']
spec.executables = []
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.required_ruby_version = '>= 2.3'
spec.add_runtime_dependency 'concurrent-ruby', '~> 1.0'
spec.add_runtime_dependency 'dry-core', '~> 0.2', '>= 0.2.1'
spec.add_runtime_dependency 'dry-equalizer', '~> 0.2'
spec.add_runtime_dependency 'dry-initializer', '~> 2.5'
spec.add_runtime_dependency 'dry-schema', '~> 0.3', '>= 0.4'
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec'
end
| # frozen_string_literal: true
require File.expand_path('lib/dry/validation/version', __dir__)
Gem::Specification.new do |spec|
spec.name = 'dry-validation'
spec.version = Dry::Validation::VERSION
spec.authors = ['Piotr Solnica']
spec.email = ['piotr.solnica@gmail.com']
spec.summary = 'Validation library'
spec.homepage = 'https://dry-rb.org/gems/dry-validation'
spec.license = 'MIT'
spec.files = Dir['CHANGELOG.md', 'LICENSE', 'README.md', 'lib/**/*']
spec.executables = []
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.required_ruby_version = '>= 2.3'
spec.add_runtime_dependency 'concurrent-ruby', '~> 1.0'
spec.add_runtime_dependency 'dry-core', '~> 0.2', '>= 0.2.1'
spec.add_runtime_dependency 'dry-equalizer', '~> 0.2'
spec.add_runtime_dependency 'dry-initializer', '~> 2.5'
spec.add_runtime_dependency 'dry-schema', '~> 0.3', '>= 0.5'
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec'
end
|
Set up the faye server for pub/sub messaging. | require 'faye'
Faye::WebSocket.load_adapter('thin')
bayeux = Faye::RackAdapter.new(:mount => 'faye', :timeout => 50)
run bayeux | |
Change to use built-in symbols | # frozen_string_literal: true
require_relative "../lib/tty-prompt"
require 'pastel'
prompt = TTY::Prompt.new
heart = prompt.decorate('❤ ', :magenta)
res = prompt.mask('What is your secret?', mask: heart) do |q|
q.validate(/[a-z\ ]{5,15}/)
end
puts "Secret: \"#{res}\""
| # frozen_string_literal: true
require_relative "../lib/tty-prompt"
require 'pastel'
prompt = TTY::Prompt.new
heart = prompt.decorate(prompt.symbols[:heart] + ' ', :magenta)
res = prompt.mask('What is your secret?', mask: heart) do |q|
q.validate(/[a-z\ ]{5,15}/)
end
puts "Secret: \"#{res}\""
|
Update hash file with interior design questionairre | # Create a design application hash
# For each question
# Print the question to the screen
# Store user answer as the value to the question key
# Print out full hash
# Ask user to type in any question that needs updating
# Print their current answer, ask for the updated answer
# Overwrite old value
# Exit
designer_app = Hash.new
puts "What's your full name?"
designer_app[:name] = gets.chomp
puts "How old are you?"
designer_app[:age] = gets.chomp.to_i
puts "How many children do you have?"
designer_app[:number_of_kids] = gets.chomp.to_i
puts "What decor theme would you like?"
designer_app[:theme] = gets.chomp
puts "How did you hear about us?"
designer_app[:referral] = gets.chomp
puts "Is this your first time using Fancy Wallz Interior Design? (y/n)"
if gets.chomp == "y"
designer_app[:new_client] = true
else
designer_app[:new_client] = false
end
puts "\n————Your details————"
designer_app.each {|key, value| puts "#{key}: #{value}" }
#add some formatting so that the colon doesn't get printed with the symbols
puts "\nWould you like to update any info?
If so, type the name of the category you'd like to update.
If not, type 'none'"
response = gets.chomp
if response == "none"
puts "Thanks for registering with Fancy Wallz!"
exit #exiting here so it doesn't re-print all the details again
else
key_to_update = response.to_sym
puts "#{key_to_update} is currently set to #{designer_app[key_to_update]}. Please enter a new value to overwrite."
designer_app[key_to_update] = gets.chomp
puts "Thanks for updating your info!"
end
puts "\n————Your details————"
designer_app.each {|key, value| puts "#{key}: #{value}" }
| |
Add deprecated message into gemspec | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'pseudo_object/version'
Gem::Specification.new do |spec|
spec.name = "pseudo_object"
spec.version = PseudoObject::VERSION
spec.authors = ["indeep-xyz"]
spec.email = ["indeep.xyz@gmail.com"]
spec.summary = %q{Pseudo class objects of standard library in Ruby.}
spec.description = %q{Pseudo class objects of standard library in Ruby.}
spec.homepage = "https://github.com/indeep-xyz/pseudo-object"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.10"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'pseudo_object/version'
Gem::Specification.new do |spec|
spec.name = "pseudo_object"
spec.version = PseudoObject::VERSION
spec.authors = ["indeep-xyz"]
spec.email = ["indeep.xyz@gmail.com"]
spec.summary = %q{Pseudo class objects of standard library in Ruby.}
spec.description = %q{Pseudo class objects of standard library in Ruby.}
spec.homepage = "https://github.com/indeep-xyz/pseudo-object"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.10"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec"
spec.post_install_message = <<-MESSAGE
! The 'PseudoObject' gem has been deprecated and has been replaced by 'Pseudoo'.
! See: https://rubygems.org/gems/pseudoo
! And: https://github.com/indeep-xyz/pseudoo
MESSAGE
end
|
Add fetch data from postal | class Address < ActiveRecord::Base
translates :building_name, :street_name,
:street_name, :province_name, :district_name, :sub_district_name,
:extra_info
belongs_to :addressable, polymorphic: true
belongs_to :postal_code
end | class Address < ActiveRecord::Base
translates :building_name, :street_name,
:street_name, :province_name, :district_name, :sub_district_name,
:extra_info
belongs_to :addressable, polymorphic: true
belongs_to :postal_code
def fetch_data_from_postal_code
if postal_code
[:en, :th].each do |x|
Globalize.with_locale(x) do
self.assign_attributes(postal_code.locality)
end
end
nil
end
end
end |
Add a data migration to trim excessive slugs | require 'gds_api/router'
router = GdsApi::Router.new(Plek.current.find('router-api'))
Document.find_by_sql("SELECT *, LENGTH(slug) AS slug_length FROM documents HAVING `slug_length` > 250;").each do |document|
if published = document.published_edition
old_slug = document.slug
old_path = Whitehall.url_maker.document_path(published)
new_slug = document.normalize_friendly_id(published.title)
puts "Changing '#{old_slug}' to '#{new_slug}' for document '#{document.id}'"
document.update_attribute(:slug, new_slug)
new_path = Whitehall.url_maker.document_path(published.reload)
puts "Redirecting '#{old_path}' to '#{new_path}'"
router.add_redirect_route(old_path, 'exact', new_path)
end
end
| |
Add missing dependency on libedit | class Btag < Formula
desc "Command-line based audio file tagger"
homepage "https://github.com/fernandotcl/btag"
url "https://github.com/fernandotcl/btag/archive/release-1.4.0.tar.gz"
sha256 "e127b3841fdddb50b6d644e0dc6b7d99bb5f90aabe6a90adf254b6cd2eaefb1a"
head "https://github.com/fernandotcl/btag.git"
depends_on "cmake" => :build
depends_on "pkg-config" => :build
depends_on "boost"
depends_on "libcue"
depends_on "taglib"
def install
system "cmake", ".", "-DENABLE_TESTS=1", *std_cmake_args
system "make"
system "make", "check"
system "make", "install"
man1.install "man/btag.1"
end
test do
system "#{bin}/btag", "--help"
end
end
| class Btag < Formula
desc "Command-line based audio file tagger"
homepage "https://github.com/fernandotcl/btag"
url "https://github.com/fernandotcl/btag/archive/release-1.4.0.tar.gz"
sha256 "e127b3841fdddb50b6d644e0dc6b7d99bb5f90aabe6a90adf254b6cd2eaefb1a"
head "https://github.com/fernandotcl/btag.git"
depends_on "cmake" => :build
depends_on "pkg-config" => :build
depends_on "boost"
depends_on "libcue"
depends_on "libedit"
depends_on "taglib"
def install
system "cmake", ".", "-DENABLE_TESTS=1", *std_cmake_args
system "make"
system "make", "check"
system "make", "install"
man1.install "man/btag.1"
end
test do
system "#{bin}/btag", "--help"
end
end
|
Add `gem.required_ruby_version = ">= 2.0.0"` explicitly | # -*- encoding: utf-8 -*-
Gem::Specification.new do |gem|
gem.name = "mysql2-cs-bind"
gem.version = "0.0.7"
gem.authors = ["TAGOMORI Satoshi"]
gem.email = ["tagomoris@gmail.com"]
gem.homepage = "https://github.com/tagomoris/mysql2-cs-bind"
gem.summary = %q{extension for mysql2 to add client-side variable binding}
gem.description = %q{extension for mysql2 to add client-side variable binding, by adding method Mysql2::Client#xquery}
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_runtime_dependency "mysql2"
# tests
gem.add_development_dependency 'eventmachine'
gem.add_development_dependency 'rake-compiler', "~> 0.7.7"
gem.add_development_dependency 'rake', '0.8.7' # NB: 0.8.7 required by rake-compiler 0.7.9
gem.add_development_dependency 'rspec', '2.10.0'
end
| # -*- encoding: utf-8 -*-
Gem::Specification.new do |gem|
gem.name = "mysql2-cs-bind"
gem.version = "0.0.7"
gem.authors = ["TAGOMORI Satoshi"]
gem.email = ["tagomoris@gmail.com"]
gem.homepage = "https://github.com/tagomoris/mysql2-cs-bind"
gem.summary = %q{extension for mysql2 to add client-side variable binding}
gem.description = %q{extension for mysql2 to add client-side variable binding, by adding method Mysql2::Client#xquery}
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.required_ruby_version = ">= 2.0.0"
gem.add_runtime_dependency "mysql2"
# tests
gem.add_development_dependency 'eventmachine'
gem.add_development_dependency 'rake-compiler', "~> 0.7.7"
gem.add_development_dependency 'rake', '0.8.7' # NB: 0.8.7 required by rake-compiler 0.7.9
gem.add_development_dependency 'rspec', '2.10.0'
end
|
Add yard to dependencies | # encoding: utf-8
require File.expand_path('../lib/greeb/version', __FILE__)
Gem::Specification.new do |s|
s.name = 'greeb'
s.version = Greeb::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ['Dmitry A. Ustalov']
s.email = ['dmitry@eveel.ru']
s.homepage = 'https://github.com/eveel/greeb'
s.summary = 'Greeb is a simple regexp-based tokenizer.'
s.description = 'Greeb is a simple yet awesome regexp-based tokenizer, ' \
'written in Ruby.'
s.rubyforge_project = 'greeb'
s.add_development_dependency 'rake'
s.add_development_dependency 'minitest', '>= 2.11'
s.add_development_dependency 'simplecov'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ['lib']
end
| # encoding: utf-8
require File.expand_path('../lib/greeb/version', __FILE__)
Gem::Specification.new do |s|
s.name = 'greeb'
s.version = Greeb::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ['Dmitry A. Ustalov']
s.email = ['dmitry@eveel.ru']
s.homepage = 'https://github.com/eveel/greeb'
s.summary = 'Greeb is a simple regexp-based tokenizer.'
s.description = 'Greeb is a simple yet awesome regexp-based tokenizer, ' \
'written in Ruby.'
s.rubyforge_project = 'greeb'
s.add_development_dependency 'rake'
s.add_development_dependency 'minitest', '>= 2.11'
s.add_development_dependency 'simplecov'
s.add_development_dependency 'yard'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ['lib']
end
|
Extend permited params in checkout_controller | module Spree
CheckoutController.class_eval do
before_action :permit_line_items_attributes, only: :update
private
def permit_line_items_attributes
line_item_attributes = {
line_items_attributes:[
:id,
ship_address_attributes: [
:firstname, :lastname, :address1, :address2, :city, :country_id,
:state_id, :zipcode, :phone, :state_name, :alternative_phone, :company,
{ country: [:iso, :name, :iso3, :iso_name],
state: [:name, :abbr] }
]
]
}
Spree::PermittedAttributes.checkout_attributes.push(line_item_attributes)
end
end
end
| module Spree
CheckoutController.class_eval do
before_action :permit_line_items_attributes, only: :update
private
def permit_line_items_attributes
line_item_attributes = {
line_items_attributes:[
:id,
:gift,
:gift_name,
:gift_email,
:gift_message,
ship_address_attributes: [
:firstname, :lastname, :address1, :address2, :city, :country_id,
:state_id, :zipcode, :phone, :state_name, :alternative_phone, :company,
{ country: [:iso, :name, :iso3, :iso_name],
state: [:name, :abbr] }
]
]
}
Spree::PermittedAttributes.checkout_attributes.push(line_item_attributes)
end
end
end
|
Remove dead code in tests | require 'spec_helper'
describe VSphereCloud::Cloud do
let(:client_stub) { double(cookie: nil) }
let(:client) { instance_double('VSphereCloud::Client', login: nil, logout: nil, stub: client_stub) }
let(:config) { { fake: 'config' } }
subject(:vsphere_cloud) { VSphereCloud::Cloud.new(config) }
before do
VSphereCloud::Config.should_receive(:configure).with(config)
VSphereCloud::Cloud.any_instance.stub(:at_exit)
VSphereCloud::Client.stub(new: client)
end
describe 'has_vm?' do
let(:vm_id) { 'vm_id' }
context 'the vm is found' do
it 'returns true' do
vsphere_cloud.should_receive(:get_vm_by_cid).with(vm_id)
expect(vsphere_cloud.has_vm?(vm_id)).to be_true
end
end
context 'the vm is not found' do
it 'returns false' do
vsphere_cloud.should_receive(:get_vm_by_cid).with(vm_id).and_raise(Bosh::Clouds::VMNotFound)
expect(vsphere_cloud.has_vm?(vm_id)).to be_false
end
end
end
describe 'snapshot_disk' do
it 'raises not implemented exception when called' do
expect { vsphere_cloud.snapshot_disk('123') }.to raise_error(Bosh::Clouds::NotImplemented)
end
end
end
| require 'spec_helper'
describe VSphereCloud::Cloud do
let(:config) { { fake: 'config' } }
subject(:vsphere_cloud) { VSphereCloud::Cloud.new(config) }
before do
VSphereCloud::Config.should_receive(:configure).with(config)
VSphereCloud::Cloud.any_instance.stub(:at_exit)
end
describe 'has_vm?' do
let(:vm_id) { 'vm_id' }
context 'the vm is found' do
it 'returns true' do
vsphere_cloud.should_receive(:get_vm_by_cid).with(vm_id)
expect(vsphere_cloud.has_vm?(vm_id)).to be_true
end
end
context 'the vm is not found' do
it 'returns false' do
vsphere_cloud.should_receive(:get_vm_by_cid).with(vm_id).and_raise(Bosh::Clouds::VMNotFound)
expect(vsphere_cloud.has_vm?(vm_id)).to be_false
end
end
end
describe 'snapshot_disk' do
it 'raises not implemented exception when called' do
expect { vsphere_cloud.snapshot_disk('123') }.to raise_error(Bosh::Clouds::NotImplemented)
end
end
end
|
Update Anki to version 2.0.18 | class Anki < Cask
url 'http://ankisrs.net/download/mirror/anki-2.0.17.dmg'
homepage 'http://ankisrs.net/'
version '2.0.17'
sha1 '58cd3fa4ba568f380a4c8382ac878553e70f3a46'
link 'Anki.app'
end
| class Anki < Cask
url 'http://ankisrs.net/download/mirror/anki-2.0.18.dmg'
homepage 'http://ankisrs.net/'
version '2.0.18'
sha1 'b9b22375e55b9aaac949e23c1eacc05b4fa6bb65'
link 'Anki.app'
end
|
Copy categories views in views generator | # Thanks to plataformatec/devise
# The code used to inspire this generator!
require 'rails/generators'
module Forem
module Generators
class ViewsGenerator < Rails::Generators::Base #:nodoc:
source_root File.expand_path("../../../../app/views/forem", __FILE__)
desc "Used to copy forem's views to your application's views."
def copy_views
view_directory :admin
view_directory :forums
view_directory :posts
view_directory :topics
end
protected
def view_directory(name)
directory name.to_s, "app/views/forem/#{name}"
end
end
end
end
| # Thanks to plataformatec/devise
# The code used to inspire this generator!
require 'rails/generators'
module Forem
module Generators
class ViewsGenerator < Rails::Generators::Base #:nodoc:
source_root File.expand_path("../../../../app/views/forem", __FILE__)
desc "Used to copy forem's views to your application's views."
def copy_views
view_directory :admin
view_directory :categories
view_directory :forums
view_directory :posts
view_directory :topics
end
protected
def view_directory(name)
directory name.to_s, "app/views/forem/#{name}"
end
end
end
end
|
Remove AWS credentials from s3 object metadata | module ElectricSheep
module Resources
class S3Object < Resource
option :key, required: true
option :bucket, required: true
option :access_key, required: true
option :secret_key, required: true
end
end
end
| module ElectricSheep
module Resources
class S3Object < Resource
option :key, required: true
option :bucket, required: true
end
end
end
|
Use base instead of central in login pages | require 'mumukit/core'
I18n.load_translations_path File.join(__dir__, 'laboratory', 'locales', '*.yml')
module Mumuki
module Laboratory
end
end
require 'mumuki/domain'
require 'mumukit/login'
require 'mumukit/nuntius'
require 'mumukit/platform'
require 'kaminari'
require 'bootstrap-kaminari-views'
Mumukit::Nuntius.configure do |config|
config.app_name = 'laboratory'
end
Mumukit::Platform.configure do |config|
config.application = Mumukit::Platform.laboratory
config.web_framework = Mumukit::Platform::WebFramework::Rails
end
class Mumuki::Laboratory::Engine < ::Rails::Engine
config.i18n.available_locales = Mumukit::Platform::Locale.supported
end
module Mumukit::Platform::OrganizationMapping::Path
class << self
patch :organization_name do |request, domain, hyper|
name = hyper.(request, domain)
if %w(auth login logout).include? name
'central'
else
name
end
end
end
end
require_relative './laboratory/version'
require_relative './laboratory/extensions'
require_relative './laboratory/controllers'
require_relative './laboratory/engine'
| require 'mumukit/core'
I18n.load_translations_path File.join(__dir__, 'laboratory', 'locales', '*.yml')
module Mumuki
module Laboratory
end
end
require 'mumuki/domain'
require 'mumukit/login'
require 'mumukit/nuntius'
require 'mumukit/platform'
require 'kaminari'
require 'bootstrap-kaminari-views'
Mumukit::Nuntius.configure do |config|
config.app_name = 'laboratory'
end
Mumukit::Platform.configure do |config|
config.application = Mumukit::Platform.laboratory
config.web_framework = Mumukit::Platform::WebFramework::Rails
end
class Mumuki::Laboratory::Engine < ::Rails::Engine
config.i18n.available_locales = Mumukit::Platform::Locale.supported
end
module Mumukit::Platform::OrganizationMapping::Path
class << self
patch :organization_name do |request, domain, hyper|
name = hyper.(request, domain)
if %w(auth login logout).include? name
'base'
else
name
end
end
end
end
require_relative './laboratory/version'
require_relative './laboratory/extensions'
require_relative './laboratory/controllers'
require_relative './laboratory/engine'
|
Add views to the auto load path during init | require 'prospecto/controller'
module Prospecto
class Railtie < Rails::Railtie
initializer "prospecto.initialize" do |app|
ActionController::Base.extend(ProspectoController)
end
end
end
| require 'prospecto/controller'
module Prospecto
class Railtie < Rails::Railtie
initializer "prospecto.initialize" do |app|
ActionController::Base.extend(ProspectoController)
end
initializer 'prospecto.autoload', :before => :set_autoload_paths do |app|
Dir["#{app.root}/app/views/**/"].each do |view_folder|
app.config.autoload_paths << view_folder
end
end
end
end
|
Remove Rails 2.1 handling code from noosfero HTTP caching code | module NoosferoHttpCaching
def self.included(c)
c.send(:after_filter, :noosfero_set_cache)
c.send(:before_filter, :noosfero_session_check_before)
c.send(:after_filter, :noosfero_session_check_after)
end
def noosfero_set_cache
return if logged_in?
n = nil
if profile
unless request.path =~ /^\/myprofile/
n = environment.profile_cache_in_minutes
end
else
if request.path == '/'
n = environment.home_cache_in_minutes
else
if params[:controller] != 'account' && request.path !~ /^\/admin/
n = environment.general_cache_in_minutes
end
end
end
if n
expires_in n.minutes, :private => false, :public => true
end
end
def noosfero_session_check_before
return if params[:controller] == 'account'
headers["X-Noosfero-Auth"] = (session[:user] != nil).to_s
end
def noosfero_session_check_after
if headers['X-Noosfero-Auth'] == 'true'
# special case: logout
if !session[:user]
session.delete
end
else
# special case: login
if session[:user]
headers['X-Noosfero-Auth'] = 'true'
end
end
end
end
class ActionController::CgiResponse
def out_with_noosfero_session_check(output = $stdout)
if headers['X-Noosfero-Auth'] == 'false'
@cgi.send(:instance_variable_set, '@output_cookies', nil)
end
headers.delete('X-Noosfero-Auth')
out_without_noosfero_session_check(output)
end
alias_method_chain :out, :noosfero_session_check
end
if Rails.env != 'development'
ActionController::Base.send(:include, NoosferoHttpCaching)
end
| module NoosferoHttpCaching
def self.included(c)
c.send(:after_filter, :noosfero_set_cache)
end
def noosfero_set_cache
return if logged_in?
n = nil
if profile
unless request.path =~ /^\/myprofile/
n = environment.profile_cache_in_minutes
end
else
if request.path == '/'
n = environment.home_cache_in_minutes
else
if params[:controller] != 'account' && request.path !~ /^\/admin/
n = environment.general_cache_in_minutes
end
end
end
if n
expires_in n.minutes, :private => false, :public => true
end
end
end
if Rails.env != 'development'
ActionController::Base.send(:include, NoosferoHttpCaching)
end
|
Test "Check for regression, nil URL from git “top level” causes illegal instruction with implicitly forced unwrap" | class Carthage < Formula
desc "Decentralized dependency manager for Cocoa"
homepage "https://github.com/Carthage/Carthage"
head "https://github.com/jdhealy/Carthage.git",
:revision => 'dcfd2444176dd42da3f4877faf95f28e8488d268',
:using => :git,
:shallow => false
depends_on :xcode => ["8.2", :build]
def install
system "make", "prefix_install", "PREFIX=#{prefix}"
bash_completion.install "Source/Scripts/carthage-bash-completion" => "carthage"
zsh_completion.install "Source/Scripts/carthage-zsh-completion" => "_carthage"
fish_completion.install "Source/Scripts/carthage-fish-completion" => "carthage.fish"
end
test do
(testpath/"Cartfile").write 'github "jspahrsummers/xcconfigs"'
system bin/"carthage", "update"
end
end
| class Carthage < Formula
desc "Decentralized dependency manager for Cocoa"
homepage "https://github.com/Carthage/Carthage"
head "https://github.com/jdhealy/Carthage.git",
:revision => 'f8caf5598d24eff08952a462af0015fe56e6456f',
:using => :git,
:shallow => false
depends_on :xcode => ["8.2", :build]
def install
system "make", "prefix_install", "PREFIX=#{prefix}"
bash_completion.install "Source/Scripts/carthage-bash-completion" => "carthage"
zsh_completion.install "Source/Scripts/carthage-zsh-completion" => "_carthage"
fish_completion.install "Source/Scripts/carthage-fish-completion" => "carthage.fish"
end
test do
(testpath/"Cartfile").write 'github "jspahrsummers/xcconfigs"'
system bin/"carthage", "update"
end
end
|
Disable integration tests if there is no heroku app configured | require 'spec_helper'
describe "#bootstrap" do
let(:user) { ENV['HEROKU_USER'] }
let(:password) { ENV['HEROKU_PASSWORD'] }
let(:client) { Heroku::Client.new(user, password) }
let(:command) { Heroku::Command::Json.new }
it "bootstrap stuff" do
ENV.delete 'HEROKU_APP'
command.bootstrap
end
end
| require 'spec_helper'
if ENV['HEROKU_APP']
describe "#bootstrap" do
let(:user) { ENV['HEROKU_USER'] }
let(:password) { ENV['HEROKU_PASSWORD'] }
let(:client) { Heroku::Client.new(user, password) }
let(:command) { Heroku::Command::Json.new }
it "bootstrap stuff" do
ENV.delete 'HEROKU_APP'
command.bootstrap
end
end
end |
Fix seed data: password_hash to password. Add additional question choices to test seed. | user01 = User.create( username: "Albert", password_hash: "Albert")
user02 = User.create( username: "Bertha", password_hash: "Bertha")
survey01 = Survey.create(title: "Test Survey 01", description: "A test survey.", user_id: user01.id )
survey01.questions.create(text: "What is your favorite color?")
survey01.questions.create( text: "What is your favorite number?")
survey01.questions.create( text: "How many meals do you eat a day?")
survey01.questions[0].choices.create(text: "red")
survey01.questions[1].choices.create(text: "3")
survey01.questions[2].choices.create(text: "2")
Response.create(user_id: user01.id, survey_id: survey01.id)
| user01 = User.create( username: "Albert", password: "Albert")
user02 = User.create( username: "Bertha", password: "Bertha")
survey01 = Survey.create(title: "Test Survey 01", description: "A test survey.", user_id: user01.id )
survey01.questions.create(text: "What is your favorite color?")
survey01.questions.create( text: "What is your favorite number?")
survey01.questions.create( text: "How many meals do you eat a day?")
survey01.questions[0].choices.create(text: "red")
survey01.questions[0].choices.create(text: "blue")
survey01.questions[1].choices.create(text: "3")
survey01.questions[1].choices.create(text: "7")
survey01.questions[2].choices.create(text: "2")
survey01.questions[2].choices.create(text: "5")
Response.create(user_id: user01.id, survey_id: survey01.id)
|
Use a 1.9.3-compatible way of counting bytes in Utf8mb3Cleaner | # encoding: utf-8
module ActiveCleaner
class Utf8mb3Cleaner < BaseCleaner
def clean_value(old_value, record=nil)
unless old_value.nil?
old_value.each_char.select { |char| char.bytes.length < 4 }.join('')
end
end
end
end
| # encoding: utf-8
module ActiveCleaner
class Utf8mb3Cleaner < BaseCleaner
def clean_value(old_value, record=nil)
unless old_value.nil?
old_value.each_char.select { |char| char.bytesize < 4 }.join('')
end
end
end
end
|
Make sure modified request isn't stopped by Rack::Protection::AuthenticityToken | require 'warden'
require File.join(File.dirname(__FILE__), 'padrino', 'warden')
Warden::Manager.before_failure do |env, opts|
# Sinatra is very sensitive to the request method
# since authentication could fail on any type of method, we need
# to set it for the failure app so it is routed to the correct block
env['REQUEST_METHOD'] = "POST"
end
| require 'warden'
require File.join(File.dirname(__FILE__), 'padrino', 'warden')
Warden::Manager.before_failure do |env, opts|
# Sinatra is very sensitive to the request method
# since authentication could fail on any type of method, we need
# to set it for the failure app so it is routed to the correct block
env['REQUEST_METHOD'] = "POST"
# Make sure our modified request isn't stopped by
# Rack::Protection::AuthenticityToken, if user doesn't have csrf set yet
request = Rack::Request.new(env)
csrf = request.session[:csrf] || SecureRandom.hex(32)
env['HTTP_X_CSRF_TOKEN'] = request.session[:csrf] = csrf
end
|
Set attr_reader for most of Palta::Server instance variables | require "palta/core"
require "socket"
require "json"
module Palta
class Server
def initialize options = {}
@host = options[:host] || "localhost"
@port = options[:port] || 8888
@debug = options[:debug] || options[:verbose] || false
@dir = options[:dir] || "./.palta/data"
@max_threads = options[:max_threads] || 8
@threads = []
end
def actions &block
instance_eval(&block) if block_given?
end
def on_msg msg
on_any(msg)
send("on_#{msg[:type]}", msg)
end
def on_any msg
puts "on_any: #{msg}"
end
def start
@server = TCPServer.new @host, @port
@max_threads.times do |i|
@threads << Thread.new do
loop do
client = @server.accept
data = client.recv(1024)
if @debug
puts "[Palta::Server] thread #{i} recv: #{data}"
end
msg = JSON.parse(data, :symbolize_names => true)
on_msg(msg)
end
end
end
end
def stop
@threads.each do |t|
Thread.kill(t)
end
end
end
end
| require "palta/core"
require "socket"
require "json"
module Palta
class Server
attr_reader :host, :port, :debug, :dir, :max_threads
def initialize options = {}
@host = options[:host] || "localhost"
@port = options[:port] || 8888
@debug = options[:debug] || options[:verbose] || false
@dir = options[:dir] || "./.palta/data"
@max_threads = options[:max_threads] || 8
@threads = []
end
def actions &block
instance_eval(&block) if block_given?
end
def on_msg msg
on_any(msg)
send("on_#{msg[:type]}", msg)
end
def on_any msg
puts "on_any: #{msg}"
end
def start
@server = TCPServer.new @host, @port
@max_threads.times do |i|
@threads << Thread.new do
loop do
client = @server.accept
data = client.recv(1024)
if @debug
puts "[Palta::Server] thread #{i} recv: #{data}"
end
msg = JSON.parse(data, :symbolize_names => true)
on_msg(msg)
end
end
end
end
def stop
@threads.each do |t|
Thread.kill(t)
end
end
end
end
|
Use original method name as variable | # TODO (smolnar)
# * create custom handlers for preprocessing args
# * add option to specify context which method run on (class or instance)
# * figure out specs
module Scout
module Worker
extend ActiveSupport::Concern
included do
include Sidekiq::Worker
end
module ClassMethods
def worker
@worker
end
def perform_by(method, options = {})
@worker = Base.new(self, method, options)
@worker.register
end
end
class Base
attr_reader :base, :method, :options
def initialize(base, method, options = {})
@base = base
@method = method
@options = options
end
def register
context = options[:on] == :instance ? base : base.singleton_class
context.send(:alias_method, original_method, method)
base.send(:define_method, :perform) do |*args|
context.send(original_method, *args)
end
context.send(:define_method, method) do |*args|
target = self.is_a?(Class) ? self : self.class
target.perform_async(*args)
end
end
def original_method
@original_method ||= :"original_#{method}"
end
end
end
end
| # TODO (smolnar)
# * create custom handlers for preprocessing args
# * add option to specify context which method run on (class or instance)
# * figure out specs
module Scout
module Worker
extend ActiveSupport::Concern
included do
include Sidekiq::Worker
end
module ClassMethods
def worker
@worker
end
def perform_by(method, options = {})
@worker = Base.new(self, method, options)
@worker.register
end
end
class Base
attr_reader :base, :method, :options
def initialize(base, method, options = {})
@base = base
@method = method
@options = options
end
def register
context = options[:on] == :instance ? base : base.singleton_class
original_method = :"original_#{method}"
context.send(:alias_method, original_method, method)
base.send(:define_method, :perform) do |*args|
context.send(original_method, *args)
end
context.send(:define_method, method) do |*args|
target = self.is_a?(Class) ? self : self.class
target.perform_async(*args)
end
end
end
end
end
|
Clarify that we only generate JSON | namespace :ember do
desc "Generate documentation with YUIDoc."
task :docs do
EmberDev::DocumentationGenerator.new.generate
end
end
| namespace :ember do
desc "Generate JSON for documentation with YUIDoc."
task :docs do
EmberDev::DocumentationGenerator.new.generate
end
end
|
Declare openssl-ccm as runtime dependency | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'adyen_cse/version'
Gem::Specification.new do |spec|
spec.name = "adyen-cse-ruby"
spec.version = AdyenCse::VERSION
spec.authors = ["Joey Cheng"]
spec.email = ["jooeycheng@gmail.com"]
spec.summary = %q{Adyen Client-side encryption library for Ruby}
spec.description = %q{Port of Adyen Android CSE library to Ruby gem}
spec.homepage = "https://github.com/jooeycheng/adyen-cse-ruby"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.14"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "minitest", "~> 5.0"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'adyen_cse/version'
Gem::Specification.new do |spec|
spec.name = "adyen-cse-ruby"
spec.version = AdyenCse::VERSION
spec.authors = ["Joey Cheng"]
spec.email = ["jooeycheng@gmail.com"]
spec.summary = %q{Adyen Client-side encryption library for Ruby}
spec.description = %q{Port of Adyen Android CSE library to Ruby gem}
spec.homepage = "https://github.com/jooeycheng/adyen-cse-ruby"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_runtime_dependency "openssl-ccm", "~> 1.2.1"
spec.add_development_dependency "bundler", "~> 1.14"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "minitest", "~> 5.0"
end
|
Fix thinko in the Chrome::Service spec. | require File.expand_path("../../spec_helper", __FILE__)
module Selenium
module WebDriver
module Chrome
describe Service do
let(:mock_process) do
mock("ChildProcess", :io => mock.as_null_object, :start => true)
end
# ugh.
before { Service.instance_variable_set("@executable_path", nil) }
it "uses the user-provided path if set" do
Platform.stub!(:os => :unix)
Platform.stub!(:assert_executable).with("/some/path")
Chrome.path = "/some/path"
ChildProcess.should_receive(:build).
with { |*args| args.first.should == "/some/path" }.
and_return(mock_process)
Service.default_service.start
end
it "finds the Chrome server binary by searching PATH" do
Platform.stub!(:os => :unix)
Platform.should_receive(:find_binary).once.and_return("/some/path")
Service.executable_path.should == "/some/path"
end
end
end # Chrome
end # WebDriver
end # Selenium
| require File.expand_path("../../spec_helper", __FILE__)
module Selenium
module WebDriver
module Chrome
describe Service do
let(:mock_process) do
mock("ChildProcess", :io => mock.as_null_object, :start => true)
end
# ugh.
before { Service.instance_variable_set("@executable_path", nil) }
it "uses the user-provided path if set" do
Platform.stub!(:os => :unix)
Platform.stub!(:assert_executable).with("/some/path")
Chrome.path = "/some/path"
ChildProcess.should_receive(:build).
with { |*args| args.first.should == "/some/path" }.
and_return(mock_process)
Service.default_service
end
it "finds the Chrome server binary by searching PATH" do
Platform.stub!(:os => :unix)
Platform.should_receive(:find_binary).once.and_return("/some/path")
Service.executable_path.should == "/some/path"
end
end
end # Chrome
end # WebDriver
end # Selenium
|
Sort rummager fields by type | class SearchApiReference
def self.fetch_field_definitions
contents = HTTP.get(
field_definitions_url,
)
JSON.parse(contents)
end
def self.field_definitions_url
"https://raw.githubusercontent.com/alphagov/rummager/master/config/schema/field_definitions.json"
end
end
| class SearchApiReference
def self.fetch_field_definitions
contents = HTTP.get(
field_definitions_url,
)
fields = JSON.parse(contents)
fields.sort_by { |name, definition| [definition["type"], name] }
end
def self.field_definitions_url
"https://raw.githubusercontent.com/alphagov/rummager/master/config/schema/field_definitions.json"
end
end
|
Add CMake to the path after installation | #
# Cookbook:: cmake
# Recipe:: _package
#
package "cmake" do
not_if { platform_family?('windows') }
end
cmake_version = node["cmake"]["version"]
windows_package "CMake #{cmake_version}, a cross-platform, open-source build system" do
source "http://www.cmake.org/files/v#{cmake_version[/^\d\.\d/, 0]}/cmake-#{cmake_version}-win32-x86.exe"
only_if { platform_family?('windows') }
end | #
# Cookbook:: cmake
# Recipe:: _package
#
package "cmake" do
not_if { platform_family?('windows') }
end
cmake_version = node["cmake"]["version"]
windows_package "CMake #{cmake_version}, a cross-platform, open-source build system" do
source "http://www.cmake.org/files/v#{cmake_version[/^\d\.\d/, 0]}/cmake-#{cmake_version}-win32-x86.exe"
only_if { platform_family?('windows') }
end
env 'PATH' do
value 'C:\Program Files (x86)\CMake\bin'
delim ';'
action :modify
only_if { platform_family?('windows') }
end
|
Update gemspec for rrdtool make | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/rrdtool_lib/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Nicolas Brousse"]
gem.email = ["pro@nicolas-brousse.fr"]
gem.description = %q{An RRDtool cli}
gem.summary = %q{An RRDtool cli}
gem.homepage = "http://github.com/nicolas-brousse/rrdtool"
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "rrdtool_lib"
gem.require_paths = ["lib"]
gem.version = RrdtoolLib::VERSION
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/rrdtool_lib/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Nicolas Brousse"]
gem.email = ["pro@nicolas-brousse.fr"]
gem.description = %q{An RRDtool cli}
gem.summary = %q{An RRDtool cli}
gem.homepage = "http://github.com/nicolas-brousse/rrdtool"
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "rrdtool_lib"
gem.require_paths = ["lib"]
gem.version = RrdtoolLib::VERSION
s.extensions << 'rrdtool/extconf.rb'
end
|
Replace class var with a class instance var | class UserRanking
def self.users_array
User.find(all.entries.collect(&:_id))
rescue Mongoid::Errors::DocumentNotFound
[]
end
def self.users_hash
Hash[*users_array.collect { |u| [u._id, u] }.flatten]
end
def self.users
@@users ||= users_hash
end
def user
@user ||= UserRankingAllTime.users[_id]
end
end
| class UserRanking
class << self
def users_array
User.find(all.entries.collect(&:_id))
rescue Mongoid::Errors::DocumentNotFound
[]
end
def users_hash
Hash[*users_array.collect { |u| [u._id, u] }.flatten]
end
def users
@users ||= users_hash
end
end
def user
@user ||= UserRankingAllTime.users[_id]
end
end
|
Use a more specific matcher in Sysvinit test | require 'spec_helper'
describe 'Chef::Provider::DockerService::Sysvinit with Centos' do
let(:chef_run) do
ChefSpec::SoloRunner.new(
platform: 'centos',
version: '7.0',
step_into: 'docker_service'
).converge('docker_service_test::sysvinit')
end
it 'creates docker_service[default]' do
expect(chef_run).to create_docker_service('default')
end
it 'creates the sysvinit file' do
expect(chef_run).to render_file('/etc/init.d/docker')
end
end
| require 'spec_helper'
describe 'Chef::Provider::DockerService::Sysvinit with Centos' do
let(:chef_run) do
ChefSpec::SoloRunner.new(
platform: 'centos',
version: '7.0',
step_into: 'docker_service'
).converge('docker_service_test::sysvinit')
end
it 'creates docker_service[default]' do
expect(chef_run).to create_docker_service('default')
end
it 'creates the sysvinit file' do
expect(chef_run).to create_template('/etc/init.d/docker')
end
end
|
Add i18n_scope to dummy app | ActiveModelSerializers.config.key_transform = :unaltered
| ActiveModelSerializers.config.key_transform = :unaltered
Caprese.config.i18n_scope = 'api.v1.errors'
|
Add preloading of application in Puma. | # coding: utf-8
# Store the pid of the server in the file at “path”.
pidfile 'tmp/pids/puma.pid'
# Use “path” as the file to store the server info state. This is
# used by “pumactl” to query and control the server.
state_path 'tmp/pids/puma.state'
# Configure “min” to be the minimum number of threads to use to answer
# requests and “max” the maximum.
threads 0, 4
# How many worker processes to run.
# workers 2
# Code to run when a worker boots to setup the process before booting
# the app.
#
# This can be called multiple times to add hooks.
#
# on_worker_boot do
# puts 'On worker boot...'
# end
# Bind the server to “url”. “tcp://”, “unix://” and “ssl://” are the only
# accepted protocols.
bind "tcp://0.0.0.0:#{ENV['PORT']}"
bind 'unix://tmp/run/puma.sock'
# Instead of “bind 'ssl://127.0.0.1:9292?key=path_to_key&cert=path_to_cert'” you
# can also use the “ssl_bind” option.
# ssl_bind '127.0.0.1', '9292', { key: path_to_key, cert: path_to_cert }
| # coding: utf-8
# Store the pid of the server in the file at “path”.
pidfile 'tmp/pids/puma.pid'
# Use “path” as the file to store the server info state. This is
# used by “pumactl” to query and control the server.
state_path 'tmp/pids/puma.state'
# Configure “min” to be the minimum number of threads to use to answer
# requests and “max” the maximum.
threads 0, 4
# How many worker processes to run.
# workers 2
# Code to run when a worker boots to setup the process before booting
# the app.
#
# This can be called multiple times to add hooks.
#
# on_worker_boot do
# puts 'On worker boot...'
# end
# Bind the server to “url”. “tcp://”, “unix://” and “ssl://” are the only
# accepted protocols.
bind "tcp://0.0.0.0:#{ENV['PORT']}"
bind 'unix://tmp/run/puma.sock'
# Instead of “bind 'ssl://127.0.0.1:9292?key=path_to_key&cert=path_to_cert'” you
# can also use the “ssl_bind” option.
# ssl_bind '127.0.0.1', '9292', { key: path_to_key, cert: path_to_cert }
# Load up the application prior to receiving any requests.
preload_app!
|
Remove require on old file. | #
# Copyright:: Copyright (c) 2014 Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'rubygems'
require 'rspec/mocks'
require 'pry-debugger'
require 'test_helpers'
require 'support/generated_file_support'
RSpec.configure do |c|
c.include ChefDK
c.include TestHelpers
c.after(:all) { clear_tempdir }
c.filter_run :focus => true
c.run_all_when_everything_filtered = true
c.treat_symbols_as_metadata_keys_with_true_values = true
end
| #
# Copyright:: Copyright (c) 2014 Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'rubygems'
require 'rspec/mocks'
require 'pry-debugger'
require 'test_helpers'
RSpec.configure do |c|
c.include ChefDK
c.include TestHelpers
c.after(:all) { clear_tempdir }
c.filter_run :focus => true
c.run_all_when_everything_filtered = true
c.treat_symbols_as_metadata_keys_with_true_values = true
end
|
Add Royal TSX 2 beta | cask :v1 => 'royal-tsx-beta' do
version '2.0.0.17'
sha256 '45da4fb0b273fc038cdc91354d19a7f908d20ad67b84edfe79ef7c1843f475e2'
url "http://v2.royaltsx.com/updates/royaltsx_#{version}.dmg"
appcast 'http://v2.royaltsx.com/updates_beta.php'
homepage 'http://www.royaltsx.com'
license :unknown
app 'Royal TSX.app'
end
| |
Add utf8 text demo, based on ageldama's script | #!/usr/bin/env ruby
# Original script was contributed by ageldama (Yun, Jonghyouk)
require 'encoding/character/utf-8'
require 'rubygame'
# Initialize Rubygame
Rubygame.init
screen = Rubygame::Screen.set_mode([320,200])
queue = Rubygame::EventQueue.new
# Initialize fonts
fontname = 'freesansbold.ttf'
str = u'abc123하이~'
if ARGV[0]
if File.exist?(File.expand_path(ARGV[0]))
fontname = File.expand_path(ARGV[0])
str = ARGV[1..-1].join(" ")
else
str = ARGV[0..-1].join(" ")
end
else
puts <<EOF
This script demonstrates UTF8 (8-bit Unicode Transformation Format) text
rendered with TTF fonts. This allows you to display international symbols
in your games.
Unfortunately, the sample font that is distributed with rubygame
(freesansbold.ttf) cannot display all characters correctly.
If you like, you can give some arguments to this script to try it out:
1) A path to a different TTF font to use. (optional)
*) A custom string to display.
EOF
end
Rubygame::TTF.setup
fnt = Rubygame::TTF.new(fontname, 20)
loop do
queue.each do |event|
case event
when Rubygame::KeyDownEvent
Rubygame::TTF.quit
Rubygame.quit
exit
end
end
screen.fill([0, 0, 0])
surf_str = fnt.render_utf8(str, true, [0xff, 0xff, 0xff])
surf_str.blit(screen, [10, 10])
screen.update
end
| |
Use kill for terminting httpry | # encoding: UTF-8
#
# Copyright (c) 2016 Tomas Korcak <korczis@gmail.com>. All rights reserved.
# This source code is licensed under the MIT-style license found in the
# LICENSE file in the root directory of this source tree.
module Zlown
class Script
HTTPRY_PID_FILE = '/root/.zlown/run/httpry.pid'
def self.httpry_start(args = [], opts = {})
cmd = "httpry -d -P #{HTTPRY_PID_FILE} -i wlan1 -o /root/.zlown/data/httpry.log -b /root/.zlown/data/httpry.bin"
puts cmd
system cmd
end
def self.httpry_stop(args = [], opts = {})
Process.kill('HUP', File.open(HTTPRY_PID_FILE).read.to_i)
end
end
end
| # encoding: UTF-8
#
# Copyright (c) 2016 Tomas Korcak <korczis@gmail.com>. All rights reserved.
# This source code is licensed under the MIT-style license found in the
# LICENSE file in the root directory of this source tree.
module Zlown
class Script
HTTPRY_PID_FILE = '/root/.zlown/run/httpry.pid'
def self.httpry_start(args = [], opts = {})
cmd = "httpry -d -P #{HTTPRY_PID_FILE} -i wlan1 -o /root/.zlown/data/httpry.log -b /root/.zlown/data/httpry.bin"
puts cmd
system cmd
end
def self.httpry_stop(args = [], opts = {})
pid = File.open(HTTPRY_PID_FILE).read.to_i
cmd = "kill #{pid}"
puts cmd
system cmd
end
end
end
|
Package version is increased from 0.14.0.0 to 0.15.0.0 | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'evt-messaging'
s.version = '0.14.0.0'
s.summary = 'Messaging primitives for Eventide'
s.description = ' '
s.authors = ['The Eventide Project']
s.email = 'opensource@eventide-project.org'
s.homepage = 'https://github.com/eventide-project/messaging'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.3.3'
s.add_runtime_dependency 'evt-event_source'
s.add_development_dependency 'test_bench'
end
| # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'evt-messaging'
s.version = '0.15.0.0'
s.summary = 'Messaging primitives for Eventide'
s.description = ' '
s.authors = ['The Eventide Project']
s.email = 'opensource@eventide-project.org'
s.homepage = 'https://github.com/eventide-project/messaging'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.3.3'
s.add_runtime_dependency 'evt-event_source'
s.add_development_dependency 'test_bench'
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.