Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Use fonticons instead of fileicons in the RegistryItemDecorator
class RegistryItemDecorator < MiqDecorator def self.fonticon nil end def fileicon "100/#{image_name.downcase}.png" end end
class RegistryItemDecorator < MiqDecorator def fonticon image_name == 'registry_string_items' ? 'ff ff-file-txt-o' : 'ff ff-file-bin-o' end end
Use _url, not _path, in mailers
class Maintenance < ActionMailer::Base default :from => AppConfig.mail.sender_address def account_removal_warning(user) @user = user @login_url = new_user_session_path @pod_url = AppConfig.environment.url @after_days = AppConfig.settings.maintenance.remove_old_users.after_days.to_s @remove_after = @user.remove_after mail(:to => @user.email, :subject => I18n.t('notifier.remove_old_user.subject')) do |format| format.text format.html end end end
class Maintenance < ActionMailer::Base default :from => AppConfig.mail.sender_address def account_removal_warning(user) @user = user @login_url = new_user_session_url @pod_url = AppConfig.environment.url @after_days = AppConfig.settings.maintenance.remove_old_users.after_days.to_s @remove_after = @user.remove_after mail(:to => @user.email, :subject => I18n.t('notifier.remove_old_user.subject')) do |format| format.text format.html end end end
Use the Figs environment variables for the default admins and the AuthPds settings
class UserSession < Authlogic::Session::Base pds_url Settings.login.pds_url calling_system Settings.login.calling_system anonymous true redirect_logout_url Settings.login.redirect_logout_url def additional_attributes h = {} return h unless pds_user h[:marli_admin] = true if Settings.login.default_admins.include? pds_user.uid patron = Exlibris::Aleph::Patron.new(patron_id: pds_user.nyuidn) addr_info = patron.address h[:address] = {} h[:address][:street_address] = addr_info["z304_address_2"]["__content__"] h[:address][:city] = addr_info["z304_address_3"]["__content__"] h[:address][:state] = addr_info["z304_address_4"]["__content__"] h[:address][:postal_code] = addr_info["z304_zip"]["__content__"] return h end end
class UserSession < Authlogic::Session::Base pds_url (ENV['PDS_URL'] || 'https://login.library.nyu.edu') calling_system 'marli' anonymous true redirect_logout_url 'http://bobcat.library.nyu.edu' def additional_attributes h = {} return h unless pds_user h[:marli_admin] = true if default_admins.include? pds_user.uid patron = Exlibris::Aleph::Patron.new(patron_id: pds_user.nyuidn) addr_info = patron.address h[:address] = {} h[:address][:street_address] = addr_info["z304_address_2"]["__content__"] h[:address][:city] = addr_info["z304_address_3"]["__content__"] h[:address][:state] = addr_info["z304_address_4"]["__content__"] h[:address][:postal_code] = addr_info["z304_zip"]["__content__"] return h end private def default_admins (Figs.env['MARLI_DEFAULT_ADMINS'] || []) end end
Replace cookie serializer format according to new rails version
# Be sure to restart your server when you modify this file. Rails.application.config.action_dispatch.cookies_serializer = :marshal
# Be sure to restart your server when you modify this file. Rails.application.config.action_dispatch.cookies_serializer = :json
Update Homebrew formula for v0.2.0
require 'formula' class Osxsub < Formula homepage 'https://github.com/mwunsch/osxsub' url 'https://github.com/mwunsch/osxsub/tarball/v0.1.2' sha1 '93c766bfde5aa27c186018d4450c0c41ddae6ffa' head 'https://github.com/mwunsch/osxsub.git' def install bin.install 'bin/osxsub' prefix.install 'lib' end end
require 'formula' class Osxsub < Formula homepage 'https://github.com/mwunsch/osxsub' url 'https://github.com/mwunsch/osxsub/tarball/v0.2.0' sha1 'dd2385baa671a72aa8bab40fbd18d3e1295a74b4' head 'https://github.com/mwunsch/osxsub.git' def install bin.install 'bin/osxsub' prefix.install 'lib' end end
Use File separator instead of slash
# encoding: utf-8 module RySafe::Safe class Node include Comparable include Util::Dates include Util::Hashable SEPARATOR = '/' attr_accessor :name, :parent def initialize name, parent = nil raise ArgumentError if name.nil? @name = name @parent = parent end def self.from_path(path) raise ArgumentError if path == "/" elements = path.sub(/^\//, '').split(SEPARATOR) current = elements.last unless current.nil? empty = elements.empty? parent = empty ? nil : from_path(elements[0..-2].join(SEPARATOR)) new(current, parent) end end def root? @parent.nil? end def parent? !root? end def parents nodes = [] if parent? nodes << parent nodes << parent.parents end nodes.flatten end def to_s path end def path nodes = [] if parent? nodes << parent.path else nodes << nil # for first '/' end nodes << @name nodes.join(SEPARATOR) end def <=> other @name <=> other.name end def === pattern name === pattern end protected def hash_data @name end end end
# encoding: utf-8 module RySafe::Safe class Node include Comparable include Util::Dates include Util::Hashable SEPARATOR = File::SEPARATOR attr_accessor :name, :parent def initialize name, parent = nil raise ArgumentError if name.nil? @name = name @parent = parent end def self.from_path(path) raise ArgumentError if path == "/" elements = path.sub(/^\//, '').split(SEPARATOR) current = elements.last unless current.nil? empty = elements.empty? parent = empty ? nil : from_path(elements[0..-2].join(SEPARATOR)) new(current, parent) end end def root? @parent.nil? end def parent? !root? end def parents nodes = [] if parent? nodes << parent nodes << parent.parents end nodes.flatten end def to_s path end def path nodes = [] if parent? nodes << parent.path else nodes << nil # for first '/' end nodes << @name nodes.join(SEPARATOR) end def <=> other @name <=> other.name end def === pattern name === pattern end protected def hash_data @name end end end
Rename the user column to users.
class RenameUserToUsername < ActiveRecord::Migration def self.up rename_column :pureftpd_users, :user, :username end def self.down rename_column :pureftpd_users, :username, :user end end
Add x64 architecture to Windows cross-compilation targets
# To be used if the gem has extensions. # If this task set is inclueded then you will need to also have # # spec.add_development_dependency( 'rake-compiler', '~> 0.8.1' ) # # in your top level rakefile begin require 'rake/extensiontask' require 'rake/javaextensiontask' if RUBY_PLATFORM == "java" then Rake::JavaExtensionTask.new( This.name) do |ext| ext.ext_dir = File.join( 'ext', This.name, "java" ) ext.lib_dir = File.join( 'lib', This.name ) ext.gem_spec = This.java_gemspec end else Rake::ExtensionTask.new( This.name ) do |ext| ext.ext_dir = File.join( 'ext', This.name, "c" ) ext.lib_dir = File.join( 'lib', This.name ) ext.gem_spec = This.ruby_gemspec ext.cross_compile = true # enable cross compilation (requires cross compile toolchain) ext.cross_platform = 'i386-mingw32' # forces the Windows platform instead of the default one # configure options only for cross compile end end task :test_requirements => :compile rescue LoadError This.task_warning( 'extension' ) end CLOBBER << FileList["lib/**/*.{jar,so,bundle}"] CLOBBER << FileList["lib/#{This.name}/{1,2}.*/"]
# To be used if the gem has extensions. # If this task set is inclueded then you will need to also have # # spec.add_development_dependency( 'rake-compiler', '~> 0.8.1' ) # # in your top level rakefile begin require 'rake/extensiontask' require 'rake/javaextensiontask' if RUBY_PLATFORM == "java" then Rake::JavaExtensionTask.new( This.name) do |ext| ext.ext_dir = File.join( 'ext', This.name, "java" ) ext.lib_dir = File.join( 'lib', This.name ) ext.gem_spec = This.java_gemspec end else Rake::ExtensionTask.new( This.name ) do |ext| ext.ext_dir = File.join( 'ext', This.name, "c" ) ext.lib_dir = File.join( 'lib', This.name ) ext.gem_spec = This.ruby_gemspec ext.cross_compile = true # enable cross compilation (requires cross compile toolchain) ext.cross_platform = %w[x86-mingw32 x64-mingw32] # forces the Windows platform instead of the default one # configure options only for cross compile end end task :test_requirements => :compile rescue LoadError This.task_warning( 'extension' ) end CLOBBER << FileList["lib/**/*.{jar,so,bundle}"] CLOBBER << FileList["lib/#{This.name}/{1,2}.*/"]
Remove another instance of break_out_of_song (not needed any more)
module Kramdown module Converter class LatexRepositext # Include this module in latex converters that render record_marks module RenderRecordMarksMixin def convert_record_mark(el, opts) r = break_out_of_song(@inside_song) if @options[:disable_record_mark] r << inner(el, opts) else meta = %( id: #{ el.attr['id'] }) r << "\\RtRecordMark{#{ meta }}#{ inner(el, opts) }" end r end end end end end
module Kramdown module Converter class LatexRepositext # Include this module in latex converters that render record_marks module RenderRecordMarksMixin def convert_record_mark(el, opts) if @options[:disable_record_mark] inner(el, opts) else meta = %( id: #{ el.attr['id'] }) "\\RtRecordMark{#{ meta }}#{ inner(el, opts) }" end end end end end end
Add dependencies and an author
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'hologram/version' Gem::Specification.new do |spec| spec.name = "hologram" spec.version = Hologram::VERSION spec.authors = ["JD Cantrell"] spec.email = ["jcantrell@trulia.com"] spec.description = %q{TODO: Write a gem description} spec.summary = %q{TODO: Write a gem summary} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files`.split($/) 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_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'hologram/version' Gem::Specification.new do |spec| spec.name = "hologram" spec.version = Hologram::VERSION spec.authors = ["JD Cantrell", "August Flanagan"] spec.email = ["jdcantrell@gmail.com"] spec.description = %q{TODO: Write a gem description} spec.summary = %q{TODO: Write a gem summary} spec.homepage = "" spec.license = "TODO" spec.add_dependency "redcarpet", "~> 2.2.2" spec.add_dependency "sass", "~> 3.2.7" spec.files = `git ls-files`.split($/) 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_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" end
Use convention in postmark initializer template
Thincloud::Postmark.configure do |config| config.api_key = "POSTMARK_API_TEST" end
Thincloud::Postmark.configure do |config| config.api_key = ENV["POSTMARK_API_KEY"] end
Use include_package instead of individual imports in Concurrency
# encoding: utf-8 require 'java' module Autobahn module Concurrency java_import 'java.lang.Thread' java_import 'java.lang.InterruptedException' java_import 'java.util.concurrent.atomic.AtomicInteger' java_import 'java.util.concurrent.atomic.AtomicBoolean' java_import 'java.util.concurrent.ThreadFactory' java_import 'java.util.concurrent.Executors' java_import 'java.util.concurrent.LinkedBlockingQueue' java_import 'java.util.concurrent.LinkedBlockingDeque' java_import 'java.util.concurrent.ArrayBlockingQueue' java_import 'java.util.concurrent.TimeUnit' java_import 'java.util.concurrent.CountDownLatch' java_import 'java.util.concurrent.locks.ReentrantLock' class NamingDaemonThreadFactory include ThreadFactory def self.next_id @id ||= Concurrency::AtomicInteger.new @id.get_and_increment end def initialize(base_name) @base_name = base_name end def newThread(runnable) t = Concurrency::Thread.new(runnable) t.daemon = true t.name = "#@base_name-#{self.class.next_id}" t end end class Lock def initialize @lock = ReentrantLock.new end def lock @lock.lock yield ensure @lock.unlock end end def self.shutdown_thread_pool!(tp, timeout=1, hard_timeout=30) tp.shutdown return true if tp.await_termination(timeout, TimeUnit::SECONDS) tp.shutdown_now return tp.await_termination(hard_timeout, TimeUnit::SECONDS) end end end
# encoding: utf-8 require 'java' module Autobahn module Concurrency java_import 'java.lang.Thread' java_import 'java.lang.InterruptedException' include_package 'java.util.concurrent' include_package 'java.util.concurrent.atomic' include_package 'java.util.concurrent.locks' class NamingDaemonThreadFactory include Concurrency::ThreadFactory def self.next_id @id ||= Concurrency::AtomicInteger.new @id.get_and_increment end def initialize(base_name) @base_name = base_name end def newThread(runnable) t = Concurrency::Thread.new(runnable) t.daemon = true t.name = "#@base_name-#{self.class.next_id}" t end end class Lock def initialize @lock = Concurrency::ReentrantLock.new end def lock @lock.lock yield ensure @lock.unlock end end def self.shutdown_thread_pool!(tp, timeout=1, hard_timeout=30) tp.shutdown return true if tp.await_termination(timeout, TimeUnit::SECONDS) tp.shutdown_now return tp.await_termination(hard_timeout, TimeUnit::SECONDS) end end end
Correct migration to apply Postgres specific instructions
class CreateElasticProductState < ActiveRecord::Migration def up create_table :solidus_elastic_product_states do |t| t.belongs_to :product, null: false, index: true, unique: true t.text :json, limit: (16.megabytes - 1) t.boolean :uploaded, default: false, null: false, index: true t.datetime :locked_for_serialization_at t.datetime :locked_for_upload_at, index: true t.index :locked_for_serialization_at, name: 'index_states_on_locked_for_serialization_at' t.index :json, where: 'json is null' end # to get out of a transaction execute("commit;") execute "INSERT INTO #{Solidus::ElasticProduct::State.table_name} (product_id) SELECT id FROM #{Spree::Product.table_name}" end def down drop_table :solidus_elastic_product_states end end
class CreateElasticProductState < ActiveRecord::Migration def up create_table :solidus_elastic_product_states do |t| t.belongs_to :product, null: false, index: true, unique: true t.text :json, limit: (16.megabytes - 1) t.boolean :uploaded, default: false, null: false, index: true t.datetime :locked_for_serialization_at t.datetime :locked_for_upload_at, index: true t.index :locked_for_serialization_at, name: 'index_states_on_locked_for_serialization_at' t.index :json, where: 'json is null' end # Run Insert outside of a transaction for Postgres if connection.adapter_name =~ /postgres/i execute("commit;") end execute "INSERT INTO #{Solidus::ElasticProduct::State.table_name} (product_id) SELECT id FROM #{Spree::Product.table_name}" end def down drop_table :solidus_elastic_product_states end end
Create r_init function and load libs for sequential mining
module Vimentor class Rclient def initialize() @connection = Rserve::Connection.new end def version() rdo("R.version.string").as_string end def plot_2d_array(arr) n = [] y = [] arr.each do |a| n.push(a[0]) y.push(a[1]) end nstr = n.to_s.sub(/^\[/, "").sub(/\]$/, "") ystr = y.to_s.sub(/^\[/, "").sub(/\]$/, "") cmd = <<END counts <- c(#{ystr}); names(counts) <- c(#{nstr}); barplot(counts); END rdo(cmd) STDIN.gets end private def rdo(str) @connection.eval(str) end end end
module Vimentor class Rclient def initialize() @connection = Rserve::Connection.new r_init() end def r_init() @connection.eval("library(Matrix)") @connection.eval("library(arules)") @connection.eval("library(arulesSequences)") end def version() rdo("R.version.string").as_string end def plot_2d_array(arr) n = [] y = [] arr.each do |a| n.push(a[0]) y.push(a[1]) end nstr = n.to_s.sub(/^\[/, "").sub(/\]$/, "") ystr = y.to_s.sub(/^\[/, "").sub(/\]$/, "") cmd = <<END counts <- c(#{ystr}); names(counts) <- c(#{nstr}); barplot(counts); END rdo(cmd) STDIN.gets end private def rdo(str) @connection.eval(str) end end end
Add test for capitalized letter
require './hero' describe Hero do end
require './hero' describe Hero do it "has a capitalized name" do hero = Hero.new 'mike' expect(hero.name).to eq 'Mike' # это hero.name == 'Mike' end end
Support for maillists and subscription was enabled
require 'yandex/pdd/client/connection' require 'yandex/pdd/client/domains' require 'yandex/pdd/client/mailboxes' module Yandex module Pdd class Client include HTTParty include Yandex::Pdd::Client::Connection include Yandex::Pdd::Client::Domains include Yandex::Pdd::Client::Mailboxes base_uri 'https://pddimp.yandex.ru' format :json def initialize(token = nil) @token = token || ENV['PDD_TOKEN'] self.class.default_options.merge!(headers: { PddToken: @token }) end end end end
require 'yandex/pdd/client/connection' require 'yandex/pdd/client/domains' require 'yandex/pdd/client/mailboxes' require 'yandex/pdd/client/maillists' require 'yandex/pdd/client/subscriptions' module Yandex module Pdd class Client include HTTParty include Yandex::Pdd::Client::Connection include Yandex::Pdd::Client::Domains include Yandex::Pdd::Client::Mailboxes include Yandex::Pdd::Client::Maillists include Yandex::Pdd::Client::Subscriptions base_uri 'https://pddimp.yandex.ru' format :json def initialize(token = nil) @token = token || ENV['PDD_TOKEN'] self.class.default_options.merge!(headers: { PddToken: @token }) end end end end
Update select2-rails now that it has been fixed.
# encoding: UTF-8 version = File.read(File.expand_path("../../SPREE_VERSION", __FILE__)).strip Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_backend' s.version = version s.summary = 'backend e-commerce functionality for the Spree project.' s.description = 'Required dependency for Spree' s.required_ruby_version = '>= 1.9.3' s.author = 'Sean Schofield' s.email = 'sean@spreecommerce.com' s.homepage = 'http://spreecommerce.com' s.rubyforge_project = 'spree_backend' s.files = Dir['LICENSE', 'README.md', 'app/**/*', 'config/**/*', 'lib/**/*', 'db/**/*', 'vendor/**/*'] s.require_path = 'lib' s.requirements << 'none' s.add_dependency 'spree_api', version s.add_dependency 'spree_core', version s.add_dependency 'jquery-rails', '~> 3.0.0' s.add_dependency 'jquery-ui-rails', '~> 4.0.0' # Set to 3.4.5 until https://github.com/argerim/select2-rails/pull/51 is merged. s.add_dependency 'select2-rails', '= 3.4.5' s.add_development_dependency 'email_spec', '~> 1.2.1' end
# encoding: UTF-8 version = File.read(File.expand_path("../../SPREE_VERSION", __FILE__)).strip Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_backend' s.version = version s.summary = 'backend e-commerce functionality for the Spree project.' s.description = 'Required dependency for Spree' s.required_ruby_version = '>= 1.9.3' s.author = 'Sean Schofield' s.email = 'sean@spreecommerce.com' s.homepage = 'http://spreecommerce.com' s.rubyforge_project = 'spree_backend' s.files = Dir['LICENSE', 'README.md', 'app/**/*', 'config/**/*', 'lib/**/*', 'db/**/*', 'vendor/**/*'] s.require_path = 'lib' s.requirements << 'none' s.add_dependency 'spree_api', version s.add_dependency 'spree_core', version s.add_dependency 'jquery-rails', '~> 3.0.0' s.add_dependency 'jquery-ui-rails', '~> 4.0.0' s.add_dependency 'select2-rails', '~> 3.4.7' s.add_development_dependency 'email_spec', '~> 1.2.1' end
Include default configuration values from Pling::Gateway::Base
require 'pling' require 'action_mailer' module Pling module Gateway class ActionMailer < Base class Mailer < ::ActionMailer::Base append_view_path File.expand_path('../../../../app/views', __FILE__) def pling_message(message, device, configuration) @message, @device, @configuration = message, device, configuration use_text = configuration.delete(:text) use_html = configuration.delete(:html) mail(configuration.merge(:to => device.identifier)) do |format| format.text { render 'pling/mailer/pling_message' } if use_text format.html { render 'pling/mailer/pling_message' } if use_html end end end handles :email, :mail, :actionmailer def initialize(configuration) setup_configuration(configuration, :require => [:from]) end def deliver(message, device) message = Pling._convert(message, :message) device = Pling._convert(device, :device) mailer = configuration[:mailer] || Pling::Gateway::ActionMailer::Mailer mailer.pling_message(message, device, configuration).deliver end private def default_configuration { :html => true, :text => true } end end end end
require 'pling' require 'action_mailer' module Pling module Gateway class ActionMailer < Base class Mailer < ::ActionMailer::Base append_view_path File.expand_path('../../../../app/views', __FILE__) def pling_message(message, device, configuration) @message, @device, @configuration = message, device, configuration use_text = configuration.delete(:text) use_html = configuration.delete(:html) mail(configuration.merge(:to => device.identifier)) do |format| format.text { render 'pling/mailer/pling_message' } if use_text format.html { render 'pling/mailer/pling_message' } if use_html end end end handles :email, :mail, :actionmailer def initialize(configuration) setup_configuration(configuration, :require => [:from]) end def deliver(message, device) message = Pling._convert(message, :message) device = Pling._convert(device, :device) mailer = configuration[:mailer] || Pling::Gateway::ActionMailer::Mailer mailer.pling_message(message, device, configuration).deliver end private def default_configuration super.merge({ :html => true, :text => true }) end end end end
Add very basic spec test for gluster::volume
require 'spec_helper' describe 'gluster::volume', type: :define do let(:title) { 'storage1' } let(:params) do { replica: 2, bricks: [ 'srv1.local:/export/brick1/brick', 'srv2.local:/export/brick1/brick', 'srv1.local:/export/brick2/brick', 'srv2.local:/export/brick2/brick' ], options: [ 'server.allow-insecure: on', 'nfs.ports-insecure: on' ] } end describe 'strict variables tests' do describe 'missing gluster_binary fact' do it { is_expected.to compile } end describe 'missing gluster_peer_list fact' do let(:facts) do { gluster_binary: '/usr/sbin/gluster' } end it { is_expected.to compile } end describe 'missing gluster_volume_list fact' do let(:facts) do { gluster_binary: '/usr/sbin/gluster', gluster_peer_list: 'peer1.example.com,peer2.example.com' } end it { is_expected.to compile } end describe 'with all facts' do let(:facts) do { gluster_binary: '/usr/sbin/gluster', gluster_peer_list: 'peer1.example.com,peer2.example.com', gluster_volume_list: 'gl1.example.com:/glusterfs/backup,gl2.example.com:/glusterfs/backup' } end it { is_expected.to compile } end end end
Remove the null constraint on several spree tables
class RemoveNullConstraintsFromSpreeTables < ActiveRecord::Migration def up change_column :spree_properties, :presentation, :string, null: true change_column :spree_taxonomies, :name, :string, null: true change_column :spree_taxons, :name, :string, null: true end def down change_column :spree_properties, :presentation, :string, null: false change_column :spree_taxonomies, :name, :string, null: false change_column :spree_taxons, :name, :string, null: false end end
Add answers as nested resources for questions
Rails.application.routes.draw do resources :questions end
Rails.application.routes.draw do root 'questions#index' resources :questions do resources :answers, only: [:new, :create] end end
Create a special purpose not scored section for CIS CentOS7 v1.1.0.
# 3.4 Disable Print Server - CUPS (Not Scored) service 'cups' do action [:stop, :disable] end # 3.7 Remove LDAP (Not Scored) package 'openldap-servers' do action :remove end package 'openldap-clients' do action :remove end # 3.8 Disable NFS and RPC (Not Scored) service 'nfslock' do action [:stop, :disable] end service 'rpcgssd' do action [:stop, :disable] end service 'rpcbind' do action [:stop, :disable] end service 'rpcidmapd' do action [:stop, :disable] end service 'rpcsvcgssd' do action [:stop, :disable] end # 3.9 Remove DNS Server (Not Scored) package 'bind' do action :remove end # 3.10 Remove FTP Server (Not Scored) package 'vsftpd' do action :remove end # 3.11 Remove HTTP Server (Not Scored) package 'httpd' do action :remove end # 3.12 Remove Dovecot (IMAP and POP3 services) (Not Scored) package 'dovecot' do action :remove end # 3.13 Remove Samba (Not Scored) package 'samba' do action :remove end # 3.14 Remove HTTP Proxy Server (Not Scored) package 'squid' do action :remove end # 3.15 Remove SNMP Server (Not Scored) package 'net-snmp' do action :remove end
Update fpm-cookery to avoid installing Puppet 4.x
require "buildtasks/mixins/dsl" module BuildTasks module FPMCookery class DSL include BuildTasks::Mixins::DSL def initialize(&block) @recipe = "recipe.rb" @fpm_cookery_version = "~> 0.25.0" @fpm_version = "~> 1.3.3" instance_eval(&block) if block_given? end def recipe(arg = nil) set_or_return(:recipe, arg, :kind_of => String) end def fpm_cookery_version(arg = nil) set_or_return(:fpm_cookery_version, arg, :kind_of => String) end def fpm_version(arg = nil) set_or_return(:fpm_version, arg, :kind_of => String) end end end end
require "buildtasks/mixins/dsl" module BuildTasks module FPMCookery class DSL include BuildTasks::Mixins::DSL def initialize(&block) @recipe = "recipe.rb" @fpm_cookery_version = "~> 0.27.0" @fpm_version = "~> 1.3.3" instance_eval(&block) if block_given? end def recipe(arg = nil) set_or_return(:recipe, arg, :kind_of => String) end def fpm_cookery_version(arg = nil) set_or_return(:fpm_cookery_version, arg, :kind_of => String) end def fpm_version(arg = nil) set_or_return(:fpm_version, arg, :kind_of => String) end end end end
Add to Accessors strong_attr_accessor method
module Accessors def self.included(base) base.extend ClassMethods end module ClassMethods def attr_accessor_with_history(*args) args.each do |arg| var_name = "@#{arg}".to_sym define_method(arg) { instance_variable_get(var_name) } define_method("#{arg}=".to_sym) do |value| instance_variable_set(var_name, value) @var_history ||= {} @var_history[var_name] ||= [] @var_history[var_name] << value end define_method("#{arg}_history") { @var_history[var_name] } end end end end
module Accessors def self.included(base) base.extend ClassMethods end module ClassMethods def attr_accessor_with_history(*args) args.each do |arg| var_name = "@#{arg}".to_sym define_method(arg) { instance_variable_get(var_name) } define_method("#{arg}=".to_sym) do |value| instance_variable_set(var_name, value) @var_history ||= {} @var_history[var_name] ||= [] @var_history[var_name] << value end define_method("#{arg}_history") { @var_history[var_name] } end end def strong_attr_acessor(name, name_class) var_name = "@#{name}".to_sym define_method(name) { instance_variable_get(var_name) } define_method("#{name}=".to_sym) do |value| raise 'Несоответствие типов.' unless self.class == name_class instance_variable_set(var_name, value) end end end end
Remove pry from coinmate orderbook
require 'pry' module Cryptoexchange::Exchanges module Coinmate module Services class OrderBook < Cryptoexchange::Services::Market class << self def supports_individual_ticker_query? true end end def fetch(market_pair) output = super(ticker_url(market_pair)) adapt(output, market_pair) end def ticker_url(market_pair) "#{Cryptoexchange::Exchanges::Coinmate::Market::API_URL}/orderBook?currencyPair=#{market_pair.base}_#{market_pair.target}&groupByPriceLimit=False" end def adapt(output, market_pair) order_book = Cryptoexchange::Models::OrderBook.new timestamp = Time.now.to_i order_book.base = market_pair.base order_book.target = market_pair.target order_book.market = Coinmate::Market::NAME order_book.asks = adapt_orders(output['data']['asks'], timestamp) order_book.bids = adapt_orders(output['data']['bids'], timestamp) order_book.timestamp = timestamp order_book.payload = output order_book end def adapt_orders(orders, timestamp) # Format as: [price, amount, timestamp] orders.collect { |order_entry| order_entry.values << timestamp } end end end end end
module Cryptoexchange::Exchanges module Coinmate module Services class OrderBook < Cryptoexchange::Services::Market class << self def supports_individual_ticker_query? true end end def fetch(market_pair) output = super(ticker_url(market_pair)) adapt(output, market_pair) end def ticker_url(market_pair) "#{Cryptoexchange::Exchanges::Coinmate::Market::API_URL}/orderBook?currencyPair=#{market_pair.base}_#{market_pair.target}&groupByPriceLimit=False" end def adapt(output, market_pair) order_book = Cryptoexchange::Models::OrderBook.new timestamp = Time.now.to_i order_book.base = market_pair.base order_book.target = market_pair.target order_book.market = Coinmate::Market::NAME order_book.asks = adapt_orders(output['data']['asks'], timestamp) order_book.bids = adapt_orders(output['data']['bids'], timestamp) order_book.timestamp = timestamp order_book.payload = output order_book end def adapt_orders(orders, timestamp) # Format as: [price, amount, timestamp] orders.collect { |order_entry| order_entry.values << timestamp } end end end end end
Convert Sass::Script::Variable docs to YARD.
module Sass module Script class Variable # :nodoc: attr_reader :name def initialize(name) @name = name end def inspect "!#{name}" end def perform(environment) (val = environment.var(name)) && (return val) raise SyntaxError.new("Undefined variable: \"!#{name}\".") end end end end
module Sass module Script # A SassScript node representing a variable. class Variable # The name of the variable. # # @return [String] attr_reader :name # @param name [String] See \{#name} def initialize(name) @name = name end # @return [String] A string representation of the variable def inspect "!#{name}" end # Evaluates the variable. # # @param environment [Sass::Environment] The environment in which to evaluate the SassScript # @return [Literal] The SassScript object that is the value of the variable # @raise [Sass::SyntaxError] if the variable is undefined def perform(environment) (val = environment.var(name)) && (return val) raise SyntaxError.new("Undefined variable: \"!#{name}\".") end end end end
Add an update path for entities
module Fog module Monitoring class Rackspace class Real def update_entity(entity_id, options = {}) data = {} data['label'] = options['label'] data['metadata'] = options['metadata'] data['ip_addresses'] = options['ip_addresses'] request( :body => MultiJson.encode(data), :expects => [201], :method => 'PUT', :path => "entities/#{entity_id}" ) end end end end end
Set the value from the coins cache
class SetValueAsEarnableCoins < ActiveRecord::Migration def change Wip.find_each do |wip| begin wip.value = wip.respond_to?(:contracts) && wip.contracts.earnable_cents.to_i wip.save! rescue end end end end
class SetValueAsEarnableCoins < ActiveRecord::Migration def change Wip.update_all('value = earnable_coins_cache') end end
Use 'attr_reader' in Gravatar API
module Looks module Gravatar class Image include Comparable def self.new_from_addresses(value) id = value['userimage'] if not id.empty? url = value['userimage_url'] rating = value['rating'] new(id, url, rating) else nil end end def self.new_from_images(key, value) id = key url = value[1] rating = value[0] new(id, url, rating) end attr_accessor :id, :url, :rating def initialize(id, url, rating) @id = id @url = url @rating = rating end def <=>(other) id <=> other.id end def to_s id end end end end
module Looks module Gravatar class Image include Comparable def self.new_from_addresses(value) id = value['userimage'] if not id.empty? url = value['userimage_url'] rating = value['rating'] new(id, url, rating) else nil end end def self.new_from_images(key, value) id = key url = value[1] rating = value[0] new(id, url, rating) end attr_reader :id, :url, :rating def initialize(id, url, rating) @id = id @url = url @rating = rating end def <=>(other) id <=> other.id end def to_s id end end end end
Update platform-api requirement from ~> 2.0.0 to >= 2.0, < 2.3
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'dynosaur/version' Gem::Specification.new do |spec| spec.name = 'dynosaur' spec.version = Dynosaur::VERSION spec.authors = ['Tom Collier'] spec.email = ['collier@apartmentlist.com'] spec.license = 'MIT' spec.summary = 'Run a rake task in a separate process (locally or on Heroku)' spec.files = `git ls-files -z`.split("\x0").reject { |f| f =~ %r{^(spec)/} } spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_runtime_dependency 'platform-api', '~> 2.0.0' spec.add_runtime_dependency 'sys-proctable', '>= 0.9', '< 2.0' spec.add_development_dependency 'bundler', '~> 1.8' spec.add_development_dependency 'codeclimate-test-reporter', '~> 0.4' spec.add_development_dependency 'pry-byebug', '~> 3' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3' end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'dynosaur/version' Gem::Specification.new do |spec| spec.name = 'dynosaur' spec.version = Dynosaur::VERSION spec.authors = ['Tom Collier'] spec.email = ['collier@apartmentlist.com'] spec.license = 'MIT' spec.summary = 'Run a rake task in a separate process (locally or on Heroku)' spec.files = `git ls-files -z`.split("\x0").reject { |f| f =~ %r{^(spec)/} } spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_runtime_dependency 'platform-api', '>= 2.0', '< 2.3' spec.add_runtime_dependency 'sys-proctable', '>= 0.9', '< 2.0' spec.add_development_dependency 'bundler', '~> 1.8' spec.add_development_dependency 'codeclimate-test-reporter', '~> 0.4' spec.add_development_dependency 'pry-byebug', '~> 3' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3' end
Isolate global state (env vars) for a mailer configuration test, by running it in a separated process
RSpec.describe "Components: mailer.configuration", type: :cli do context "with hanami-mailer" do it "resolves mailer configuration" do with_project do require Pathname.new(Dir.pwd).join("config", "environment") Hanami::Components.resolve('mailer.configuration') expect(Hanami::Components['mailer.configuration']).to be_kind_of(Hanami::Mailer::Configuration) end end it "resolves mailer configuration for current environment" do with_project do unshift "config/environment.rb", "ENV['HANAMI_ENV'] = 'production'" require Pathname.new(Dir.pwd).join("config", "environment") Hanami::Components.resolve('mailer.configuration') configuration = Hanami::Components['mailer.configuration'] expect(configuration.delivery_method.first).to eq(:smtp) end end end end
RSpec.describe "Components: mailer.configuration", type: :cli do context "with hanami-mailer" do it "resolves mailer configuration" do with_project do require Pathname.new(Dir.pwd).join("config", "environment") Hanami::Components.resolve('mailer.configuration') expect(Hanami::Components['mailer.configuration']).to be_kind_of(Hanami::Mailer::Configuration) end end it "resolves mailer configuration for current environment" do with_project do unshift "config/environment.rb", "ENV['HANAMI_ENV'] = 'production'" write "script/components", <<-EOF require "\#{__dir__}/../config/environment" Hanami::Components.resolve('mailer.configuration') configuration = Hanami::Components['mailer.configuration'] puts "mailer.configuration.delivery_method: \#{configuration.delivery_method.first.inspect}" EOF bundle_exec "ruby script/components" expect(out).to include("mailer.configuration.delivery_method: :smtp") end end end end
Add feature spec to cover deleting a challenge
require "spec_helper" feature "Deleting a challenege" do include OmniAuthHelper before(:each) do mock_omni_auth end scenario "as the owner of the challenge" do user = User.create!( nickname: ADMINS.first, name: "foo", uid: "123545", image: "bar", provider: "twitter" ) challenge = Challenge.create!( title: "challenge1", description: "a sample challenge", input: "aa", output: "bb", diff: "aabb", user_id: user.id ) visit root_path click_link "Sign in with Twitter" click_link "challenge1" click_button "Delete Challenge" expect(Challenge.count).to eq(0) end scenario "not as the owner of the challenge" do user = User.create!( nickname: "foo", name: "bar", uid: 545321, image: "baz", provider: "twitter" ) challenge = Challenge.create!( title: "challenge1", description: "a sample challenge", input: "aa", output: "bb", diff: "aabb", user_id: user.id ) visit root_path click_link "challenge1" expect(page).not_to have_text("Delete Challenge") expect(Challenge.count).to eq(1) end end
Add FakeWeb.clean_registry for right use of FakeWeb
require 'spec_helper' require 'pavlov_rss' require 'fake_web' describe PavlovRss::Reader do describe "#fetch" do before :each do FakeWeb.register_uri(:get, "http://example.com/test1", :body => sample_feed) @reader = PavlovRss::Reader.new("http://example.com/test1") @feeds = @reader.fetch end it "return right channel title" do @feeds.first.channel.title.should eq RSS::Parser.parse(sample_feed).channel.title end end end
require 'spec_helper' require 'pavlov_rss' require 'fake_web' describe PavlovRss::Reader do after do FakeWeb.clean_registry end describe "#fetch" do before :each do FakeWeb.register_uri(:get, "http://example.com/test1", :body => sample_feed) @reader = PavlovRss::Reader.new("http://example.com/test1") @feeds = @reader.fetch end it "return right channel title" do @feeds.first.channel.title.should eq RSS::Parser.parse(sample_feed).channel.title end end end
Use "mystery man" if there's no Gravatar image
# frozen_string_literal: true module UsersHelper # Returns the Gravatar for the given user. def gravatar_for(user) gravatar_id = Digest::MD5.hexdigest(user.email.downcase) gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}" image_tag(gravatar_url, alt: user.name, class: 'gravatar') end end
# frozen_string_literal: true module UsersHelper # Returns the Gravatar for the given user. def gravatar_for(user) gravatar_id = Digest::MD5.hexdigest(user.email.downcase) gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?d=mm" image_tag(gravatar_url, alt: user.name, class: 'gravatar') end end
Change to rails version 4.1.0
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "ct_angular_js_rails/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "ct_angular_js_rails" s.version = CtAngularJsRails::VERSION s.authors = ["Codetalay"] s.email = ["developer.codetalay@gmail.com"] s.homepage = "http://www.codetalay.com" s.summary = "Summary" s.description = "Description" s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 4.0.0" s.add_development_dependency "sqlite3" end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "ct_angular_js_rails/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "ct_angular_js_rails" s.version = CtAngularJsRails::VERSION s.authors = ["Codetalay"] s.email = ["developer.codetalay@gmail.com"] s.homepage = "http://www.codetalay.com" s.summary = "Summary" s.description = "Description" s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 4.1.0" s.add_development_dependency "sqlite3" end
Fix the contributions report on the project for channel admins
class Reports::ContributionReportsForProjectOwnersController < Reports::BaseController def index @report = end_of_association_chain.to_xls( columns: I18n.t('contribution_report_to_project_owner').values ) super do |format| format.xls { send_data @report, filename: 'apoiadores.xls' } end end def end_of_association_chain conditions = { project_id: params[:project_id] } conditions.merge!(reward_id: params[:reward_id]) if params[:reward_id].present? conditions.merge!(state: (params[:state].present? ? params[:state] : 'confirmed')) conditions.merge!(project_owner_id: current_user.id) unless current_user.try(:admin) report_sql = "" I18n.t('contribution_report_to_project_owner').keys[0..-2].each{ |column| report_sql << "#{column} AS \"#{I18n.t("contribution_report_to_project_owner.#{column}")}\"," } super. select(%Q{ #{report_sql} CASE WHEN anonymous='t' THEN '#{I18n.t('yes')}' WHEN anonymous='f' THEN '#{I18n.t('no')}' END as "#{I18n.t('contribution_report_to_project_owner.anonymous')}" }). where(conditions) end end
class Reports::ContributionReportsForProjectOwnersController < Reports::BaseController def index @report = end_of_association_chain.to_xls( columns: I18n.t('contribution_report_to_project_owner').values ) super do |format| format.xls { send_data @report, filename: 'apoiadores.xls' } end end def end_of_association_chain conditions = { project_id: params[:project_id] } conditions.merge!(reward_id: params[:reward_id]) if params[:reward_id].present? conditions.merge!(state: (params[:state].present? ? params[:state] : 'confirmed')) conditions.merge!(project_owner_id: current_user.id) unless (current_user.try(:admin) || (current_user.present? && channel.present? && channel.users.include?(current_user))) report_sql = "" I18n.t('contribution_report_to_project_owner').keys[0..-2].each{ |column| report_sql << "#{column} AS \"#{I18n.t("contribution_report_to_project_owner.#{column}")}\"," } super. select(%Q{ #{report_sql} CASE WHEN anonymous='t' THEN '#{I18n.t('yes')}' WHEN anonymous='f' THEN '#{I18n.t('no')}' END as "#{I18n.t('contribution_report_to_project_owner.anonymous')}" }). where(conditions) end end
Add check if remore is cloned
require 'securerandom' require 'erb' module Skyed # This module encapsulates all the Git features. module Git class << self def clone_stack_remote(stack, options) unless Skyed::Settings.current_stack?(stack[:stack_id]) Skyed::Init.opsworks_git_key options end ENV['PKEY'] ||= Skyed::Settings.opsworks_git_key Skyed::Utils.create_template('/tmp', 'ssh-git', 'ssh-git.erb', 0755) ENV['GIT_SSH'] = '/tmp/ssh-git' path = "/tmp/skyed.#{SecureRandom.hex}" r = ::Git.clone(stack[:custom_cookbooks_source][:url], path) puts r.path path end end end end
require 'securerandom' require 'erb' module Skyed # This module encapsulates all the Git features. module Git class << self def clone_stack_remote(stack, options) unless Skyed::Settings.current_stack?(stack[:stack_id]) Skyed::Init.opsworks_git_key options end ENV['PKEY'] ||= Skyed::Settings.opsworks_git_key Skyed::Utils.create_template('/tmp', 'ssh-git', 'ssh-git.erb', 0755) ENV['GIT_SSH'] = '/tmp/ssh-git' path = "/tmp/skyed.#{SecureRandom.hex}" r = ::Git.clone(stack[:custom_cookbooks_source][:url], path) puts repo_path(r) path end end end end
Print "T" instead of "True" for ruby interop
require_relative 'core' require_relative 'numbers' System_Print=->to_print{Kernel.print to_print} System_PrintLine=->to_print{System_Print[to_print+"\n"]} Raise=->to_raise{raise to_raise} ConvertToRubyNumber= ->number{ increment_ruby_number = ->result{->_{ IfZero[result][ ->_{Cons[False][1]} ][ ->_{Cons[False][Cdr[result]+1]} ] }} Cdr[NumbersReduce[increment_ruby_number][number]] } PrintNumber=->number{puts ConvertToRubyNumber[number]} def assert(expected, actual, msg = "") if(expected==actual) PrintTrue.(Noop) else Raise["Fail! expected #{expected}, got #{actual}. #{msg}"] end end
require_relative 'core' require_relative 'numbers' require_relative 'testing' System_Print=->to_print{Kernel.print to_print} System_PrintLine=->to_print{System_Print[to_print+"\n"]} Raise=->to_raise{raise to_raise} ConvertToRubyNumber= ->number{ increment_ruby_number = ->result{->_{ IfZero[result][ ->_{Cons[False][1]} ][ ->_{Cons[False][Cdr[result]+1]} ] }} Cdr[NumbersReduce[increment_ruby_number][number]] } PrintNumber=->number{puts ConvertToRubyNumber[number]} def assert(expected, actual, msg = "") if(expected==actual) Assert[True] else Raise["Fail! expected #{expected}, got #{actual}. #{msg}"] end end
Add RFC 141 healthcheck endpoints
ReleaseApp::Application.routes.draw do resources :applications do collection do get "archived", to: "applications#archived" end member do get :deploy get :stats end resources :deployments end resources :deployments resource :site, only: %i[show update] get "/activity", to: "deployments#recent", as: :activity get "/healthcheck", to: GovukHealthcheck.rack_response( GovukHealthcheck::ActiveRecord, ) get "/stats", to: "stats#index" root to: redirect("/applications", status: 302) if Rails.env.development? mount GovukAdminTemplate::Engine, at: "/style-guide" end end
ReleaseApp::Application.routes.draw do resources :applications do collection do get "archived", to: "applications#archived" end member do get :deploy get :stats end resources :deployments end resources :deployments resource :site, only: %i[show update] get "/activity", to: "deployments#recent", as: :activity get "/healthcheck", to: GovukHealthcheck.rack_response( GovukHealthcheck::ActiveRecord, ) get "/healthcheck/live", to: proc { [200, {}, %w[OK]] } get "/healthcheck/ready", to: GovukHealthcheck.rack_response( GovukHealthcheck::ActiveRecord, ) get "/stats", to: "stats#index" root to: redirect("/applications", status: 302) if Rails.env.development? mount GovukAdminTemplate::Engine, at: "/style-guide" end end
Allow curl to get HTML
HoustonLightning::Application.routes.draw do class FormatTest attr_accessor :mime_type def initialize(format) @mime_type = Mime::Type.lookup_by_extension(format) end def matches?(request) request.format == mime_type end end resources :talks, only: [:index, :create], :constraints => FormatTest.new(:json) post '/admin/authenticate', to: 'admin#authenticate', :constraints => FormatTest.new(:json) delete '/admin/destroy', to: 'admin#destroy', :constraints => FormatTest.new(:json) post '/admin/start', to: 'admin#start', :constraints => FormatTest.new(:json) get '*foo', :to => 'angular#index', :constraints => FormatTest.new(:html) get '/', :to => 'angular#index', :constraints => FormatTest.new(:html) end
HoustonLightning::Application.routes.draw do class FormatTest attr_accessor :mime_type def initialize(format) @mime_type = Mime::Type.lookup_by_extension(format) end def matches?(request) request.format == mime_type || request.format == '*/*' end end resources :talks, only: [:index, :create], :constraints => FormatTest.new(:json) post '/admin/authenticate', to: 'admin#authenticate', :constraints => FormatTest.new(:json) delete '/admin/destroy', to: 'admin#destroy', :constraints => FormatTest.new(:json) post '/admin/start', to: 'admin#start', :constraints => FormatTest.new(:json) get '*foo', :to => 'angular#index', :constraints => FormatTest.new(:html) get '/', :to => 'angular#index', :constraints => FormatTest.new(:html) end
Fix typo in integration test
require 'serverspec' # require 'mongo' include Serverspec::Helper::Exec include Serverspec::Helper::DetectOS describe file("/etc/mongodb/mongod.conf") do it { should be_file } it { should contain "port = 27018" } it { should contain "dbpath = /var/lib/mongo_data/mongod-primary" } end describe file("/etc/init/mongod-primary.conf") do it { should be_file } end describe port(27018) do it { should be_listening } end describe service('mongod-primary') do it { should be_enabled } it { should be_running } end # @TODO - work out how to load gems in test environment # # describe "mongo server" do # it "should have status = ok" do # retries = 0 # begin # connection = ::Mongo::MongoClient.new("127.0.0.1", 27018) # connection['test'].command({'serverStatus' => 1})['ok'].must_equal 1 # connection.close # rescue ::Mongo::ConnectionFailure # raise if retries >= 3 # retries += 1 # sleep(10) # retry # end # end # end
require 'serverspec' # require 'mongo' include Serverspec::Helper::Exec include Serverspec::Helper::DetectOS describe file("/etc/mongodb/mongod-primary.conf") do it { should be_file } it { should contain "port = 27018" } it { should contain "dbpath = /var/lib/mongo_data/mongod-primary" } end describe file("/etc/init/mongod-primary.conf") do it { should be_file } end describe port(27018) do it { should be_listening } end describe service('mongod-primary') do it { should be_enabled } it { should be_running } end # @TODO - work out how to load gems in test environment # # describe "mongo server" do # it "should have status = ok" do # retries = 0 # begin # connection = ::Mongo::MongoClient.new("127.0.0.1", 27018) # connection['test'].command({'serverStatus' => 1})['ok'].must_equal 1 # connection.close # rescue ::Mongo::ConnectionFailure # raise if retries >= 3 # retries += 1 # sleep(10) # retry # end # end # end
Update to mock controller in test
require_relative 'test_helper' class TestApp < Rulers::Application end class RulersAppTest < Test::Unit::TestCase include Rack::Test::Methods def app TestApp.new end def test_request get '/test' assert last_response.ok? body = last_response.body assert body['Hello'] end def test_to_underscore word = 'Rulers::HttpController' assert_equal 'rulers/http_controller', Rulers.to_underscore(word) word = 'Rulers::HTTPController' assert_equal 'rulers/http_controller', Rulers.to_underscore(word) word = 'Rulers::H4Controller' assert_equal 'rulers/h4_controller', Rulers.to_underscore(word) end end
require_relative 'test_helper' class TestController < Rulers::Controller def index 'Hello!' end end class TestApp < Rulers::Application def get_controller_and_action ['TestController', 'index'] end end class RulersAppTest < Test::Unit::TestCase include Rack::Test::Methods def app TestApp.new end def test_request get '/test' assert last_response.ok? body = last_response.body assert body['Hello'] end def test_to_underscore word = 'Rulers::HttpController' assert_equal 'rulers/http_controller', Rulers.to_underscore(word) word = 'Rulers::HTTPController' assert_equal 'rulers/http_controller', Rulers.to_underscore(word) word = 'Rulers::H4Controller' assert_equal 'rulers/h4_controller', Rulers.to_underscore(word) end end
Check for existence of exactly the called `fixture_path=` method
# Configure Rails Environment ENV["RAILS_ENV"] = "test" require File.expand_path("../dummy/config/environment.rb", __FILE__) require "rails/test_help" Rails.backtrace_cleaner.remove_silencers! # Load support files Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } # Load fixtures from the engine if ActiveSupport::TestCase.method_defined?(:fixture_path) ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__) end
# Configure Rails Environment ENV["RAILS_ENV"] = "test" require File.expand_path("../dummy/config/environment.rb", __FILE__) require "rails/test_help" Rails.backtrace_cleaner.remove_silencers! # Load support files Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } # Load fixtures from the engine if ActiveSupport::TestCase.method_defined?(:fixture_path=) ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__) end
Set rvm gemset in Capfile
# config valid only for current version of Capistrano lock '3.6.1' set :application, 'trinity' set :repo_url, 'git@github.com:NotyIm/trinity.git' # Default branch is :master # ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp # Default deploy_to directory is /var/www/my_app_name # set :deploy_to, '/var/www/my_app_name' # Default value for :scm is :git # set :scm, :git # Default value for :format is :airbrussh. # set :format, :airbrussh # You can configure the Airbrussh format using :format_options. # These are the defaults. # set :format_options, command_output: true, log_file: 'log/capistrano.log', color: :auto, truncate: :auto # Default value for :pty is false set :pty, true # Default value for :linked_files is [] # append :linked_files, 'config/database.yml', 'config/secrets.yml' # Default value for linked_dirs is [] # append :linked_dirs, 'log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'public/system' # Default value for default_env is {} # set :default_env, { path: "/opt/ruby/bin:$PATH" } # Default value for keep_releases is 5 set :keep_releases, 3
# config valid only for current version of Capistrano lock '3.6.1' set :application, 'trinity' set :repo_url, 'git@github.com:NotyIm/trinity.git' # Default branch is :master # ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp # Default deploy_to directory is /var/www/my_app_name # set :deploy_to, '/var/www/my_app_name' # Default value for :scm is :git # set :scm, :git # Default value for :format is :airbrussh. # set :format, :airbrussh # You can configure the Airbrussh format using :format_options. # These are the defaults. # set :format_options, command_output: true, log_file: 'log/capistrano.log', color: :auto, truncate: :auto # Default value for :pty is false set :pty, true # Default value for :linked_files is [] # append :linked_files, 'config/database.yml', 'config/secrets.yml' # Default value for linked_dirs is [] # append :linked_dirs, 'log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'public/system' # Default value for default_env is {} # set :default_env, { path: "/opt/ruby/bin:$PATH" } # Default value for keep_releases is 5 set :keep_releases, 3 set :rvm_ruby_version, '2.3.3@trinity'
Remove Centos 6 from this Cookbook
name 'resource_from_hash' maintainer 'Oregon State University' maintainer_email 'systems@osuosl.org' source_url 'https://github.com/osuosl-cookbooks/resource_from_hash' issues_url 'https://github.com/osuosl-cookbooks/resource_from_hash/issues' license 'Apache-2.0' chef_version '>= 14.0' description 'Installs/Configures resource_from_hash' version '1.2.2' supports 'centos', '~> 6.0' supports 'centos', '~> 7.0'
name 'resource_from_hash' maintainer 'Oregon State University' maintainer_email 'systems@osuosl.org' source_url 'https://github.com/osuosl-cookbooks/resource_from_hash' issues_url 'https://github.com/osuosl-cookbooks/resource_from_hash/issues' license 'Apache-2.0' chef_version '>= 14.0' description 'Installs/Configures resource_from_hash' version '1.2.2' supports 'centos', '~> 7.0'
Put the tour 'create your first factlink page' screenshot on pending
require 'integration_helper' describe "Check the tour", type: :request do before do @user = make_non_tos_user_and_login fill_in "user_agrees_tos_name", with: "Sko Brenden" check "user_agrees_tos" click_button "Next" end it 'You''re almost set page should be the same' do assume_unchanged_screenshot 'extension' end it 'Let''s create your first factlink page should be the same' do click_link "Skip this step" sleep 1 assume_unchanged_screenshot 'create_your_first_factlink' end end
require 'integration_helper' describe "Check the tour", type: :request do before do @user = make_non_tos_user_and_login fill_in "user_agrees_tos_name", with: "Sko Brenden" check "user_agrees_tos" click_button "Next" end it 'You''re almost set page should be the same' do assume_unchanged_screenshot 'extension' end pending 'Let''s create your first factlink page should be the same' do click_link "Skip this step" sleep 1 assume_unchanged_screenshot 'create_your_first_factlink' end end
Make special-case creation methods private.
module GirFFI # The InPointer class handles conversion from ruby types to pointers for # arguments with direction :in. This is used for arguments that are # arrays, strings, or interfaces. class InPointer < FFI::Pointer def self.from_array type, ary return nil if ary.nil? return self.from_utf8_array ary if type == :utf8 return self.from_interface_pointer_array ary if type == :interface_pointer ffi_type = GirFFI::Builder::TAG_TYPE_MAP[type] || type block = ArgHelper.allocate_array_of_type ffi_type, ary.length block.send "put_array_of_#{ffi_type}", 0, ary self.new block end def self.from type, val return nil if val.nil? self.new ArgHelper.utf8_to_inptr(val) end def self.from_utf8_array ary return nil if ary.nil? ptr_ary = ary.map {|str| self.from :utf8, str} ptr_ary << nil self.from_array :pointer, ptr_ary end def self.from_interface_pointer_array ary return nil if ary.nil? ptr_ary = ary.map {|ifc| ifc.to_ptr} ptr_ary << nil self.from_array :pointer, ptr_ary end end end
module GirFFI # The InPointer class handles conversion from ruby types to pointers for # arguments with direction :in. This is used for arguments that are # arrays, strings, or interfaces. class InPointer < FFI::Pointer def self.from_array type, ary return nil if ary.nil? return from_utf8_array ary if type == :utf8 return from_interface_pointer_array ary if type == :interface_pointer ffi_type = GirFFI::Builder::TAG_TYPE_MAP[type] || type block = ArgHelper.allocate_array_of_type ffi_type, ary.length block.send "put_array_of_#{ffi_type}", 0, ary self.new block end def self.from type, val return nil if val.nil? self.new ArgHelper.utf8_to_inptr(val) end class << self private def from_utf8_array ary ptr_ary = ary.map {|str| self.from :utf8, str} ptr_ary << nil self.from_array :pointer, ptr_ary end def from_interface_pointer_array ary ptr_ary = ary.map {|ifc| ifc.to_ptr} ptr_ary << nil self.from_array :pointer, ptr_ary end end end end
Fix Module as type in bean definitions
module Fabrique class BeanDefinition attr_reader :constructor_args, :factory_method, :id, :properties, :type def initialize(attrs = {}) @id = attrs["id"] type_name = attrs["class"] @type = type_name.is_a?(Module) ? @type_name : Module.const_get(type_name) @constructor_args = attrs["constructor_args"] || [] @constructor_args = keywordify(@constructor_args) if @constructor_args.is_a?(Hash) @properties = attrs["properties"] || {} @scope = attrs["scope"] || "singleton" @factory_method = attrs["factory_method"] || "new" end def dependencies (dependencies_of(@constructor_args) + dependencies_of(@properties)).uniq end def singleton? @scope == "singleton" end private def keywordify(args) args.inject({}) { |m, (k, v)| k = k.intern rescue k; m[k.intern] = v; m } end def dependencies_of(data, acc = []) if data.is_a?(Hash) dependencies_of(data.values, acc) elsif data.is_a?(Array) data.each do |o| dependencies_of(o, acc) end elsif data.is_a?(BeanReference) or data.is_a?(BeanPropertyReference) acc << data end acc end end end
module Fabrique class BeanDefinition attr_reader :constructor_args, :factory_method, :id, :properties, :type def initialize(attrs = {}) @id = attrs["id"] type_name = attrs["class"] @type = type_name.is_a?(Module) ? type_name : Module.const_get(type_name) @constructor_args = attrs["constructor_args"] || [] @constructor_args = keywordify(@constructor_args) if @constructor_args.is_a?(Hash) @properties = attrs["properties"] || {} @scope = attrs["scope"] || "singleton" @factory_method = attrs["factory_method"] || "new" end def dependencies (accumulate_dependencies(@constructor_args) + accumulate_dependencies(@properties)).uniq end def singleton? @scope == "singleton" end private def keywordify(args) args.inject({}) { |m, (k, v)| k = k.intern rescue k; m[k.intern] = v; m } end def accumulate_dependencies(data, acc = []) if data.is_a?(Hash) accumulate_dependencies(data.values, acc) elsif data.is_a?(Array) data.each do |o| accumulate_dependencies(o, acc) end elsif data.is_a?(BeanReference) or data.is_a?(BeanPropertyReference) acc << data end acc end end end
Use precondition to inherit params in spec test for mod::jk
require 'spec_helper' describe 'apache::mod::jk', :type => :class do it_behaves_like 'a mod class, without including apache' shared_examples 'minimal resources' do it { is_expected.to compile } it { is_expected.to compile.with_all_deps } it { is_expected.to create_class('apache::mod::jk') } it { is_expected.to contain_class('apache') } it { is_expected.to contain_apache__mod('jk') } it { is_expected.to contain_file('jk.conf').that_notifies('Class[apache::service]') } end context "with only required facts and no parameters" do let :facts do { :osfamily => 'RedHat', :operatingsystem => 'RedHat', :operatingsystemrelease => '6', } end let :params do { :log_file => '/var/log/httpd/mod_jk.log', :shm_file => '/var/log/httpd/jk-runtime-status', } end it_behaves_like 'minimal resources' it { verify_contents(catalogue, 'jk.conf', ['<IfModule jk_module>', '</IfModule>']) } end end
require 'spec_helper' describe 'apache::mod::jk', :type => :class do it_behaves_like 'a mod class, without including apache' shared_examples 'minimal resources' do it { is_expected.to compile } it { is_expected.to compile.with_all_deps } it { is_expected.to create_class('apache::mod::jk') } it { is_expected.to contain_class('apache') } it { is_expected.to contain_apache__mod('jk') } it { is_expected.to contain_file('jk.conf').that_notifies('Class[apache::service]') } end context "with only required facts and no parameters" do let :facts do { :osfamily => 'RedHat', :operatingsystem => 'RedHat', :operatingsystemrelease => '6', } end let(:pre_condition) do 'include apache' end it_behaves_like 'minimal resources' it { verify_contents(catalogue, 'jk.conf', ['<IfModule jk_module>', '</IfModule>']) } end end
Use 'strictly_current' scope for NoEnrolledStudentAlert
class CourseAlertManager def create_no_students_alerts courses_to_check = Course.current courses_to_check.each do |course| next unless course.students.empty? next unless within_no_student_alert_period?(course.timeline_start) next if Alert.exists?(course_id: course.id, type: 'NoEnrolledStudentsAlert') alert = Alert.create(type: 'NoEnrolledStudentsAlert', course_id: course.id) alert.email_course_admins end end private # Only create an alert if has been at least MIN_DAYS but less than # MAX_DAYS since the assignment start date. NO_STUDENT_ALERT_MIN_DAYS = 15 NO_STUDENT_ALERT_MAX_DAYS = 22 def within_no_student_alert_period?(date) return false unless date < NO_STUDENT_ALERT_MIN_DAYS.days.ago return false unless NO_STUDENT_ALERT_MAX_DAYS.days.ago < date true end end
class CourseAlertManager def create_no_students_alerts courses_to_check = Course.strictly_current courses_to_check.each do |course| next unless course.students.empty? next unless within_no_student_alert_period?(course.timeline_start) next if Alert.exists?(course_id: course.id, type: 'NoEnrolledStudentsAlert') alert = Alert.create(type: 'NoEnrolledStudentsAlert', course_id: course.id) alert.email_course_admins end end private # Only create an alert if has been at least MIN_DAYS but less than # MAX_DAYS since the assignment start date. NO_STUDENT_ALERT_MIN_DAYS = 15 NO_STUDENT_ALERT_MAX_DAYS = 22 def within_no_student_alert_period?(date) return false unless date < NO_STUDENT_ALERT_MIN_DAYS.days.ago return false unless NO_STUDENT_ALERT_MAX_DAYS.days.ago < date true end end
Remove factory girl from migration script
require_migration describe UpdateEmsInMiqAlertStatus do let(:miq_alert_status_stub) { migration_stub(:MiqAlertStatus) } migration_context :up do it 'it sets ems_id for vms' do ext = FactoryGirl.create(:ext_management_system) vm = FactoryGirl.create(:vm_cloud, :ext_management_system => ext) miq_alert_status = miq_alert_status_stub.create!(:resource_type => "VmOrTemplate", :resource_id => vm.id) expect(miq_alert_status.ems_id).to be_nil migrate expect(miq_alert_status.reload.ems_id).to eq(ext.id) end end end
require_migration class UpdateEmsInMiqAlertStatus < ActiveRecord::Migration[5.0] class ExtManagementSystem < ActiveRecord::Base self.inheritance_column = :_type_disabled # disable STI end class Vm < ActiveRecord::Base self.inheritance_column = :_type_disabled # disable STI belongs_to :ext_management_system, :foreign_key => :ems_id end end describe UpdateEmsInMiqAlertStatus do let(:miq_alert_status_stub) { migration_stub(:MiqAlertStatus) } let(:vm_cloud_stub) { migration_stub(:Vm) } let(:ext_management_system_stub) { migration_stub(:ExtManagementSystem) } migration_context :up do it 'it sets ems_id for vms' do ext = ext_management_system_stub.create vm = vm_cloud_stub.create(:ext_management_system => ext) miq_alert_status = miq_alert_status_stub.create!(:resource_type => "VmOrTemplate", :resource_id => vm.id) expect(miq_alert_status.ems_id).to be_nil migrate expect(miq_alert_status.reload.ems_id).to eq(ext.id) end end end
Stop crash if user not found; remove `@` symbols
class UsersController < ApplicationController # index: # /users # # search: # /users?perspective=0xff902fc776998336a213c5c6050a4572b7453643&skill=UX&depth=4 def index if params[:perspective] trust_graph_root_user = User.find_by(uport_address: params[:perspective]) @users = trust_graph_root_user.search_trust_graph(params[:skill], depth: params[:depth]) else @users = User.limit(200).includes(:skill_claims) end render json: @users.as_json(skills: true) end # GET /users/0x01d3b5eaa2e305a1553f0e2612353c94e597449e (uPort address) def show @user = User.find_or_create_by!(uport_address: params[:uport_address]) render json: @user.as_json(projects: true, skills: true, confirmations: true) UpdateProfile.perform_async @user.to_param # update profile info from uPort async end end
class UsersController < ApplicationController # index: # /users # # search: # /users?perspective=0xff902fc776998336a213c5c6050a4572b7453643&skill=UX&depth=4 def index if params[:perspective] trust_graph_root_user = User.find_by(uport_address: params[:perspective]) users = if trust_graph_root_user.nil? [] else trust_graph_root_user.search_trust_graph(params[:skill], depth: params[:depth]) end else users = User.limit(200).includes(:skill_claims) end render json: users.as_json(skills: true) end # GET /users/0x01d3b5eaa2e305a1553f0e2612353c94e597449e (uPort address) def show user = User.find_or_create_by!(uport_address: params[:uport_address]) render json: user.as_json(projects: true, skills: true, confirmations: true) UpdateProfile.perform_async user.to_param # update profile info from uPort async end end
Fix to the upgradeable? method to be all around better
module MetasploitDataModels::ActiveRecordModels::Session def self.included(base) base.class_eval { belongs_to :host, :class_name => "Mdm::Host" has_one :workspace, :through => :host, :class_name => "Mdm::Workspace" has_many :events, :class_name => "Mdm::SessionEvent", :order => "created_at", :dependent => :delete_all has_many :routes, :class_name => "Mdm::Route", :dependent => :delete_all scope :alive, where("closed_at IS NULL") scope :dead, where("closed_at IS NOT NULL") scope :upgradeable, where("closed_at IS NULL AND stype = 'shell' and platform ILIKE '%win%'") serialize :datastore, ::MetasploitDataModels::Base64Serializer.new before_destroy :stop def upgradeable? return true if (self.stype == 'shell' and self.platform =~ /win/) else return false end private def stop c = Pro::Client.get rescue nil c.session_stop(self.local_id) rescue nil # ignore exceptions (XXX - ideally, stopped an already-stopped session wouldn't throw XMLRPCException) end } end end
module MetasploitDataModels::ActiveRecordModels::Session def self.included(base) base.class_eval { belongs_to :host, :class_name => "Mdm::Host" has_one :workspace, :through => :host, :class_name => "Mdm::Workspace" has_many :events, :class_name => "Mdm::SessionEvent", :order => "created_at", :dependent => :delete_all has_many :routes, :class_name => "Mdm::Route", :dependent => :delete_all scope :alive, where("closed_at IS NULL") scope :dead, where("closed_at IS NOT NULL") scope :upgradeable, where("closed_at IS NULL AND stype = 'shell' and platform ILIKE '%win%'") serialize :datastore, ::MetasploitDataModels::Base64Serializer.new before_destroy :stop def upgradeable? (self.platform =~ /win/ and self.stype == 'shell') end private def stop c = Pro::Client.get rescue nil c.session_stop(self.local_id) rescue nil # ignore exceptions (XXX - ideally, stopped an already-stopped session wouldn't throw XMLRPCException) end } end end
Remove duplicate definition of replace_all field on MemberList
module NetSuite module Records class MemberList < Support::Sublist include Namespaces::ListAcct fields :replace_all sublist :item_member, ItemMember end end end
module NetSuite module Records class MemberList < Support::Sublist include Namespaces::ListAcct sublist :item_member, ItemMember end end end
Update Users model attribute comment
# == Schema Information # # Table name: users # # id :integer not null, primary key # first_name :string # last_name :string # ssn :string # dob :date # created_at :datetime not null # updated_at :datetime not null # phone_number :string # sex :string # vet_status :boolean # grade :decimal(8, 5) # class User < ApplicationRecord has_many :histories def letter_grade case grade when 80..100 'F' when 65...80 'D' when 50...65 'C' when 30...50 'B' when 0...30 'A' else 'unknown' end end def name "#{first_name} #{last_name}" end def entered_on created_at.to_date end def date_of_birth if dob.nil? "" else I18n.localize dob, format: :long end end end
# == Schema Information # # Table name: users # # id :integer not null, primary key # first_name :string # last_name :string # ssn :string # dob :date # created_at :datetime not null # updated_at :datetime not null # phone_number :string # grade :decimal(8, 5) # fleeing :boolean # incarcerated :boolean # welfare :boolean # insufficent_income :boolean # alcohol_or_drug_abuse :boolean # physical_health_issue :boolean # mental_health_issue :boolean # exchange_for_sex :boolean # sex :string # vet_status :boolean # class User < ApplicationRecord has_many :histories def letter_grade case grade when 80..100 'F' when 65...80 'D' when 50...65 'C' when 30...50 'B' when 0...30 'A' else 'unknown' end end def name "#{first_name} #{last_name}" end def entered_on created_at.to_date end def date_of_birth if dob.nil? "" else I18n.localize dob, format: :long end end end
Change route to share application
#module CatarseStripe #class Engine < ::Rails::Engine #isolate_namespace CatarseStripe #end #end module ActionDispatch::Routing class Mapper def mount_catarse_stripe_at(catarse_stripe) namespace CatarseStripe do namespeace :payment do get '/stripe/:id/review' => 'stripe#review', :as => 'review_stripe' post '/stripe/notifications' => 'stripe#ipn', :as => 'ipn_stripe' match '/stripe/:id/notifications' => 'stripe#notifications', :as => 'notifications_stripe' match '/stripe/:id/pay' => 'stripe#pay', :as => 'pay_stripe' match '/stripe/:id/success' => 'stripe#success', :as => 'success_stripe' match '/stripe/:id/cancel' => 'stripe#cancel', :as => 'cancel_stripe' match '/stripe/:id/charge' => 'stripe#charge', :as => 'charge_stripe' end end end end end
#module CatarseStripe #class Engine < ::Rails::Engine #isolate_namespace CatarseStripe #end #end module ActionDispatch::Routing class Mapper def mount_catarse_stripe_at(catarse_stripe) namespace CatarseStripe do namespace :payment do get '/stripe/:id/review' => 'stripe#review', :as => 'review_stripe' post '/stripe/notifications' => 'stripe#ipn', :as => 'ipn_stripe' match '/stripe/:id/notifications' => 'stripe#notifications', :as => 'notifications_stripe' match '/stripe/:id/pay' => 'stripe#pay', :as => 'pay_stripe' match '/stripe/:id/success' => 'stripe#success', :as => 'success_stripe' match '/stripe/:id/cancel' => 'stripe#cancel', :as => 'cancel_stripe' match '/stripe/:id/charge' => 'stripe#charge', :as => 'charge_stripe' end end end end end
Fix spec test for spanner quickstart
# Copyright 2016 Google, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "rspec" require "google/cloud/spanner" describe "Spanner Quickstart" do it "outputs a 1" do spanner = Google::Cloud::Spanner.new instance_id = ENV["GOOGLE_CLOUD_SPANNER_TEST_INSTANCE"] database_id = ENV["GOOGLE_CLOUD_SPANNER_TEST_DATABASE"] database_client = spanner.client instance_id, database_id expect(Google::Cloud::Spanner).to receive(:new). with(project: "YOUR_PROJECT_ID"). and_return(spanner) expect(spanner).to receive(:client). with("my-instance", "my-database"). and_return(database_client) expect { load File.expand_path("../quickstart.rb", __dir__) }.to output("1").to_stdout end end
# Copyright 2016 Google, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "rspec" require "google/cloud/spanner" describe "Spanner Quickstart" do it "outputs a 1" do spanner = Google::Cloud::Spanner.new instance_id = ENV["GOOGLE_CLOUD_SPANNER_TEST_INSTANCE"] database_id = ENV["GOOGLE_CLOUD_SPANNER_TEST_DATABASE"] database_client = spanner.client instance_id, database_id expect(Google::Cloud::Spanner).to receive(:new). with(project: "YOUR_PROJECT_ID"). and_return(spanner) expect(spanner).to receive(:client). with("my-instance", "my-database"). and_return(database_client) expect { load File.expand_path("../quickstart.rb", __dir__) }.to output(/1/).to_stdout end end
Add tests for Construi module
require 'spec_helper' RSpec.describe Construi do describe 'run' do let(:targets) { ['target1', 'target2'] } let(:config) { { 'image' => 'image:latest' } } let(:runner) { instance_double(Construi::Runner).as_null_object } let(:runner_class) { class_double(Construi::Runner).as_stubbed_const } before { allow(Construi::Config).to receive(:load_file).with('construi.yml').and_return(config) } before { allow(runner_class).to receive(:new).with(config).and_return runner } subject! { Construi.run(targets) } it { expect(runner_class).to have_received(:new).with(config) } it { expect(runner).to have_received(:run).with(targets) } end end
Add a default base_path for Organizer
module Catalog class Organizer def initialize(base_path:) @base_path = base_path end def run! new_documents.each do |document| matcher = DrawerMatcher.new(document: document) if matcher.match? DocumentMover.new(document: document, drawer: matcher.drawer).move! end end end private def new_documents unorganized_files.map { |path| Document.new(path: path) } end def unorganized_files Dir[File.expand_path(@base_path)].reject { |path| File.directory?(path) } end end end
module Catalog class Organizer def initialize(base_path: nil) @base_path = base_path || '~/Downloads/*' end def run! new_documents.each do |document| matcher = DrawerMatcher.new(document: document) if matcher.match? DocumentMover.new(document: document, drawer: matcher.drawer).move! end end true end private def new_documents unorganized_files.map { |path| Document.new(path: path) } end def unorganized_files Dir[File.expand_path(@base_path)].reject { |path| File.directory?(path) } end end end
Add caveat about setting NODENV_ROOT
class Nodenv < Formula homepage "https://github.com/OiNutter/nodenv" head "https://github.com/OiNutter/nodenv.git" url "https://github.com/OiNutter/nodenv/archive/v0.2.0.tar.gz" sha1 "ce66e6a546ad92b166c4133796df11cd9fbbbd5f" def install prefix.install "bin", "libexec" end def caveats; <<-EOS.undent To enable shims and autocompletion add to your profile: if which nodenv > /dev/null; then eval "$(nodenv init -)"; fi EOS end end
class Nodenv < Formula homepage "https://github.com/OiNutter/nodenv" head "https://github.com/OiNutter/nodenv.git" url "https://github.com/OiNutter/nodenv/archive/v0.2.0.tar.gz" sha1 "ce66e6a546ad92b166c4133796df11cd9fbbbd5f" def install prefix.install "bin", "libexec" end def caveats; <<-EOS.undent To enable shims and autocompletion add to your profile: if which nodenv > /dev/null; then eval "$(nodenv init -)"; fi To use Homebrew's directories rather than ~/.nodenv add to your profile: export NODENV_ROOT=#{opt_prefix}/nodenv EOS end end
Remove world priorities and news from search
edition_types_to_remove = [WorldwidePriority] if ! Whitehall.world_location_news_feature? edition_types_to_remove << WorldLocationNewsArticle end edition_types_to_remove.each do |klass| klass.all.each do |edition| next unless edition.latest_edition edition.remove_from_search_index puts "#{edition.title} removed from Rummager" end end
Add shader files to resources
Pod::Spec.new do |s| s.name = 'ResearchKit' s.version = '1.0.0' s.summary = 'ResearchKit is an open source software framework that makes it easy to create apps for medical research or for other research projects.' s.homepage = 'https://www.github.com/ResearchKit/ResearchKit' s.license = { :type => 'BSD', :file => 'LICENSE' } s.author = { "Apple Inc." => "http://apple.com" } s.source = { :git => 'https://github.com/ResearchKit/ResearchKit.git', :tag => "v#{s.version}"} s.source_files = 'ResearchKit/**/*' s.private_header_files = 'ResearchKit/**/*Private.h' s.resources = 'ResearchKit/Animations/**/*.m4v', 'ResearchKit/Artwork.xcassets', 'ResearchKit/Localized/*.lproj' s.platform = :ios, '8.0' s.requires_arc = true end
Pod::Spec.new do |s| s.name = 'ResearchKit' s.version = '1.0.0' s.summary = 'ResearchKit is an open source software framework that makes it easy to create apps for medical research or for other research projects.' s.homepage = 'https://www.github.com/ResearchKit/ResearchKit' s.license = { :type => 'BSD', :file => 'LICENSE' } s.author = { "Apple Inc." => "http://apple.com" } s.source = { :git => 'https://github.com/ResearchKit/ResearchKit.git', :tag => "v#{s.version}"} s.source_files = 'ResearchKit/**/*' s.private_header_files = 'ResearchKit/**/*Private.h' s.resources = 'ResearchKit/**/*.{fsh,vsh}', 'ResearchKit/Animations/**/*.m4v', 'ResearchKit/Artwork.xcassets', 'ResearchKit/Localized/*.lproj' s.platform = :ios, '8.0' s.requires_arc = true end
Resolve gem build warnings, add a license.
dir = File.dirname(__FILE__) require File.expand_path(File.join(dir, 'lib', 'logglier', 'version')) Gem::Specification.new do |s| s.name = 'logglier' s.version = Logglier::VERSION s.date = Time.now s.summary = 'Loggly "plugin" for Logger' s.description = 'Logger => Loggly' s.authors = ["Edward Muller (aka freeformz)"] s.email = 'edwardam@interlix.com' s.homepage = 'http://github.com/freeformz/logglier' s.files = %w{ README.md Gemfile LICENSE logglier.gemspec Rakefile } + Dir["lib/**/*.rb"] s.require_paths = ['lib'] s.test_files = Dir["spec/**/*.rb"] s.rubyforge_project = 'logglier' s.required_ruby_version = '>= 1.8.6' s.required_rubygems_version = '>= 1.3.6' s.add_dependency 'multi_json' s.add_development_dependency 'rake' s.add_development_dependency 'rspec', '~> 2.11.0' end
dir = File.dirname(__FILE__) require File.expand_path(File.join(dir, 'lib', 'logglier', 'version')) Gem::Specification.new do |s| s.name = 'logglier' s.version = Logglier::VERSION s.date = Time.now s.summary = 'Loggly "plugin" for Logger' s.description = 'Logger => Loggly' s.license = "http://opensource.org/licenses/Apache-2.0" s.authors = ["Edward Muller (aka freeformz)"] s.email = 'edwardam@interlix.com' s.homepage = 'http://github.com/freeformz/logglier' s.files = %w{ README.md Gemfile LICENSE logglier.gemspec Rakefile } + Dir["lib/**/*.rb"] s.require_paths = ['lib'] s.test_files = Dir["spec/**/*.rb"] s.rubyforge_project = 'logglier' s.required_ruby_version = '>= 1.8.6' s.required_rubygems_version = '>= 1.3.6' s.add_dependency 'multi_json', '~> 0' s.add_development_dependency 'rake', '~> 0' s.add_development_dependency 'rspec', '~> 2.11', '>= 2.11.0' end
Allow payload to be specified at init time
require 'net/http' module Juici class Callback attr_reader :url attr_accessor :payload def initialize(url) @url = url end def process! Net::HTTP.start(url.host, url.port) do |http| request = Net::HTTP::Post.new(url.request_uri) request.body = payload http.request request # Net::HTTPResponse object end end end end
require 'net/http' module Juici class Callback attr_reader :url attr_accessor :payload def initialize(url, pl=nil) @url = url @payload = pl if pl end def process! Net::HTTP.start(url.host, url.port) do |http| request = Net::HTTP::Post.new(url.request_uri) request.body = payload http.request request # Net::HTTPResponse object end end end end
Fix subtasks problem in Redmine 0.9.x
require 'redmine_charts/line_data_converter' require 'redmine_charts/pie_data_converter' require 'redmine_charts/stack_data_converter' require 'redmine_charts/utils' require 'redmine_charts/conditions_utils' require 'redmine_charts/grouping_utils' require 'redmine_charts/range_utils' require 'redmine_charts/issue_patch' require 'redmine_charts/time_entry_patch' module RedmineCharts def self.has_sub_issues_functionality_active ((Redmine::VERSION.to_a <=> [0,9,5]) >= 0) or (Redmine::VERSION.to_a == [0,9,4,'devel']) end end
require 'redmine_charts/line_data_converter' require 'redmine_charts/pie_data_converter' require 'redmine_charts/stack_data_converter' require 'redmine_charts/utils' require 'redmine_charts/conditions_utils' require 'redmine_charts/grouping_utils' require 'redmine_charts/range_utils' require 'redmine_charts/issue_patch' require 'redmine_charts/time_entry_patch' module RedmineCharts def self.has_sub_issues_functionality_active ((Redmine::VERSION.to_a <=> [1,0,0]) >= 0) end end
Add Meld for OSX v3.16.0 (r1)
cask 'meld' do version '3.16.0 (r1)' sha256 '324e096e0253e8ad4237f64a90cdda200fe427db8cf7ebc78143fc98e2d33ebc' # github.com/yousseb/meld was verified as official when first introduced to the cask url 'https://github.com/yousseb/meld/releases/download/osx-9/meldmerge.dmg' name 'Meld for OSX' homepage 'https://yousseb.github.io/meld/' license :gpl app 'Meld.app' end
Update xACT 2.25 to 2.27
class Xact < Cask url 'http://xact.scottcbrown.org/xACT2.25.zip' homepage 'http://xact.scottcbrown.org' version '2.25' sha256 '16425a50bdf9c8af8b436f88f4918145b553135a93887ae1ccddaad8edc79b51' link 'xACT 2.25/xACT.app' end
class Xact < Cask url 'http://xact.scottcbrown.org/xACT2.27.zip' homepage 'http://xact.scottcbrown.org' version '2.27' sha256 'a99965cc9c34838b2492dd99a5d5419123132b5eae30b7db5be14fc095750135' link 'xACT 2.27/xACT.app' end
Create a flag to include fakefs for specs
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'failspell'
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'rspec' require 'fakefs/safe' require 'fakefs/spec_helpers' require 'failspell' RSpec.configure do |config| config.include FakeFS::SpecHelpers, fakefs: true end
Support of Mac OS X 10.7
Pod::Spec.new do |s| s.name = 'Watt' s.version = '0.1' s.authors = { 'Benoit Pereira da Silva' => 'benoit@pereira-da-silva.com' } s.homepage = 'https://https://github.com/benoit-pereira-da-silva/Watt' s.summary = 'A multimedia - hypermedia engine' s.source = { :git => 'https://github.com/benoit-pereira-da-silva/Watt.git'} s.license = { :type => "LGPL", :file => "LICENSE" } s.platform = :ios, '5.0' s.requires_arc = true s.source_files = 'WattPlayer','WattPlayer/**/*.{h,m}' s.public_header_files = 'WattPlayer/**/*.h' s.ios.deployment_target = '5.0' end
Pod::Spec.new do |s| s.name = 'Watt' s.version = '0.1' s.authors = { 'Benoit Pereira da Silva' => 'benoit@pereira-da-silva.com' } s.homepage = 'https://https://github.com/benoit-pereira-da-silva/Watt' s.summary = 'A multimedia - hypermedia engine' s.source = { :git => 'https://github.com/benoit-pereira-da-silva/Watt.git'} s.license = { :type => "LGPL", :file => "LICENSE" } s.ios.deployment_target = '5.0' s.osx.deployment_target = '10.7' s.requires_arc = true s.source_files = 'WattPlayer','WattPlayer/**/*.{h,m}' s.public_header_files = 'WattPlayer/**/*.h' end
Update rubocop requirement from ~> 1.5.2 to ~> 1.6.0
# coding: utf-8 # frozen_string_literal: true lib = File.expand_path("lib", __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "business/version" Gem::Specification.new do |spec| spec.name = "business" spec.version = Business::VERSION spec.authors = ["Harry Marr"] spec.email = ["developers@gocardless.com"] spec.summary = "Date calculations based on business calendars" spec.description = "Date calculations based on business calendars" spec.homepage = "https://github.com/gocardless/business" spec.licenses = ["MIT"] spec.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR) 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_development_dependency "gc_ruboconfig", "~> 2.23.0" spec.add_development_dependency "rspec", "~> 3.1" spec.add_development_dependency "rspec_junit_formatter", "~> 0.4.1" spec.add_development_dependency "rubocop", "~> 1.5.2" end
# coding: utf-8 # frozen_string_literal: true lib = File.expand_path("lib", __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "business/version" Gem::Specification.new do |spec| spec.name = "business" spec.version = Business::VERSION spec.authors = ["Harry Marr"] spec.email = ["developers@gocardless.com"] spec.summary = "Date calculations based on business calendars" spec.description = "Date calculations based on business calendars" spec.homepage = "https://github.com/gocardless/business" spec.licenses = ["MIT"] spec.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR) 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_development_dependency "gc_ruboconfig", "~> 2.23.0" spec.add_development_dependency "rspec", "~> 3.1" spec.add_development_dependency "rspec_junit_formatter", "~> 0.4.1" spec.add_development_dependency "rubocop", "~> 1.6.0" end
Update SoundCloud Downloader to 2.6.4
cask :v1 => 'soundcloud-downloader' do version '2.6.2' sha256 'a68b69c3c1e523a1f93f8f9d774f8fa071e33cd0bbebdaaf7972103a58832005' url "http://black-burn.ch/scd/downloads/#{version.delete('.')}/ex/b" name 'SoundCloud Downloader' appcast 'http://black-burn.ch/applications/scd/updates.php?hwni=1', :sha256 => '3aec7755cdc3208b781ce41613d60f8e574f6c34e3fd819826e6734dd7aac70d' homepage 'http://black-burn.ch/scd/' license :mit app 'SoundCloud Downloader.app' end
cask :v1 => 'soundcloud-downloader' do version '2.6.4' sha256 'eabb5f3f7ef0db45a804a720069fa98160ff51ca6ec6e0184423f1f4ef98e0af' url "http://black-burn.ch/scd/downloads/#{version.delete('.')}/in/b" name 'SoundCloud Downloader' appcast 'http://black-burn.ch/applications/scd/updates.php?hwni=1', :sha256 => '3aec7755cdc3208b781ce41613d60f8e574f6c34e3fd819826e6734dd7aac70d' homepage 'http://black-burn.ch/scd/' license :mit app 'SoundCloud Downloader.app' end
Update to history's fork of model_stubbing to make compat with Edge Rails.
# Attempts to work around rails fixture loading module ModelStubbing module Extension def self.included(base) class << base attr_accessor :definition, :definition_inserted end base.extend ClassMethods if base.respond_to?(:prepend_after) base.prepend_after(:all) do if self.class.definition_inserted self.class.definition.teardown! self.class.definition_inserted = false end end end end module ClassMethods def create_model_methods_for(models) class_eval models.collect { |model| model.stub_method_definition }.join("\n") end end def database? defined?(ActiveRecord) end def setup_fixtures ModelStubbing.records.clear if self.class.definition unless self.class.definition_inserted self.class.definition.insert! self.class.definition_inserted = true end self.class.definition.setup_test_run end if database? ActiveRecord::Base.connection.increment_open_transactions ActiveRecord::Base.connection.begin_db_transaction end end def teardown_fixtures if self.class.definition self.class.definition.teardown_test_run end if database? ActiveRecord::Base.connection.rollback_db_transaction ActiveRecord::Base.verify_active_connections! end end def stubs(key) self.class.definition && self.class.definition.stubs[key] end def current_time self.class.definition && self.class.definition.current_time end end end
# Attempts to work around rails fixture loading module ModelStubbing module Extension def self.included(base) class << base attr_accessor :definition, :definition_inserted end base.extend ClassMethods if base.respond_to?(:prepend_after) base.prepend_after(:all) do if self.class.definition_inserted self.class.definition.teardown! self.class.definition_inserted = false end end end end module ClassMethods def create_model_methods_for(models) class_eval models.collect { |model| model.stub_method_definition }.join("\n") end end def database? defined?(ActiveRecord) end def setup_fixtures ModelStubbing.records.clear if self.class.definition unless self.class.definition_inserted self.class.definition.insert! self.class.definition_inserted = true end self.class.definition.setup_test_run end if database? ActiveRecord::Base.connection.increment_open_transactions ActiveRecord::Base.connection.begin_db_transaction end end def teardown_fixtures if self.class.definition self.class.definition.teardown_test_run end if database? ActiveRecord::Base.connection.rollback_db_transaction ActiveRecord::Base.connection.decrement_open_transactions ActiveRecord::Base.verify_active_connections! end end def stubs(key) self.class.definition && self.class.definition.stubs[key] end def current_time self.class.definition && self.class.definition.current_time end end end
Support equality checks for Kafka::PendingMessage
module Kafka class PendingMessage attr_reader :value, :key, :topic, :partition, :partition_key, :create_time, :bytesize def initialize(value, key, topic, partition, partition_key, create_time) @value = value @key = key @topic = topic @partition = partition @partition_key = partition_key @create_time = create_time @bytesize = key.to_s.bytesize + value.to_s.bytesize end end end
module Kafka class PendingMessage attr_reader :value, :key, :topic, :partition, :partition_key, :create_time, :bytesize def initialize(value, key, topic, partition, partition_key, create_time) @value = value @key = key @topic = topic @partition = partition @partition_key = partition_key @create_time = create_time @bytesize = key.to_s.bytesize + value.to_s.bytesize end def ==(other) @value == other.value && @key == other.key && @topic == other.topic && @partition == other.partition && @partition_key == other.partition_key && @create_time == other.create_time && @bytesize == other.bytesize end end end
Fix AssociationLoader Rails 7 Deprecation Warning
class AssociationLoader < GraphQL::Batch::Loader def self.validate(model, association_name) new(model, association_name) nil end def initialize(model, association_name) super() @model = model @association_name = association_name validate end def load(record) raise TypeError, "#{@model} loader can't load association for #{record.class}" unless record.is_a?(@model) return Promise.resolve(read_association(record)) if association_loaded?(record) super end # We want to load the associations on all records, even if they have the same id def cache_key(record) record.object_id end def perform(records) preload_association(records) records.each { |record| fulfill(record, read_association(record)) } end private def validate unless @model.reflect_on_association(@association_name) raise ArgumentError, "No association #{@association_name} on #{@model}" end end def preload_association(records) ::ActiveRecord::Associations::Preloader.new.preload(records, @association_name) end def read_association(record) record.public_send(@association_name) end def association_loaded?(record) record.association(@association_name).loaded? end end
class AssociationLoader < GraphQL::Batch::Loader def self.validate(model, association_name) new(model, association_name) nil end def initialize(model, association_name) super() @model = model @association_name = association_name validate end def load(record) raise TypeError, "#{@model} loader can't load association for #{record.class}" unless record.is_a?(@model) return Promise.resolve(read_association(record)) if association_loaded?(record) super end # We want to load the associations on all records, even if they have the same id def cache_key(record) record.object_id end def perform(records) preload_association(records) records.each { |record| fulfill(record, read_association(record)) } end private def validate unless @model.reflect_on_association(@association_name) raise ArgumentError, "No association #{@association_name} on #{@model}" end end def preload_association(records) ::ActiveRecord::Associations::Preloader.new(records: records, associations: @association_name).call end def read_association(record) record.public_send(@association_name) end def association_loaded?(record) record.association(@association_name).loaded? end end
Send application activity for channel creation as well as deletion.
class ChannelObserver < ActiveRecord::Observer def after_destroy(channel) broadcast_data = { :event => "channel#delete", :entity => channel.attributes, :extra => {} } Kandan::Config.broadcaster.broadcast("/app/activities", broadcast_data) end end
class ChannelObserver < ActiveRecord::Observer def after_destroy(channel) broadcast('delete', channel) end def after_create(channel) broadcast('create', channel) end private def broadcast(event, channel) data = { :event => "channel#" << event, :entity => channel.attributes, :extra => {} } Kandan::Config.broadcaster.broadcast("/app/activities", data) end end
Fix parsing of author id
module WpPost extend ActiveSupport::Concern included do serialize :acf_fields end def update_post(json) self.class.mappable_wordpress_attributes.each do |wp_attribute| send("#{wp_attribute}=", json[wp_attribute]) end self.wp_id = json['ID'] self.author_id = json['author'] self.published_at = json['date'] self.order = json['menu_order'] save! end module ClassMethods def mappable_wordpress_attributes %w( slug title status content excerpt acf_fields ) end end end
module WpPost extend ActiveSupport::Concern included do serialize :acf_fields end def update_post(json) self.class.mappable_wordpress_attributes.each do |wp_attribute| send("#{wp_attribute}=", json[wp_attribute]) end self.wp_id = json['ID'] self.author_id = json['author']['ID'] self.published_at = json['date'] self.order = json['menu_order'] save! end module ClassMethods def mappable_wordpress_attributes %w( slug title status content excerpt acf_fields ) end end end
Make application recipe deploy more than one application.
# # Cookbook Name:: application # Recipe:: default # # Copyright 2009, Opscode, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # search(:apps) do |app| (app["server_roles"] & node.run_list.roles).each do |app_role| app["type"][app_role].each do |thing| node.run_state[:current_app] = app include_recipe "application::#{thing}" end end end node.run_state.delete(:current_app)
# # Cookbook Name:: application # Recipe:: default # # Copyright 2009, Opscode, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # search(:apps) do |app| (app["server_roles"] & node.run_list.roles).each do |app_role| app["type"][app_role].each do |thing| node.run_state[:current_app] = app # Force include_recipe node.run_state[:seen_recipes].delete("application::#{thing}") include_recipe "application::#{thing}" end end end node.run_state.delete(:current_app)
Fix AbcSize RuboCop offense recently introduced
require 'forwardable' require 'byebug/helpers/reflection' require 'byebug/command_list' module Byebug # # Subcommand additions. # module Subcommands def self.included(command) command.extend(ClassMethods) end extend Forwardable def_delegators :'self.class', :subcommand_list # # Delegates to subcommands or prints help if no subcommand specified. # def execute return puts(help) unless @match[1] subcmd = subcommand_list.match(@match[1]) fail CommandNotFound.new(@match[1], self.class) unless subcmd subcmd.new(processor, arguments).execute rescue => e errmsg(e.message) end # # Class methods added to subcommands # module ClassMethods include Helpers::ReflectionHelper # # Default help text for a command with subcommands # def help super + subcommand_list.to_s end # # Command's subcommands. # def subcommand_list @subcommand_list ||= CommandList.new(commands) end end end end
require 'forwardable' require 'byebug/helpers/reflection' require 'byebug/command_list' module Byebug # # Subcommand additions. # module Subcommands def self.included(command) command.extend(ClassMethods) end extend Forwardable def_delegators :'self.class', :subcommand_list # # Delegates to subcommands or prints help if no subcommand specified. # def execute subcmd_name = @match[1] return puts(help) unless subcmd_name subcmd = subcommand_list.match(subcmd_name) fail CommandNotFound.new(subcmd_name, self.class) unless subcmd subcmd.new(processor, arguments).execute rescue => e errmsg(e.message) end # # Class methods added to subcommands # module ClassMethods include Helpers::ReflectionHelper # # Default help text for a command with subcommands # def help super + subcommand_list.to_s end # # Command's subcommands. # def subcommand_list @subcommand_list ||= CommandList.new(commands) end end end end
Package version is increased from 2.5.1.1 to 2.5.1.2
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'evt-messaging' s.version = '2.5.1.1' s.summary = 'Common primitives for platform-specific messaging implementations 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.4.0' s.add_runtime_dependency 'evt-message_store' s.add_development_dependency 'test_bench' end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'evt-messaging' s.version = '2.5.1.2' s.summary = 'Common primitives for platform-specific messaging implementations 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.4.0' s.add_runtime_dependency 'evt-message_store' s.add_development_dependency 'test_bench' end
Create migration test for removing Type / Template/VMs filters
require_migration describe RemoveTypeTemplateAndVmsFiltersFromMiqSearch do let(:miq_search_stub) { migration_stub(:MiqSearch) } migration_context :up do it "removes Type Template/VMs filters from MiqSearch" do filter_1 = miq_search_stub.create!(described_class::TEMPLATE_TYPE_FILTER) filter_2 = miq_search_stub.create!(described_class::VMS_TYPE_FILTER) filter_3 = miq_search_stub.create!(:name => 'Template/VMs test filter') migrate filter_1 = miq_search_stub.find_by(:id => filter_1.id) filter_2 = miq_search_stub.find_by(:id => filter_2.id) filter_3 = miq_search_stub.find_by(:id => filter_3.id) expect(filter_1).to be_nil expect(filter_2).to be_nil expect(filter_3).to_not be_nil end end migration_context :down do it "adds Type Template/VMs filters to MiqSearch" do migrate temp_filter = described_class::TEMPLATE_TYPE_FILTER.dup temp_filter.except!(:filter, :search_type) filter_1 = miq_search_stub.where(temp_filter).first vms_filter = described_class::VMS_TYPE_FILTER.dup vms_filter.except!(:filter, :search_type) filter_2 = miq_search_stub.where(vms_filter).first expect(filter_1).to_not have_attributes(described_class::TEMPLATE_TYPE_FILTER) expect(filter_2).to_not have_attributes(described_class::VMS_TYPE_FILTER) end end end
Make test email come from the default email sender, not the error sender
class TestMailers < ActionMailer::Base def email() mail(to: EXCEPTION_RECIPIENTS, from: EXCEPTION_SENDER, subject: "Libra2 Test Email") end end
class TestMailers < ActionMailer::Base def email() mail(to: EXCEPTION_RECIPIENTS, from: MAIL_SENDER, subject: "Libra2 Test Email") end end
Fix `ArgumentError: wrong number of arguments (given 1, expected 2)`
module Certman class CLI < Thor desc 'request [DOMAIN]', 'Request ACM Certificate with only AWS managed services' option :remain_resources, type: :boolean, default: false option :hosted_zone, type: :string def request(domain) pastel = Pastel.new prompt = TTY::Prompt.new return unless prompt.yes?(pastel.red("NOTICE! Your selected region is *#{Aws.config[:region]}*. \ Certman create certificate on *#{Aws.config[:region]}*. OK?")) client = Certman::Client.new(domain, options) return unless prompt.yes?(pastel.red("NOTICE! Certman use *#{client.region_by_hash}* S3/SES. OK?")) return unless prompt.yes?(pastel.red("NOTICE! When requesting, Certman apend Receipt Rule to current Active \ Receipt Rule Set. OK?")) Signal.trap(:INT) do puts '' puts pastel.red('Rollback start.') client.rollback end cert_arn = client.request puts 'Done.' puts '' puts "certificate_arn: #{pastel.cyan(cert_arn)}" puts '' end desc 'delete [DOMAIN]', 'Delete ACM Certificate' def delete(domain) Certman::Client.new(domain).delete puts 'Done.' puts '' end end end
module Certman class CLI < Thor desc 'request [DOMAIN]', 'Request ACM Certificate with only AWS managed services' option :remain_resources, type: :boolean, default: false option :hosted_zone, type: :string def request(domain) pastel = Pastel.new prompt = TTY::Prompt.new return unless prompt.yes?(pastel.red("NOTICE! Your selected region is *#{Aws.config[:region]}*. \ Certman create certificate on *#{Aws.config[:region]}*. OK?")) client = Certman::Client.new(domain, options) return unless prompt.yes?(pastel.red("NOTICE! Certman use *#{client.region_by_hash}* S3/SES. OK?")) return unless prompt.yes?(pastel.red("NOTICE! When requesting, Certman apend Receipt Rule to current Active \ Receipt Rule Set. OK?")) Signal.trap(:INT) do puts '' puts pastel.red('Rollback start.') client.rollback end cert_arn = client.request puts 'Done.' puts '' puts "certificate_arn: #{pastel.cyan(cert_arn)}" puts '' end desc 'delete [DOMAIN]', 'Delete ACM Certificate' def delete(domain) Certman::Client.new(domain, options).delete puts 'Done.' puts '' end end end
Add Parser which extracts all doctests from a file
module Dest class Parser EXPRESSION = /\s*#\s*>>\s*(?<expression>.*)/ # Matches the beginning of an expression RESULT = /\s*#\s*=>\s*(?<result>.*)/ # Matches the beginning of a result def initialize(filename) @filename = filename end # Return value is a hash following this structure # { :filename => 'something.rb', # :values => [ [1, 'sum(5, 5)', '10'] ] ( Array of Arrays. [ line_number, expression, result]) # } def parse parsed_output = { :filename => @filename, :values => [] } File.open(@filename).each_line.with_index do |line, num| next if line.lstrip[0] != "#" if expr = line.match(EXPRESSION) parsed_output[:values].push [num, expr["expression"]] elsif result = line.match(RESULT) parsed_output[:values].last.push(result["result"]) end end parsed_output end def self.parse(filename) self.new(filename).parse end end end
Make sure ARC is required
Pod::Spec.new do |s| s.name = "UIColor-HNExtensions" s.version = "0.1" s.summary = "A grab-bag of useful UIColor helpers" s.description = <<-DESC A category full of useful UIColor helper methods for dealing with * Colour components * Colour Palettes * Accessibility * Gradients * Blending DESC s.homepage = "https://github.com/henrinormak/UIColor-HNExtensions" s.license = { :type => 'MIT' } s.author = { "Henri Normak" => "henri.normak@gmail.com" } s.platform = :ios s.platform = :ios, '7.0' s.source = { :git => "https://github.com/henrinormak/UIColor-HNExtensions.git", :tag => "0.1" } s.source_files = 'UIColor+HNExtensions.{h,m}' end
Pod::Spec.new do |s| s.name = "UIColor-HNExtensions" s.version = "0.1" s.summary = "A grab-bag of useful UIColor helpers" s.description = <<-DESC A category full of useful UIColor helper methods for dealing with * Colour components * Colour Palettes * Accessibility * Gradients * Blending DESC s.homepage = "https://github.com/henrinormak/UIColor-HNExtensions" s.license = { :type => 'MIT' } s.author = { "Henri Normak" => "henri.normak@gmail.com" } s.platform = :ios s.platform = :ios, '7.0' s.source = { :git => "https://github.com/henrinormak/UIColor-HNExtensions.git", :tag => "0.1" } s.source_files = 'UIColor+HNExtensions.{h,m}' s.requires_arc = true end
Use sass compiler only if the environment is not production.
module Nilgiri class App < Padrino::Application register SassInitializer use ActiveRecord::ConnectionAdapters::ConnectionManagement register Padrino::Rendering register Padrino::Mailer register Padrino::Helpers register Padrino::Sprockets sprockets enable :sessions end end
module Nilgiri class App < Padrino::Application register SassInitializer unless Padrino.env == :production use ActiveRecord::ConnectionAdapters::ConnectionManagement register Padrino::Rendering register Padrino::Mailer register Padrino::Helpers register Padrino::Sprockets sprockets enable :sessions end end
Set default output style to be expanded.
require 'compass/import-once/activate' # Require any additional compass plugins here. require 'compass-normalize' # Set this to the root of your project when deployed: http_path = "/" css_dir = "static/css" sass_dir = "sass" images_dir = "static/images" javascripts_dir = "static/js" fonts_dir = "static/fonts" # You can select your preferred output style here (can be overridden via the command line): # output_style = :expanded or :nested or :compact or :compressed # To enable relative paths to assets via compass helper functions. Uncomment: #relative_assets = true # To disable debugging comments that display the original location of your selectors. Uncomment: line_comments = false # If you prefer the indented syntax, you might want to regenerate this # project again passing --syntax sass, or you can uncomment this: # preferred_syntax = :sass # and then run: # sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv scss sass
require 'compass/import-once/activate' # Require any additional compass plugins here. require 'compass-normalize' # Set this to the root of your project when deployed: http_path = "/" css_dir = "static/css" sass_dir = "sass" images_dir = "static/images" javascripts_dir = "static/js" fonts_dir = "static/fonts" # You can select your preferred output style here (can be overridden via the command line): # output_style = :expanded or :nested or :compact or :compressed output_style = :expanded # To enable relative paths to assets via compass helper functions. Uncomment: #relative_assets = true # To disable debugging comments that display the original location of your selectors. Uncomment: line_comments = false # If you prefer the indented syntax, you might want to regenerate this # project again passing --syntax sass, or you can uncomment this: # preferred_syntax = :sass # and then run: # sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv scss sass
Fix generation of links to remove individual filters
module FilterHelper def filter_option_link(site, type, options = {}) selected = options[:selected] link_to filter_site_mappings_path(site), 'class' => "filter-option #{'filter-selected' if selected}", 'data-toggle' => 'dropdown', 'role' => 'button' do "#{type} <span class=\"glyphicon glyphicon-chevron-down\"></span>".html_safe end end def filter_remove_option_link(site, type, type_sym) link_to site_mappings_path(site, params.except(type_sym, :page)), title: 'Remove filter', class: 'filter-option filter-selected' do "<span class=\"glyphicon glyphicon-remove\"></span><span class=\"rm\">Remove</span> #{type}".html_safe end end ## # When rendering a single filter form for a dropdown we need to pass through # all the other existing filter field values def hidden_filter_fields_except(filter, field) hidden_fields = (View::Mappings::Filter.fields - [field]).map do |name| value = filter.try(name) hidden_field_tag(name, value) unless value.blank? end hidden_fields.join("\n").html_safe end end
module FilterHelper def filter_option_link(site, type, options = {}) selected = options[:selected] link_to filter_site_mappings_path(site), 'class' => "filter-option #{'filter-selected' if selected}", 'data-toggle' => 'dropdown', 'role' => 'button' do "#{type} <span class=\"glyphicon glyphicon-chevron-down\"></span>".html_safe end end def filter_remove_option_link(site, type, type_sym) link_to site_mappings_path(params.except(type_sym, :page)), title: 'Remove filter', class: 'filter-option filter-selected' do "<span class=\"glyphicon glyphicon-remove\"></span><span class=\"rm\">Remove</span> #{type}".html_safe end end ## # When rendering a single filter form for a dropdown we need to pass through # all the other existing filter field values def hidden_filter_fields_except(filter, field) hidden_fields = (View::Mappings::Filter.fields - [field]).map do |name| value = filter.try(name) hidden_field_tag(name, value) unless value.blank? end hidden_fields.join("\n").html_safe end end
Update rspec-rails 3.0.0.beta1 -> 3.0.0.beta2
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'simple_bootstrap_form/version' Gem::Specification.new do |spec| spec.name = "simple_bootstrap_form" spec.version = SimpleBootstrapForm::VERSION spec.authors = ["Sam Pierson"] spec.email = ["gems@sampierson.com"] spec.summary = %q{Bootstrap 3 Form Helper} spec.description = %q{A form helper with a 'Simple Form'-like interface, that supports Bootstrap 3} spec.homepage = "https://github.com/Piersonally/simple_bootstrap_form" spec.license = "MIT" spec.files = `git ls-files`.split($/) 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_development_dependency "bundler", "~> 1.5" spec.add_development_dependency "rake" spec.add_development_dependency "rspec-rails", ">= 3.0.0.beta1" spec.add_development_dependency "sqlite3" spec.add_development_dependency "nokogiri" # used by has_element matcher spec.add_runtime_dependency "rails", ">= 4" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'simple_bootstrap_form/version' Gem::Specification.new do |spec| spec.name = "simple_bootstrap_form" spec.version = SimpleBootstrapForm::VERSION spec.authors = ["Sam Pierson"] spec.email = ["gems@sampierson.com"] spec.summary = %q{Bootstrap 3 Form Helper} spec.description = %q{A form helper with a 'Simple Form'-like interface, that supports Bootstrap 3} spec.homepage = "https://github.com/Piersonally/simple_bootstrap_form" spec.license = "MIT" spec.files = `git ls-files`.split($/) 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_development_dependency "bundler", "~> 1.5" spec.add_development_dependency "rake" spec.add_development_dependency "rspec-rails", ">= 3.0.0.beta2" spec.add_development_dependency "sqlite3" spec.add_development_dependency "nokogiri" # used by has_element matcher spec.add_runtime_dependency "rails", ">= 4" end
Allow additional raw zone content for Bind generator
module Dyndnsd module Generator class Bind def initialize(domain, config) @domain = domain @ttl = config['ttl'] @dns = config['dns'] @email_addr = config['email_addr'] end def generate(zone) out = [] out << "$TTL #{@ttl}" out << "$ORIGIN #{@domain}." out << "" out << "@ IN SOA #{@dns} #{@email_addr} ( #{zone['serial']} 3h 5m 1w 1h )" out << "@ IN NS #{@dns}" out << "" zone['hosts'].each do |hostname,ip| name = hostname.chomp('.' + @domain) out << "#{name} IN A #{ip}" end out << "" out.join("\n") end end end end
module Dyndnsd module Generator class Bind def initialize(domain, config) @domain = domain @ttl = config['ttl'] @dns = config['dns'] @email_addr = config['email_addr'] @additional_zone_content = config['additional_zone_content'] end def generate(zone) out = [] out << "$TTL #{@ttl}" out << "$ORIGIN #{@domain}." out << "" out << "@ IN SOA #{@dns} #{@email_addr} ( #{zone['serial']} 3h 5m 1w 1h )" out << "@ IN NS #{@dns}" out << "" zone['hosts'].each do |hostname,ip| name = hostname.chomp('.' + @domain) out << "#{name} IN A #{ip}" end out << "" out << @additional_zone_content out << "" out.join("\n") end end end end
Update the URL for the allele registry to the production server
class AlleleRegistry attr_reader :variant def initialize(variant_id) @variant = Variant.find(variant_id) end def response Rails.cache.fetch(cache_key(variant.id), expires_in: 24.hours) do if hgvs = HgvsExpression.allele_registry_hgvs(variant) make_request(hgvs) else {} end end end private def make_request(hgvs) Scrapers::Util.make_get_request(allele_registry_url(hgvs)) rescue StandardError {} end def allele_registry_url(coordinate_string) URI.encode("http://reg.test.genome.network/allele?hgvs=#{coordinate_string}") end def cache_key(variant_id) "allele_registry_#{variant_id}" end end
class AlleleRegistry attr_reader :variant def initialize(variant_id) @variant = Variant.find(variant_id) end def response Rails.cache.fetch(cache_key(variant.id), expires_in: 24.hours) do if hgvs = HgvsExpression.allele_registry_hgvs(variant) make_request(hgvs) else {} end end end private def make_request(hgvs) Scrapers::Util.make_get_request(allele_registry_url(hgvs)) rescue StandardError {} end def allele_registry_url(coordinate_string) URI.encode("http://reg.genome.network/allele?hgvs=#{coordinate_string}") end def cache_key(variant_id) "allele_registry_#{variant_id}" end end
Add status override to liquid rendering
module LiquidRenderer class Railtie < ::Rails::Railtie config.liquid_renderer = ActiveSupport::OrderedOptions.new initializer 'liquid_renderer.initialize' do |app| app.config.liquid_renderer.content_for_layout ||= 'content_for_layout' ActiveSupport.on_load(:action_controller) do require 'liquid' require 'liquid-renderer/render' ActionController::Renderers.add :liquid do |content, options| content_type = options.delete(:content_type) || 'text/html' render :text => LiquidRenderer.render(content, options), :content_type => content_type end end end end end
module LiquidRenderer class Railtie < ::Rails::Railtie config.liquid_renderer = ActiveSupport::OrderedOptions.new initializer 'liquid_renderer.initialize' do |app| app.config.liquid_renderer.content_for_layout ||= 'content_for_layout' ActiveSupport.on_load(:action_controller) do require 'liquid' require 'liquid-renderer/render' ActionController::Renderers.add :liquid do |content, options| content_type = options.delete(:content_type) || 'text/html' status = options.delete(:status) || :ok render text: LiquidRenderer.render(content, options), content_type: content_type, status: status end end end end end
Add some debugging that is temporary for production
class CuttlefishLogDaemon def self.start(file) begin while true if File.exists?(file) File::Tail::Logfile.open(file) do |log| log.tail do |line| PostfixLogLine.transaction do log_line = PostfixLogLine.create_from_line(line) # Check if an email needs to be blacklisted if log_line && log_line.status == "hard_bounce" # We don't want to save duplicates if BlackList.find_by(team_id: log_line.delivery.app.team_id, address: log_line.delivery.address).nil? BlackList.create(team_id: log_line.delivery.app.team_id, address: log_line.delivery.address, caused_by_delivery: log_line.delivery) end end end end end else sleep(10) end end rescue SignalException => e if e.to_s == "SIGTERM" puts "Received SIGTERM. Shutting down..." else raise e end end end end
class CuttlefishLogDaemon def self.start(file) begin while true if File.exists?(file) File::Tail::Logfile.open(file) do |log| log.tail do |line| PostfixLogLine.transaction do log_line = PostfixLogLine.create_from_line(line) # Check if an email needs to be blacklisted if log_line && log_line.status == "hard_bounce" # We don't want to save duplicates if BlackList.find_by(team_id: log_line.delivery.app.team_id, address: log_line.delivery.address).nil? # TEMPORARY addition to debug something in production if log_line.delivery.app.team_id.nil? puts "team_id is NIL" p log_line p line end BlackList.create(team_id: log_line.delivery.app.team_id, address: log_line.delivery.address, caused_by_delivery: log_line.delivery) end end end end end else sleep(10) end end rescue SignalException => e if e.to_s == "SIGTERM" puts "Received SIGTERM. Shutting down..." else raise e end end end end
Add serverspec tests for racktables::application.
# Tests for specific Racktable application items require 'serverspec' describe user('racktables') do it { should exist } it { should belong_to_group 'racktables' } it { should have_login_shell '/bin/false' } end describe file('/var/www/racktables/wwwroot/inc/secret.php') do it { should be_a_file} its(:content) { should match /\$pdo_dsn/ } its(:content) { should match /\$user_auth_src/ } end
Remove unnecessary parenthesis from exception
# encoding: utf-8 namespace :metrics do allowed_versions = %w(mri-1.9.3 rbx-1.9.3) if allowed_versions.include?(Devtools.rvm) && system("which mutant > #{File::NULL}") desc 'Run mutant' task :mutant => :coverage do project = Devtools.project config = project.mutant cmd = %[mutant -r ./spec/spec_helper.rb "::#{config.namespace}" --rspec-dm2] Kernel.system(cmd) || raise('Mutant task is not successful') end else desc 'Run Mutant' task :mutant => :coverage do $stderr.puts 'Mutant is disabled' end end end
# encoding: utf-8 namespace :metrics do allowed_versions = %w(mri-1.9.3 rbx-1.9.3) if allowed_versions.include?(Devtools.rvm) && system("which mutant > #{File::NULL}") desc 'Run mutant' task :mutant => :coverage do project = Devtools.project config = project.mutant cmd = %[mutant -r ./spec/spec_helper.rb "::#{config.namespace}" --rspec-dm2] Kernel.system(cmd) or raise 'Mutant task is not successful' end else desc 'Run Mutant' task :mutant => :coverage do $stderr.puts 'Mutant is disabled' end end end
Use JRuby's rubyised method names
require 'spec_helper' require 'saxon/processor' describe Saxon::Processor do let(:processor) { Saxon::Processor.new } let(:xsl_file) { File.open(fixture_path('eg.xsl')) } it "can make a new XSLT instance" do expect(processor.XSLT(xsl_file)).to respond_to(:transform) end it "can make a new XML instance" do expect(processor.XML(xsl_file)).to respond_to(:getNodeKind) end end
require 'spec_helper' require 'saxon/processor' describe Saxon::Processor do let(:processor) { Saxon::Processor.new } let(:xsl_file) { File.open(fixture_path('eg.xsl')) } it "can make a new XSLT instance" do expect(processor.XSLT(xsl_file)).to respond_to(:transform) end it "can make a new XML instance" do expect(processor.XML(xsl_file)).to respond_to(:node_kind) end end
Change api docs base url.
Apipie.configure do |config| config.app_name = "AACT 2 API" config.api_base_url = "/api" config.doc_base_url = "/docs" # where is your API defined? config.api_controllers_matcher = "#{Rails.root}/app/controllers/api/**/*.rb" end
Apipie.configure do |config| config.app_name = "AACT 2 API" config.api_base_url = "/api" config.doc_base_url = "/api_docs" # where is your API defined? config.api_controllers_matcher = "#{Rails.root}/app/controllers/api/**/*.rb" end
Use `make` instead of `command` in spawn-fgci
# # Copyright 2012-2014 Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # name "spawn-fcgi" default_version "1.6.3" dependency "fcgi" dependency "fcgiwrap" source url: "http://www.lighttpd.net/download/spawn-fcgi-#{version}.tar.gz", md5: "6d75f9e9435056fa1e574d836d823cd0" relative_path "spawn-fcgi-#{version}" build do env = with_standard_compiler_flags(with_embedded_path) command "./configure" \ " --prefix=#{install_dir}/embedded", env: env command "make -j #{max_build_jobs}", env: env command "make install", env: env end
# # Copyright 2012-2014 Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # name "spawn-fcgi" default_version "1.6.3" dependency "fcgi" dependency "fcgiwrap" source url: "http://www.lighttpd.net/download/spawn-fcgi-#{version}.tar.gz", md5: "6d75f9e9435056fa1e574d836d823cd0" relative_path "spawn-fcgi-#{version}" build do env = with_standard_compiler_flags(with_embedded_path) command "./configure" \ " --prefix=#{install_dir}/embedded", env: env make "-j #{max_build_jobs}", env: env make "install", env: env end
Add error for failed update request
class UsersController < ApplicationController def index @users = User.all end def new @user = User.new end def create @user = User.new(user_params) if @user.save session[:user_id] = @user.id redirect_to @user else redirect_to :back end end def show @user = User.find(params[:id]) end def edit @user = User.find(params[:id]) end def update @user = User.new(user_params) if @user.save redirect_to @user else redirect_to 'edit_user_path' end end private def user_params params.require(:user).permit(:first_name, :last_name, :username, :city, :state, :email, :password) end end
class UsersController < ApplicationController def index @users = User.all end def new @user = User.new end def create @user = User.new(user_params) if @user.save session[:user_id] = @user.id redirect_to @user else redirect_to :back end end def show @user = User.find(params[:id]) end def edit @user = User.find(params[:id]) end def update @user = User.new(user_params) if @user.update(params[:user]) redirect_to @user else @errors = @user.errors.full_messages redirect_to 'edit_user_path' end end private def user_params params.require(:user).permit(:first_name, :last_name, :username, :city, :state, :email, :password) end end
Add test to ensure rake script setup correctly
require 'rake' describe 'evm_export_import' do let(:task_path) {'lib/tasks/evm_export_import'} describe 'evm:import:alerts', :type => :rake_task do it 'depends on the environment' do expect(Rake::Task['evm:import:alerts'].prerequisites).to include('environment') end end describe 'evm:import:alertprofiles', :type => :rake_task do it 'depends on the environment' do expect(Rake::Task['evm:import:alertprofiles'].prerequisites).to include('environment') end end describe 'evm:export:alerts', :type => :rake_task do it 'depends on the environment' do expect(Rake::Task['evm:export:alerts'].prerequisites).to include('environment') end end describe 'evm:export:alertprofiless', :type => :rake_task do it 'depends on the environment' do expect(Rake::Task['evm:export:alertprofiles'].prerequisites).to include('environment') end end end
Modify uuid test to account for nanosecond precision on some platforms
require File.expand_path('spec_helper.rb', File.dirname(__FILE__)) include CassandraCQL describe "UUID" do it "should respond_to to_guid" do UUID.new.respond_to?(:to_guid) end it "should respond_to to_time" do UUID.new.respond_to?(:to_time) end it "should instantiate from raw bytes" do UUID.new("\252}\303\374\3137\021\340\237\214\251}\315\351 ]") end it "should instantiate from a Time object" do ts = Time.new UUID.new(ts).to_time.should eq(ts) end it "should turn have a to_time class method that takes bytes" do UUID.to_time("\252}\303\374\3137\021\340\237\214\251}\315\351 ]").should be_kind_of(Time) end end
require File.expand_path('spec_helper.rb', File.dirname(__FILE__)) include CassandraCQL describe "UUID" do it "should respond_to to_guid" do UUID.new.respond_to?(:to_guid) end it "should respond_to to_time" do UUID.new.respond_to?(:to_time) end it "should instantiate from raw bytes" do UUID.new("\252}\303\374\3137\021\340\237\214\251}\315\351 ]") end it "should instantiate from a Time object" do ts = Time.new # Nanosecond precision is available on some platforms but not in UUIDv1 so they may not match, just be v.close # Note that the time returned from two UUIDs using these two timestamps will still be the same (UUID.new(ts).to_time - ts).should < 0.000001 end it "should turn have a to_time class method that takes bytes" do UUID.to_time("\252}\303\374\3137\021\340\237\214\251}\315\351 ]").should be_kind_of(Time) end end