Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Make upsert method a bit more easy to read
module ActiveRecordUpsert module ActiveRecord module RelationExtensions def upsert(existing_attributes, upsert_attributes, wheres) # :nodoc: im = arel_table.create_insert im.into arel_table substitutes, binds = substitute_values(existing_attributes) column_arr = self.klass.upsert_keys || [primary_key] column_name = column_arr.join(',') cm = arel_table.create_on_conflict_do_update cm.target = arel_table[column_name] cm.wheres = wheres filter = ->(o) { [*column_arr, 'created_at'].include?(o.name) } filter2 = ->(o) { upsert_attributes.include?(o.name) } vals_for_upsert = substitutes.reject { |s| filter.call(s.first) } vals_for_upsert = vals_for_upsert.select { |s| filter2.call(s.first) } cm.set(vals_for_upsert) on_conflict_binds = binds.reject(&filter).select(&filter2) im.on_conflict = cm.to_node im.insert substitutes @klass.connection.upsert( im, 'SQL', nil, # primary key (not used) nil, # primary key value (not used) nil, binds + on_conflict_binds) end end end end
module ActiveRecordUpsert module ActiveRecord module RelationExtensions def upsert(existing_attributes, upsert_attributes, wheres) # :nodoc: substitutes, binds = substitute_values(existing_attributes) upsert_keys = self.klass.upsert_keys || [primary_key] upsert_attributes = upsert_attributes - [*upsert_keys, 'created_at'] upsert_keys_filter = ->(o) { upsert_attributes.include?(o.name) } on_conflict_binds = binds.select(&upsert_keys_filter) vals_for_upsert = substitutes.select { |s| upsert_keys_filter.call(s.first) } on_conflict_do_update = arel_table.create_on_conflict_do_update on_conflict_do_update.target = arel_table[upsert_keys.join(',')] on_conflict_do_update.wheres = wheres on_conflict_do_update.set(vals_for_upsert) insert_manager = arel_table.create_insert insert_manager.into arel_table insert_manager.on_conflict = on_conflict_do_update.to_node insert_manager.insert substitutes @klass.connection.upsert( insert_manager, 'SQL', nil, # primary key (not used) nil, # primary key value (not used) nil, binds + on_conflict_binds) end end end end
Update combustion for rails 5.2 compat
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "err_merchant/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "err_merchant" s.version = ErrMerchant::VERSION s.authors = ["Fabian Schwahn"] s.email = ["fabian.schwahn@gmail.com"] s.homepage = "https://github.com/fschwahn/err_merchant" s.summary = "Rails Engine for rendering error pages" s.description = "Rails Engine for rendering error pages" s.files = Dir["{lib,app,config}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["spec/**/*"] s.add_dependency 'rails', '>= 3.2', '<= 5.2' s.add_development_dependency 'rake', '~> 10.0' s.add_development_dependency 'combustion', '~> 0.5.2' s.add_development_dependency 'sqlite3' s.add_development_dependency 'rspec-rails', '~> 3.0' s.add_development_dependency 'capybara', '>= 2.2' end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "err_merchant/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "err_merchant" s.version = ErrMerchant::VERSION s.authors = ["Fabian Schwahn"] s.email = ["fabian.schwahn@gmail.com"] s.homepage = "https://github.com/fschwahn/err_merchant" s.summary = "Rails Engine for rendering error pages" s.description = "Rails Engine for rendering error pages" s.files = Dir["{lib,app,config}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["spec/**/*"] s.add_dependency 'rails', '>= 3.2', '<= 5.2' s.add_development_dependency 'rake', '~> 10.0' s.add_development_dependency 'combustion', '~> 0.9.1' s.add_development_dependency 'sqlite3' s.add_development_dependency 'rspec-rails', '~> 3.0' s.add_development_dependency 'capybara', '>= 2.2' end
Remove login field duplication in providet setup module
module TaskMapper::Provider # This is the Github Provider for taskmapper module Github include TaskMapper::Provider::Base class << self attr_accessor :login, :api, :user_token end # This is for cases when you want to instantiate using TaskMapper::Provider::Github.new(auth) def self.new(auth = {}) TaskMapper.new(:github, auth) end # declare needed overloaded methods here def authorize(auth = {}) @authentication ||= TaskMapper::Authenticator.new(auth) auth = @authentication login = auth.login || auth.username if auth.login.blank? and auth.username.blank? raise TaskMapper::Exception.new('Please provide at least a username') elsif auth.token TaskMapper::Provider::Github.login = login TaskMapper::Provider::Github.user_token = auth.token TaskMapper::Provider::Github.api = Octokit::Client.new(:login => login, :token => auth.token) elsif auth.password TaskMapper::Provider::Github.login = login TaskMapper::Provider::Github.user_token = auth.token TaskMapper::Provider::Github.api = Octokit::Client.new(:login => login, :password => auth.password) else TaskMapper::Provider::Github.login = login TaskMapper::Provider::Github.user_token = nil TaskMapper::Provider::Github.api = Octokit::Client.new(:login => login) end end def valid? TaskMapper::Provider::Github.api.authenticated? || TaskMapper::Provider::Github.api.oauthed? end end end
module TaskMapper::Provider # This is the Github Provider for taskmapper module Github include TaskMapper::Provider::Base class << self attr_accessor :login, :api, :user_token end # This is for cases when you want to instantiate using TaskMapper::Provider::Github.new(auth) def self.new(auth = {}) TaskMapper.new(:github, auth) end # declare needed overloaded methods here def authorize(auth = {}) @authentication ||= TaskMapper::Authenticator.new(auth) auth = @authentication login = auth.login || auth.username if login.blank? raise TaskMapper::Exception.new('Please provide at least a username') elsif auth.token TaskMapper::Provider::Github.api = Octokit::Client.new(:login => login, :token => auth.token) elsif auth.password TaskMapper::Provider::Github.api = Octokit::Client.new(:login => login, :password => auth.password) else TaskMapper::Provider::Github.api = Octokit::Client.new(:login => login) end TaskMapper::Provider::Github.login = login end def valid? TaskMapper::Provider::Github.api.authenticated? || TaskMapper::Provider::Github.api.oauthed? end end end
Fix bug in cucumber humpyard steps
require 'pickle' Given /^the standard pages$/ do Factory :page, :id => 42, :name => 'index', :title => 'My Homepage', :position => 1 Factory :page, :id => 45, :name => 'about', :title => 'About', :position => 4 Factory :page, :id => 60, :name => 'contact', :title => 'Contact', :parent_id => 45 Factory :page, :id => 89, :name => 'imprint', :title => 'Imprint', :position => 2 end Given /^the following (.+) records?$/ do |factory, table| table.hashes.each do |hash| Factory(factory, hash) end #puts Humpyard::Page.all.inspect end Given /^the www prefix is "(.+)"$/ do |www_prefix| Humpyard::config.www_prefix = (www_prefix == :default ? nil : www_prefix) Rails::Application.reload_routes! end Transform /^table:(?:.*,)?parent(?:,.*)?$/i do |table| table.map_headers! { |header| header.downcase } table.map_column!("parent") { |a| model(a) } table end Given /^#{capture_model} is the parent of #{capture_model}$/ do |parent, child| child = model(child) child.parent = model(parent) child.save! end Then /^put me the raw result$/ do # Only use this for debugging a output if you don't know what went wrong raise page.body end
require 'pickle' Given /^the standard pages$/ do Factory :page, :id => 42, :name => 'index', :title => 'My Homepage', :position => 1 Factory :page, :id => 45, :name => 'about', :title => 'About', :position => 4 Factory :page, :id => 60, :name => 'contact', :title => 'Contact', :parent_id => 45 Factory :page, :id => 89, :name => 'imprint', :title => 'Imprint', :position => 2 end Given /^the following (.+) records?$/ do |factory, table| table.hashes.each do |hash| Factory(factory, hash) end #puts Humpyard::Page.all.inspect end Given /^the www prefix is "(.+)"$/ do |www_prefix| Humpyard::config.www_prefix = (www_prefix == ':default' ? nil : www_prefix) Rails::Application.reload_routes! end Transform /^table:(?:.*,)?parent(?:,.*)?$/i do |table| table.map_headers! { |header| header.downcase } table.map_column!("parent") { |a| model(a) } table end Given /^#{capture_model} is the parent of #{capture_model}$/ do |parent, child| child = model(child) child.parent = model(parent) child.save! end Then /^put me the raw result$/ do # Only use this for debugging a output if you don't know what went wrong raise page.body end
Remove fkey constraint so that deployment can be deleted for existing deployments
Sequel.migration do change do # newer versions of sequel support drop_foreign_key but the version breaks tests if [:mysql2, :mysql].include?(adapter_scheme) run('alter table vms drop FOREIGN KEY vms_ibfk_1') elsif [:postgres].include?(adapter_scheme) run('alter table vms drop constraint vms_deployment_id_fkey') end end end
Make spec passed on travis-ci.org
require "open3" RSpec.describe "Executable" do let(:root) { File.expand_path "../../..", File.dirname(__FILE__) } it "works" do stdout, stderr, status = Open3.capture3("#{root}/bin/whatsnew") expect(stdout).to include "What's New" expect(stdout).to include "See CHANGELOG.md: https://github.com/jollygoodcode/whatsnew/blob/master/CHANGELOG.md." expect(stderr).to be_empty expect(status).to eq 0 end it "no news file" do # /tmp does not have changelog stdout, stderr, status = Dir.chdir("/tmp") do Open3.capture3("#{root}/bin/whatsnew") end expect(stdout.chomp!).to eq "NOT FOUND" expect(stderr).to be_empty expect(status).to eq 0 end end
require "open3" RSpec.describe "Executable" do let(:root) { File.expand_path "../../..", File.dirname(__FILE__) } it "works" do stdout, stderr, status = Open3.capture3("#{root}/bin/whatsnew") expect(stdout).to include "What's New" expect(stdout).to include "See CHANGELOG.md" expect(stderr).to be_empty expect(status).to eq 0 end it "no news file" do # /tmp does not have changelog stdout, stderr, status = Dir.chdir("/tmp") do Open3.capture3("#{root}/bin/whatsnew") end expect(stdout.chomp!).to eq "NOT FOUND" expect(stderr).to be_empty expect(status).to eq 0 end end
Add correct_user method as controller method and helper.
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? before_action :authenticate_user!, except: [:home] protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:username]) end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? before_action :authenticate_user!, except: [:home] helper_method :correct_user def correct_user !!(current_user == @resource.user) end protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:username]) end end
FIX : pour le seed
module CommandesObserver extend ActiveSupport::Concern included do before_save :send_sms_on_etat_change end private def send_sms_on_etat_change if etat_changed? SMS.send to: user.telephone, message: "Votre commande #{numero}, est maintenant à l'état : #{etat.humanize}" end end end
module CommandesObserver extend ActiveSupport::Concern included do before_save :send_sms_on_etat_change end private def send_sms_on_etat_change if etat_changed? and ENV['twilio_phone_number'] and user.telephone SMS.send to: user.telephone, message: "Votre commande #{numero}, est maintenant à l'état : #{etat.humanize}" end end end
Create timed files now supports multiple new files.
#!/usr/bin/env ruby require 'ftools' module FileCreation OLDFILE = "testdata/old" NEWFILE = "testdata/new" def create_timed_files(oldfile, newfile) return if File.exist?(oldfile) && File.exist?(newfile) old_time = create_file(oldfile) while create_file(newfile) <= old_time sleep(0.1) File.delete(newfile) rescue nil end end def create_dir(dirname) FileUtils.mkdir_p(dirname) unless File.exist?(dirname) File.stat(dirname).mtime end def create_file(name) create_dir(File.dirname(name)) FileUtils.touch(name) unless File.exist?(name) File.stat(name).mtime end def delete_file(name) File.delete(name) rescue nil end end
#!/usr/bin/env ruby require 'ftools' module FileCreation OLDFILE = "testdata/old" NEWFILE = "testdata/new" def create_timed_files(oldfile, *newfiles) return if File.exist?(oldfile) && newfiles.all? { |newfile| File.exist?(newfile) } old_time = create_file(oldfile) newfiles.each do |newfile| while create_file(newfile) <= old_time sleep(0.1) File.delete(newfile) rescue nil end end end def create_dir(dirname) FileUtils.mkdir_p(dirname) unless File.exist?(dirname) File.stat(dirname).mtime end def create_file(name) create_dir(File.dirname(name)) FileUtils.touch(name) unless File.exist?(name) File.stat(name).mtime end def delete_file(name) File.delete(name) rescue nil end end
Package version is increased from 0.0.1.9 to 0.0.1.10
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'error_data' s.version = '0.0.1.9' s.summary = 'Representation of an error as a data structure' s.description = ' ' s.authors = ['Obsidian Software, Inc'] s.email = 'opensource@obsidianexchange.com' s.homepage = 'https://github.com/obsidian-btc/error-data' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.2.3' s.add_runtime_dependency 'schema' s.add_runtime_dependency 'casing' s.add_development_dependency 'serialize' s.add_development_dependency 'test_bench' end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'error_data' s.version = '0.0.1.10' s.summary = 'Representation of an error as a data structure' s.description = ' ' s.authors = ['Obsidian Software, Inc'] s.email = 'opensource@obsidianexchange.com' s.homepage = 'https://github.com/obsidian-btc/error-data' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.2.3' s.add_runtime_dependency 'schema' s.add_runtime_dependency 'casing' s.add_development_dependency 'serialize' s.add_development_dependency 'test_bench' end
Package version is increased from 0.1.6 to 0.1.7
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'error_data' s.version = '0.1.6' s.summary = 'Representation of an error as a data structure' s.description = ' ' s.authors = ['Obsidian Software, Inc'] s.email = 'opensource@obsidianexchange.com' s.homepage = 'https://github.com/obsidian-btc/error-data' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.2.3' s.add_runtime_dependency 'schema' s.add_runtime_dependency 'casing' s.add_development_dependency 'serialize' s.add_development_dependency 'minitest' s.add_development_dependency 'minitest-spec-context' s.add_development_dependency 'pry' s.add_development_dependency 'runner' end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'error_data' s.version = '0.1.7' s.summary = 'Representation of an error as a data structure' s.description = ' ' s.authors = ['Obsidian Software, Inc'] s.email = 'opensource@obsidianexchange.com' s.homepage = 'https://github.com/obsidian-btc/error-data' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.2.3' s.add_runtime_dependency 'schema' s.add_runtime_dependency 'casing' s.add_development_dependency 'serialize' s.add_development_dependency 'minitest' s.add_development_dependency 'minitest-spec-context' s.add_development_dependency 'pry' s.add_development_dependency 'runner' end
Fix deprecation warning on Thread connection close
require "net/http" require "uri" module SocialStream module Ostatus module Models module Actor extend ActiveSupport::Concern include Rails.application.routes.url_helpers included do after_commit :publish_feed end module ClassMethods # Extract the slug from the webfinger id and return the actor # searching by that slug def find_by_webfinger!(link) link =~ /(acct:)?(.*)@/ find_by_slug! $2 end end def publish_feed return if subject_type == "RemoteSubject" t = Thread.new do uri = URI.parse(SocialStream::Ostatus.hub) topic = polymorphic_url [subject, :activities], :format => :atom, :host => SocialStream::Ostatus.activity_feed_host response = Net::HTTP::post_form uri, { 'hub.mode' => 'publish', 'hub.url' => topic } #TO-DO: process 4XX look at: response.status end end end end end end
require "net/http" require "uri" module SocialStream module Ostatus module Models module Actor extend ActiveSupport::Concern include Rails.application.routes.url_helpers included do after_commit :publish_feed end module ClassMethods # Extract the slug from the webfinger id and return the actor # searching by that slug def find_by_webfinger!(link) link =~ /(acct:)?(.*)@/ find_by_slug! $2 end end def publish_feed return if subject_type == "RemoteSubject" t = Thread.new do uri = URI.parse(SocialStream::Ostatus.hub) topic = polymorphic_url [subject, :activities], :format => :atom, :host => SocialStream::Ostatus.activity_feed_host response = Net::HTTP::post_form uri, { 'hub.mode' => 'publish', 'hub.url' => topic } #TODO: process 4XX look at: response.status ActiveRecord::Base.connection.close end end end end end end
Add validation for student number
class Opiskelija < ActiveRecord::Base belongs_to :aika validates :numero, uniqueness: { scope: :aika, message: "Olet jo ilmoittautunut tähän aikaan." }, numericality: { only_integer: true } end
class Opiskelija < ActiveRecord::Base belongs_to :aika validate :legit_number?, on: :create validates :numero, uniqueness: { scope: :aika, message: "Olet jo ilmoittautunut tähän aikaan." }, numericality: { only_integer: true } def legit_number? errors.add(:numero, "ei ole validi opiskelijanumero") unless Opiskelija.validate_number(self.numero) end def self.validate_number(num) b = [3, 7, 1, 3, 7, 1, 3, 7] return false unless num.length == 9 a = num.split("").map{|p| p.to_i}.take(8) ans = (10 - (a.zip(b).map{|i,j| i*j }.inject(:+)) % 10) % 10 return (num[8].to_i == ans) end end
Add index to use drilldown
class AddIndexToSearcherRecords < ActiveRecord::Migration def change reversible do |d| case when Redmine::Database.postgresql? opclass = "pgroonga.varchar_full_text_search_ops" d.up do columns = [ "id", "name #{opclass}", "identifier #{opclass}", "description", "title #{opclass}", "summary #{opclass}", "subject #{opclass}", "comments", "content", "notes", "text", "value", "filename #{opclass}" ] sql = "CREATE INDEX index_searcher_records_pgroonga ON searcher_records USING pgroonga (#{columns.join(',')})" execute(sql) end d.down do remove_index(:searcher_records, name: "index_searcher_records_pgroonga") end when Redmine::Database.mysql? columns = %i[ name identifier description title summary subject comments content notes text value filename ] d.up do columns.each do |column| add_index(:searcher_records, column, type: "fulltext") end end d.down do columns.each do |column| remove_index(:searcher_records, column) end end else # Do nothing end end end end
class AddIndexToSearcherRecords < ActiveRecord::Migration def change reversible do |d| case when Redmine::Database.postgresql? opclass = "pgroonga.varchar_full_text_search_ops" d.up do columns = [ "id", "name #{opclass}", "identifier #{opclass}", "description", "title #{opclass}", "summary #{opclass}", "subject #{opclass}", "comments", "content", "notes", "text", "value", "filename #{opclass}", "original_type #{opclass}" ] sql = "CREATE INDEX index_searcher_records_pgroonga ON searcher_records USING pgroonga (#{columns.join(',')})" execute(sql) end d.down do remove_index(:searcher_records, name: "index_searcher_records_pgroonga") end when Redmine::Database.mysql? columns = %i[ name identifier description title summary subject comments content notes text value filename original_type ] d.up do columns.each do |column| add_index(:searcher_records, column, type: "fulltext") end end d.down do columns.each do |column| remove_index(:searcher_records, column) end end else # Do nothing end end end end
Use Rack::ThumbNailer in the site's rackup
#require 'pp' require 'eee.rb' require 'rubygems' require 'sinatra' require 'rack/cache' use Rack::Cache, :verbose => true, :metastore => 'file:/var/cache/rack/meta', :entitystore => 'file:/var/cache/rack/body' root_dir = File.dirname(__FILE__) set :environment, :development set :root, root_dir set :app_root, root_dir set :app_file, File.join(root_dir, 'eee.rb') disable :run run Sinatra::Application
#require 'pp' require 'eee.rb' require 'rubygems' require 'sinatra' require 'rack/cache' require 'image_science' ### # Cache use Rack::Cache, :verbose => true, :metastore => 'file:/var/cache/rack/meta', :entitystore => 'file:/var/cache/rack/body' ### # Thumbnail require 'rack/thumbnailer' use Rack::ThumbNailer, :cache_dir => '/tmp/rack/thumbnails' ### # Sinatra App root_dir = File.dirname(__FILE__) set :environment, :development set :root, root_dir set :app_root, root_dir set :app_file, File.join(root_dir, 'eee.rb') disable :run run Sinatra::Application
Add description to rake task
namespace :legacy do desc "Drop and recreate legacy test database, then import legacy data" task :setup => :environment do Legacy.connection.execute "DROP DATABASE IF EXISTS chorus_legacy_test" Legacy.connection.execute "CREATE DATABASE chorus_legacy_test" system "psql --host=localhost --port=8543 --username=edcadmin chorus_legacy_test < #{File.join(Rails.root, 'db', 'legacy', 'legacy.sql')}" end desc "Migrate legacy data to the rails database" task :migrate => :environment do DataMigrator.migrate end end namespace :db do namespace :test do namespace :prepare do task :legacy => "legacy:setup" end end end
namespace :legacy do desc "Drop and recreate legacy test database, then import legacy data" task :setup => :environment do Legacy.connection.execute "DROP DATABASE IF EXISTS chorus_legacy_test" Legacy.connection.execute "CREATE DATABASE chorus_legacy_test" system "psql --host=localhost --port=8543 --username=edcadmin chorus_legacy_test < #{File.join(Rails.root, 'db', 'legacy', 'legacy.sql')}" end desc "Migrate legacy data to the rails database" task :migrate => :environment do DataMigrator.migrate end end namespace :db do namespace :test do namespace :prepare do desc "Drop and recreate legacy test database, then import legacy data" task :legacy => "legacy:setup" end end end
Use different Google API key for server
Geocoder.configure( # Geocoding options timeout: 3, # geocoding service timeout (secs) lookup: :google, # name of geocoding service (symbol) # language: :en, # ISO-639 language code use_https: true, # use HTTPS for lookup requests? (if supported) # http_proxy: nil, # HTTP proxy server (user:pass@host:port) # https_proxy: nil, # HTTPS proxy server (user:pass@host:port) # api_key: nil, # API key for geocoding service # cache: nil, # cache object (must respond to #[], #[]=, and #keys) # cache_prefix: 'geocoder:', # prefix (string) to use for all cache keys # Exceptions that should not be rescued by default # (if you want to implement custom error handling); # supports SocketError and Timeout::Error always_raise: :all, # Calculation options # units: :mi, # :km for kilometers or :mi for miles # distances: :linear # :spherical or :linear google: { api_key: ENV["GOOGLE_MAPS_API_KEY"] } )
Geocoder.configure( # Geocoding options timeout: 3, # geocoding service timeout (secs) lookup: :google, # name of geocoding service (symbol) # language: :en, # ISO-639 language code use_https: true, # use HTTPS for lookup requests? (if supported) # http_proxy: nil, # HTTP proxy server (user:pass@host:port) # https_proxy: nil, # HTTPS proxy server (user:pass@host:port) # api_key: nil, # API key for geocoding service # cache: nil, # cache object (must respond to #[], #[]=, and #keys) # cache_prefix: 'geocoder:', # prefix (string) to use for all cache keys # Exceptions that should not be rescued by default # (if you want to implement custom error handling); # supports SocketError and Timeout::Error always_raise: :all, # Calculation options # units: :mi, # :km for kilometers or :mi for miles # distances: :linear # :spherical or :linear google: { api_key: ENV["GOOGLE_MAPS_API_SERVER_KEY"] } )
Remove tmp-file storage provider, switch to in-memory provider.
require 'openid/store/filesystem' Rails.application.config.middleware.use OmniAuth::Builder do provider :developer unless Rails.env.production? provider :open_id, store: OpenID::Store::Filesystem.new('/tmp'), :identifier => 'https://www.google.com/accounts/o8/id' end
require 'openid/store/filesystem' Rails.application.config.middleware.use OmniAuth::Builder do provider :developer unless Rails.env.production? provider :open_id, :identifier => 'https://www.google.com/accounts/o8/id' end
Reset the local production branch when we switch to it.
module Heroku::Deploy::Task class PrepareProductionBranch < Base include Heroku::Deploy::Shell def before_deploy @previous_branch = git "rev-parse --abbrev-ref HEAD" # Always fetch first. The repo may have already been created. task "Fetching from #{colorize "origin", :cyan}" do git "fetch origin" end task "Switching to #{colorize strategy.branch, :cyan}" do branches = git "branch" if branches.match /#{strategy.branch}$/ git "checkout #{strategy.branch}" else git "checkout -b #{strategy.branch}" end end task "Merging your current branch #{colorize @previous_branch, :cyan} into #{colorize strategy.branch, :cyan}" do git "merge #{strategy.new_commit}" end end def after_deploy task "Pushing local #{colorize strategy.branch, :cyan} to #{colorize "origin", :cyan}" git "push -u origin #{strategy.branch} -v", :exec => true switch_back_to_old_branch end def rollback_before_deploy switch_back_to_old_branch end private def switch_back_to_old_branch task "Switching back to #{colorize @previous_branch, :cyan}" do git "checkout #{@previous_branch}" end end end end
module Heroku::Deploy::Task class PrepareProductionBranch < Base include Heroku::Deploy::Shell def before_deploy @previous_branch = git "rev-parse --abbrev-ref HEAD" # Always fetch first. The repo may have already been created. task "Fetching from #{colorize "origin", :cyan}" do git "fetch origin" end task "Switching to #{colorize strategy.branch, :cyan}" do branches = git "branch" if branches.match /#{strategy.branch}$/ git "checkout #{strategy.branch}" git "reset origin/#{strategy.branch} --hard" else git "checkout -b #{strategy.branch}" end end task "Merging your current branch #{colorize @previous_branch, :cyan} into #{colorize strategy.branch, :cyan}" do git "merge #{strategy.new_commit}" end end def after_deploy task "Pushing local #{colorize strategy.branch, :cyan} to #{colorize "origin", :cyan}" git "push -u origin #{strategy.branch} -v", :exec => true switch_back_to_old_branch end def rollback_before_deploy switch_back_to_old_branch end private def switch_back_to_old_branch task "Switching back to #{colorize @previous_branch, :cyan}" do git "checkout #{@previous_branch}" end end end end
Include default recipe via run_context within action
def load_current_resource node.include_recipe 'control_group::default' ControlGroups.config_struct_init(node) new_resource.group new_resource.name unless new_resource.group end action :create do group_name = new_resource.group.to_s group_struct = Mash.new(node.run_state[:control_groups][:config][:structure]) perm = {} %w(task admin).each do |type| %w(uid gid).each do |idx| if(val = new_resource.send("perm_#{type}_#{idx}")) perm[type] ||= {} perm[type][idx] = val end end end grp_hsh = {} grp_hsh['perm'] = perm unless perm.empty? # TODO: Check that mounts are available for these %w(cpu cpuacct devices freezer memory).each do |idx| if(val = new_resource.send(idx)) grp_hsh[idx] = val end end group_struct[group_name] = grp_hsh node.run_state[:control_groups][:config][:structure] = group_struct end action :delete do # be lazy, do nothing \o/ end
def load_current_resource ControlGroups.config_struct_init(node) new_resource.group new_resource.name unless new_resource.group end action :create do run_context.include_recipe 'control_groups' group_name = new_resource.group.to_s group_struct = Mash.new(node.run_state[:control_groups][:config][:structure]) perm = {} %w(task admin).each do |type| %w(uid gid).each do |idx| if(val = new_resource.send("perm_#{type}_#{idx}")) perm[type] ||= {} perm[type][idx] = val end end end grp_hsh = {} grp_hsh['perm'] = perm unless perm.empty? # TODO: Check that mounts are available for these %w(cpu cpuacct devices freezer memory).each do |idx| if(val = new_resource.send(idx)) grp_hsh[idx] = val end end group_struct[group_name] = grp_hsh node.run_state[:control_groups][:config][:structure] = group_struct end action :delete do # be lazy, do nothing \o/ end
Remove TODO note relating to the recent changes
require "rack/test" require "sinatra" require 'capybara/cucumber' class DummyApp < Sinatra::Base get '/' do 'the best response eva!' end end Before('@http-reporter') do Nark.configure do |c| c.reporters = [:HTTP] end end Before('@app-call, @middleware, @reporting-api') do # TODO: Setup HTTP reporter Capybara.app = Nark.app(DummyApp) end After('@app-call, @middleware, @reporting-api, @reporter') do Capybara.app = nil end
require "rack/test" require "sinatra" require 'capybara/cucumber' class DummyApp < Sinatra::Base get '/' do 'the best response eva!' end end Before('@http-reporter') do Nark.configure do |c| c.reporters = [:HTTP] end end Before('@app-call, @middleware, @reporting-api') do Capybara.app = Nark.app(DummyApp) end After('@app-call, @middleware, @reporting-api, @reporter') do Capybara.app = nil end
Change to stop modifying frozen strings
# frozen_string_literal: true module FiniteMachine module Logger module_function def debug(message) FiniteMachine.logger.debug(message) end def info(message) FiniteMachine.logger.info(message) end def warn(message) FiniteMachine.logger.warn(message) end def error(message) FiniteMachine.logger.error(message) end def format_error(error) message = "#{error.class}: #{error.message}\n\t" if error.backtrace message << "occured at #{error.backtrace.join("\n\t")}" else message << "EMPTY BACKTRACE\n\t" end end def report_transition(name, from, to, *args) message = "Transition: @event=#{name} " unless args.empty? message << "@with=[#{args.join(',')}] " end message << "#{from} -> #{to}" info(message) end end # Logger end # FiniteMachine
# frozen_string_literal: true module FiniteMachine module Logger module_function def debug(message) FiniteMachine.logger.debug(message) end def info(message) FiniteMachine.logger.info(message) end def warn(message) FiniteMachine.logger.warn(message) end def error(message) FiniteMachine.logger.error(message) end def format_error(error) message = ["#{error.class}: #{error.message}\n\t"] if error.backtrace message << "occured at #{error.backtrace.join("\n\t")}" else message << "EMPTY BACKTRACE\n\t" end message.join end def report_transition(name, from, to, *args) message = ["Transition: @event=#{name} "] unless args.empty? message << "@with=[#{args.join(',')}] " end message << "#{from} -> #{to}" info(message.join) end end # Logger end # FiniteMachine
Enable Rspec :should syntax because Webmock doesn't support :expect yet
require_relative '../lib/judopay' require 'i18n' #require 'factory_girl' #require 'factories' require 'webmock/rspec' # Added to counter deprecation warning I18n.enforce_available_locales = true RSpec.configure do |config| #config.include FactoryGirl::Syntax::Methods config.include WebMock::API end # Use Judopay default configuration Judopay.configure def stub_get(path) stub_request(:get, /judopay/i) end def stub_post(path) stub_request(:post, /judopay/i) end def fixture_path File.expand_path("../fixtures", __FILE__) end def fixture(file) File.new(fixture_path + '/' + file) end
require_relative '../lib/judopay' require 'i18n' #require 'factory_girl' #require 'factories' require 'webmock/rspec' # Added to counter deprecation warning I18n.enforce_available_locales = true RSpec.configure do |config| #config.include FactoryGirl::Syntax::Methods config.include WebMock::API config.expect_with :rspec do |c| c.syntax = [:expect, :should] end end # Use Judopay default configuration Judopay.configure def stub_get(path) stub_request(:get, /judopay/i) end def stub_post(path) stub_request(:post, /judopay/i) end def fixture_path File.expand_path("../fixtures", __FILE__) end def fixture(file) File.new(fixture_path + '/' + file) end
Add filter for simplecov to exclude bundled files
$:.unshift File.expand_path("../..", __FILE__) require "simplecov" SimpleCov.start require "webmock" require "webmock/rspec" require "json" require "magnum/client" def fixture_path(filename=nil) path = File.expand_path("../fixtures", __FILE__) filename.nil? ? path : File.join(path, filename) end def fixture(file) File.read(File.join(fixture_path, file)) end def json_fixture(file) JSON.parse(fixture(file)) end def api_url(path=nil) url = "https://magnum-ci.com/api/v1" url << path if path url end def stub_api(method, path, options={}) options[:status] ||= 200 options[:headers] ||= {} options[:body] ||= "" stub_request(method, api_url(path)).to_return(options) end
$:.unshift File.expand_path("../..", __FILE__) require "simplecov" SimpleCov.start do add_filter ".bundle" end require "webmock" require "webmock/rspec" require "json" require "magnum/client" def fixture_path(filename=nil) path = File.expand_path("../fixtures", __FILE__) filename.nil? ? path : File.join(path, filename) end def fixture(file) File.read(File.join(fixture_path, file)) end def json_fixture(file) JSON.parse(fixture(file)) end def api_url(path=nil) url = "https://magnum-ci.com/api/v1" url << path if path url end def stub_api(method, path, options={}) options[:status] ||= 200 options[:headers] ||= {} options[:body] ||= "" stub_request(method, api_url(path)).to_return(options) end
Remove fakefs as a dependecy during test
require 'fakefs/safe' require 'trustworthy' RSpec.configure do |config| config.order = 'random' config.before(:each) do Trustworthy::Random.stub(:_source).and_return('/dev/urandom') end end module Trustworthy module TestValues EncryptionKey = ['7fc6880ba7a75148e6b14a6ebca73b9861954835fd17237cbedb71a6ad3fefc4'].pack('H*') AuthenticationKey = ['12e7489dc1b2e6da1213cac0df946615a7088eeccdd6b2d4bf330e9560fabd52'].pack('H*') InitializationVector = ['39164ec082fb8b7336d3c5500af99dcb'].pack('H*') end end
require 'trustworthy' RSpec.configure do |config| config.order = 'random' config.before(:each) do Trustworthy::Random.stub(:_source).and_return('/dev/urandom') end end module Trustworthy module TestValues EncryptionKey = ['7fc6880ba7a75148e6b14a6ebca73b9861954835fd17237cbedb71a6ad3fefc4'].pack('H*') AuthenticationKey = ['12e7489dc1b2e6da1213cac0df946615a7088eeccdd6b2d4bf330e9560fabd52'].pack('H*') InitializationVector = ['39164ec082fb8b7336d3c5500af99dcb'].pack('H*') end end
Add update to user resources
Rails.application.routes.draw do mount RedactorRails::Engine => '/redactor_rails' resources :snippets get '/signup', to: 'users#new' post '/signup', to: 'users#create', as: 'new_sign_up' patch 'stories/:id/upvote', to: 'votes#upvote', as: 'vote_up' get 'stories/:id/downvote', to: 'votes#downvote', as: 'vote_down' resources :users, only: [:show, :edit, :delete] get '/users/:id', to: 'users#update', as: 'users_update' resources :stories resources :tags get '/tags/:id/stories', to: 'tags#show', as: 'tags_show' # get '/stories/:id/tags', to: 'stories#show_tags', as: 'show_tags' resources :storytags root "welcome#index" get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' get '/logout', to: 'sessions#destroy' end
Rails.application.routes.draw do mount RedactorRails::Engine => '/redactor_rails' resources :snippets get '/signup', to: 'users#new' post '/signup', to: 'users#create', as: 'new_sign_up' patch 'stories/:id/upvote', to: 'votes#upvote', as: 'vote_up' get 'stories/:id/downvote', to: 'votes#downvote', as: 'vote_down' resources :users, only: [:show, :edit, :update, :delete] # patch '/users/:id', to: 'users#update', as: 'users_update' resources :stories resources :tags get '/tags/:id/stories', to: 'tags#show', as: 'tags_show' # get '/stories/:id/tags', to: 'stories#show_tags', as: 'show_tags' resources :storytags root "welcome#index" get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' get '/logout', to: 'sessions#destroy' end
Use underscore to set db_name
task :kill_postgres_connections => :environment do db_name = "#{File.basename(Rails.root)}_#{Rails.env}" sh = <<EOF ps xa \ | grep postgres: \ | grep #{db_name} \ | grep -v grep \ | awk '{print $1}' \ | xargs kill EOF puts `#{sh}` end task "db:drop" => :kill_postgres_connections task "db:migrate:reset" => :kill_postgres_connections
task :kill_postgres_connections => :environment do db_name = "#{File.basename(Rails.root).underscore}_#{Rails.env}" sh = <<EOF ps xa \ | grep postgres: \ | grep #{db_name} \ | grep -v grep \ | awk '{print $1}' \ | xargs kill EOF puts `#{sh}` puts `echo "Killed connections to #{db_name}"` end task "db:drop" => :kill_postgres_connections task "db:migrate:reset" => :kill_postgres_connections
Change to use actuall errors.
# encoding: utf-8 module TTY class Prompt class ConverterRegistry def initialize @_registry = {} end # Register converter # # @api public def register(key, contents = nil, &block) if block_given? item = block else item = contents end if key?(key) fail Error, "Converter for #{key.inspect} already registered" else @_registry[key] = item end self end # Check if converter is registered # # @return [Boolean] # # @api public def key?(key) @_registry.key?(key) end # Execute converter # # @api public def call(key, input) converter = @_registry.fetch(key) do fail Error, "#{key.inspect} is not registered" end converter.call(input) end def inspect @_registry.inspect end end # ConverterRegistry end # Prompt end # TTY
# encoding: utf-8 module TTY class Prompt class ConverterRegistry def initialize @_registry = {} end # Register converter # # @api public def register(key, contents = nil, &block) if block_given? item = block else item = contents end if key?(key) fail ArgumentError, "Converter for #{key.inspect} already registered" else @_registry[key] = item end self end # Check if converter is registered # # @return [Boolean] # # @api public def key?(key) @_registry.key?(key) end # Execute converter # # @api public def call(key, input) converter = @_registry.fetch(key) do fail ArgumentError, "#{key.inspect} is not registered" end converter.call(input) end def inspect @_registry.inspect end end # ConverterRegistry end # Prompt end # TTY
Clear cookie if visit is destroyed
module Ahoy module ControllerExtensions def self.included(base) base.helper_method :current_visit end protected def current_visit @current_visit ||= Ahoy::Visit.where(visit_token: cookies[:ahoy_visit]).first if cookies[:ahoy_visit] end end end
module Ahoy module ControllerExtensions def self.included(base) base.helper_method :current_visit end protected def current_visit if cookies[:ahoy_visit] @current_visit ||= Ahoy::Visit.where(visit_token: cookies[:ahoy_visit]).first if @current_visit @current_visit else # clear cookie if visits are destroyed cookies.delete(:ahoy_visit) nil end end end end end
Add comments for optional notification fields
class CreateNotifiableNotifications < ActiveRecord::Migration def change create_table :notifiable_notifications do |t| t.text :title t.text :message t.text :params t.integer :badge t.text :sound t.datetime :expiry t.timestamps end end end
class CreateNotifiableNotifications < ActiveRecord::Migration def change create_table :notifiable_notifications do |t| t.text :message t.text :params # APNS - Optional #t.integer :badge #t.text :sound #t.datetime :expiry # MPNS - Optional #t.text :title t.timestamps end end end
Improve cancel method to set cancelled attribute as true only if payment status is 10
module BraspagRest class Sale < Hashie::IUTrash include Hashie::Extensions::Coercion attr_reader :errors property :request_id, from: 'RequestId' property :order_id, from: 'MerchantOrderId' property :customer, from: 'Customer', with: ->(values) { BraspagRest::Customer.new(values) } property :payment, from: 'Payment', with: ->(values) { BraspagRest::Payment.new(values) } property :cancelled coerce_key :customer, BraspagRest::Customer coerce_key :payment, BraspagRest::Payment def save response = BraspagRest::Request.authorize(request_id, inverse_attributes) if response.success? initialize_attributes(response.parsed_body) else initialize_errors(response.parsed_body) and return false end true end def cancel(amount = nil) response = BraspagRest::Request.void(request_id, payment.id, (amount || payment.amount)) if response.success? initialize_attributes('Payment' => response.parsed_body) self.cancelled = true else initialize_errors(response.parsed_body) and return false end end private def initialize_errors(errors) @errors = errors.map { |error| { code: error['Code'], message: error['Message'] } } end end end
module BraspagRest class Sale < Hashie::IUTrash include Hashie::Extensions::Coercion attr_reader :errors VOIDED = 10 property :request_id, from: 'RequestId' property :order_id, from: 'MerchantOrderId' property :customer, from: 'Customer', with: ->(values) { BraspagRest::Customer.new(values) } property :payment, from: 'Payment', with: ->(values) { BraspagRest::Payment.new(values) } property :cancelled coerce_key :customer, BraspagRest::Customer coerce_key :payment, BraspagRest::Payment def save response = BraspagRest::Request.authorize(request_id, inverse_attributes) if response.success? initialize_attributes(response.parsed_body) else initialize_errors(response.parsed_body) and return false end true end def cancel(amount = nil) response = BraspagRest::Request.void(request_id, payment.id, (amount || payment.amount)) if response.success? initialize_attributes('Payment' => response.parsed_body) self.cancelled = payment.status.eql?(VOIDED) else initialize_errors(response.parsed_body) and return false end end private def initialize_errors(errors) @errors = errors.map { |error| { code: error['Code'], message: error['Message'] } } end end end
Add integration test for segmentation endpoint
require 'acceptance_helper' feature "Overview page" do let(:project) { FactoryGirl.create(:project) } background do 3.times { |i| project.events.create(type: "sale", time: DateTime.new(2013, 1, 2, 12, i + 1)) } 2.times { |i| project.events.create(type: "sale", time: DateTime.new(2013, 1, 1, 12, i + 1)) } end scenario "Request segmentation data for a project" do p Event.all.to_s get "/metrics/#{project.api_key}/data/segmentation?callback=callback?&startDate=2013-01-01&endDate=2014-01-01" expect(last_response).to be_successful last_response.header['Content-Type'].should include 'application/javascript' last_response.body.should == %Q{callback?({"element":"sales","xkey":"key","ykeys":["value"],"labels":["time"],"data":[{"key":"2013-01-01T00:00:00+00:00","value":2},{"key":"2013-01-02T00:00:00+00:00","value":3}]})} end end
Enable Maven kit item archive generation
# encoding: UTF-8 module Tetra # tetra generate-kit-archive class GenerateKitArchiveCommand < Tetra::BaseCommand def execute checking_exceptions do project = Tetra::Project.new(".") ensure_dry_running(false, project) do result_path = Tetra::Kit.new(project).to_archive print_generation_result(project, result_path) end end end end end
# encoding: UTF-8 module Tetra # tetra generate-kit-archive class GenerateKitArchiveCommand < Tetra::BaseCommand def execute checking_exceptions do project = Tetra::Project.new(".") ensure_dry_running(false, project) do kit = Tetra::Kit.new(project) result_path = kit.to_archive print_generation_result(project, result_path) kit.maven_kit_items.each do |item| result_path = item.to_archive print_generation_result(project, result_path) end end end end end end
Upgrade RubyMine EAP to 141.373
cask :v1 => 'rubymine-eap' do version '140.2694' sha256 '7376d5b04b49e503c203a2b1c9034a690835ea601847753710f3c8ec53566ebb' url "http://download.jetbrains.com/ruby/RubyMine-#{version}.dmg" homepage 'http://confluence.jetbrains.com/display/RUBYDEV/RubyMine+EAP' license :unknown app 'RubyMine EAP.app' end
cask :v1 => 'rubymine-eap' do version '141.373' sha256 '58cdd199dfe556c00014203d38509ee0682a7516b041dbf0c1edd5a48cc032eb' url "https://download.jetbrains.com/ruby/RubyMine-#{version}.dmg" name 'RubyMine EAP' homepage 'https://confluence.jetbrains.com/display/RUBYDEV/RubyMine+EAP' license :commercial app 'RubyMine EAP.app' zap :delete => [ '~/Library/Preferences/com.jetbrains.rubymine-EAP.plist', '~/Library/Preferences/RubyMine70', '~/Library/Application Support/RubyMine70', '~/Library/Caches/RubyMine70', '~/Library/Logs/RubyMine70', '/usr/local/bin/mine', ] caveats <<-EOS.undent #{token} requires Java 6 like any other IntelliJ-based IDE. You can install it with brew cask install caskroom/homebrew-versions/java6 The vendor (JetBrains) doesn't support newer versions of Java (yet) due to several critical issues, see details at https://intellij-support.jetbrains.com/entries/27854363 EOS end
Add user_id + created_at index to changesets
class AddUserDateIndexToChangeset < ActiveRecord::Migration def self.up add_index :changesets, [:user_id, :created_at], :name => "changesets_user_id_created_at_idx" end def self.down remove_index :changesets, [:user_id, :created_at], :name => "changesets_user_id_created_at_idx" end end
Fix mutant expression for null integration test
# encoding: utf-8 require 'spec_helper' describe 'null integration' do let(:base_cmd) { 'bundle exec mutant -I lib --require test_app "::TestApp*"' } around do |example| Dir.chdir(TestApp.root) do example.run end end specify 'it allows to kill mutations' do expect(Kernel.system(base_cmd)).to be(false) end end
# encoding: utf-8 require 'spec_helper' describe 'null integration' do let(:base_cmd) { 'bundle exec mutant -I lib --require test_app "TestApp*"' } around do |example| Dir.chdir(TestApp.root) do example.run end end specify 'it allows to kill mutations' do expect(Kernel.system(base_cmd)).to be(false) end end
Use temporary redirect in root/index, since destination may change soon
class RootController < ApplicationController def index redirect_to Journey::SiteOptions.site_root(logged_in?) end end
class RootController < ApplicationController def index redirect_to Journey::SiteOptions.site_root(logged_in?), 307 end end
Add environment variables to supply database credentials
require 'minitest/autorun' require 'securerandom' require_relative '../lib/orats/commands/new/server' module Orats module Test include Commands::New::Server BINARY_PATH = File.absolute_path('../../bin/orats', __FILE__) TEST_PATH = '/tmp/orats' ORATS_NEW_FLAGS = '-p pleasedonthackme --skip-server-start --skip-galaxy' def orats(command, options = {}) cmd, app_name = command.split(' ') prepend_command = '' command = "#{cmd} #{TEST_PATH}/#{app_name}" unless app_name.nil? if options.has_key?(:answer) options[:answer] == 'y' || options[:answer] == 'yes' ? insert_answer = 'yes' : insert_answer = 'echo' prepend_command = "#{insert_answer} | " end system "#{prepend_command} #{BINARY_PATH} #{command} #{options[:flags]}" end private def generate_app_name "a_#{SecureRandom.hex(8)}" end end end
require 'minitest/autorun' require 'securerandom' require_relative '../lib/orats/commands/new/server' module Orats module Test include Commands::New::Server TEST_PATH = ENV['TEST_PATH'] || '/tmp/orats' POSTGRES_HOST = ENV['POSTGRES_HOST'] || 'localhost' POSTGRES_USERNAME = ENV['POSTGRES_USERNAME'] || 'postgres' POSTGRES_PASSWORD = ENV['POSTGRES_PASSWORD'] || 'pleasedonthackme' REDIS_LOCATION = ENV['REDIS_HOST'] || 'localhost' REDIS_PASSWORD = ENV['REDIS_PASSWORD'] || '' CREDENTIALS = "-l #{POSTGRES_HOST} -u #{POSTGRES_USERNAME} -p #{POSTGRES_PASSWORD} -n #{REDIS_LOCATION} -d #{REDIS_PASSWORD}" BINARY_PATH = File.absolute_path('../../bin/orats', __FILE__) ORATS_NEW_FLAGS = "#{CREDENTIALS} -FG" def orats(command, options = {}) cmd, app_name = command.split(' ') prepend_command = '' command = "#{cmd} #{TEST_PATH}/#{app_name}" unless app_name.nil? if options.has_key?(:answer) options[:answer] == 'y' || options[:answer] == 'yes' ? insert_answer = 'yes' : insert_answer = 'echo' prepend_command = "#{insert_answer} | " end system "#{prepend_command} #{BINARY_PATH} #{command} #{options[:flags]}" end private def generate_app_name "a_#{SecureRandom.hex(8)}" end end end
Fix for the module_registry spec, also this needs to be written as unit tests.
require File.expand_path('../spec_helper', __FILE__) describe 'ModuleRegistry' do it 'needs more tests' it 'should return item by a specified path' do registry = JenkinsPipelineBuilder::ModuleRegistry.new registry.register_job_attribute(:foo, 'jenkins name', 'desc') do true end puts registry.registry.inspect registry.get('job/foo').call.should be_true end end
require File.expand_path('../spec_helper', __FILE__) describe 'ModuleRegistry' do it 'needs more tests' it 'should return item by a specified path' do registry = JenkinsPipelineBuilder::ModuleRegistry.new registry.register_job_attribute(:foo, 'jenkins name', 'desc', 'plugin_id', 1.0) do true end expect(registry.registry[:job][:foo][1.0]).to be_truthy #TODO test registered_modules end end
Add before_save callback for resetting the company logo back to default
class Startup < ActiveRecord::Base belongs_to :user extend FriendlyId friendly_id :name, use: :slugged # Alias for acts_as_taggable_on :tags acts_as_ordered_taggable acts_as_ordered_taggable_on :markets mount_uploader :image, ImageUploader validates_presence_of :name, :pitch validates_length_of :name, :maximum => 40 validates_length_of :pitch, :maximum => 100 end
class Startup < ActiveRecord::Base attr_accessor :default_logo belongs_to :user extend FriendlyId friendly_id :name, use: :slugged # Alias for acts_as_taggable_on :tags acts_as_ordered_taggable acts_as_ordered_taggable_on :markets mount_uploader :image, ImageUploader before_save :set_default_logo validates_presence_of :name, :pitch validates_length_of :name, :maximum => 40 validates_length_of :pitch, :maximum => 100 def set_default_logo self.remove_image! if self.default_logo && self.default_logo == 'set_default' end end
Fix block addition method name
SparkleFormation.new('simple').load(:user_info).overloads do dynamic!(:node, 'fubar') outputs.region do description 'Region of stack' value region! end end
SparkleFormation.new('simple').load(:user_info).overrides do dynamic!(:node, 'fubar') outputs.region do description 'Region of stack' value region! end end
Add initial solution for 6.2; fails last rspec test currently
# Die Class 2: Arbitrary Symbols # I worked on this challenge [by myself, with: ]. # I spent [#] hours on this challenge. # Pseudocode # Input: # Output: # Steps: # Initial Solution class Die def initialize(labels) end def sides end def roll end end # Refactored Solution # Reflection
# Die Class 2: Arbitrary Symbols # I worked on this challenge [by myself, with: ]. # I spent [#] hours on this challenge. # Pseudocode # Input: an array of strings # Output: when Die#roll is called it should randomly return one of those strings # Steps: # 1. Initialize an instance of Die # a. if the passed array, 'labels', is empty or zero length, raise an Arguement Error # b. populate an instance array, @labels, with the data from 'labels', the passed argument # 2. Set the number of sides to be equal to the @labels array length # 3. def the method "roll" to randomly return on of the strings from @labels # a. generate 'side_rolled' equal to a random number from 0 to the number of elements in # @labels (also equal to 'sides') # b. return the string found at index "side_rolled" of @labels # Initial Solution class Die def initialize(labels) raise ArgumentError.new("Must have at least 1 labeled side") unless labels.length >= 1 @labels = labels.dup @labels.each {|w| print " - #{w} -"} end def sides @sides = @labels.length end def roll side_rolled = rand(@sides) print " : #{@labels[side_rolled]}" @labels[side_rolled] end end # Driver code my_die = Die.new(%w{a b c d e f g h}) p "sides: #{my_die.sides}" p " rolled: #{my_die.roll}" p " rolled: #{my_die.roll}" p " rolled: #{my_die.roll}" p " rolled: #{my_die.roll}" p " rolled: #{my_die.roll}" output = [] 100.times { output << my_die.roll} output.each {|e| puts "roll = #{e}"} # Refactored Solution # Reflection
Allow users with no subscriptions to create up to 5 universes
class UniverseCoreContentAuthorizer < CoreContentAuthorizer def self.creatable_by? user user.universes.count < user.active_billing_plans.map(&:universe_limit).max end def readable_by? user [ resource.user_id == user.id, resource.privacy == 'public' ].any? end def updatable_by? user resource.user_id == user.id end def deletable_by? user resource.user_id == user.id end end
class UniverseCoreContentAuthorizer < CoreContentAuthorizer def self.creatable_by? user user.universes.count < (user.active_billing_plans.map(&:universe_limit).max || 5) end def readable_by? user [ resource.user_id == user.id, resource.privacy == 'public' ].any? end def updatable_by? user resource.user_id == user.id end def deletable_by? user resource.user_id == user.id end end
Update test to correspond with changes to the name of the variable in Game class
require 'stringio' require './lib/game.rb' require './lib/tic_tac_toe.rb' describe Game do let(:ttt){TicTacToe.new} let(:new_game){Game.new(ttt)} describe '#initialize' do it 'with a new instance of TicTacToe' do expect(new_game.instance_variable_get(:@ttt)).to eq(ttt) end end describe '#prompt_user_for_input' do it 'ask users to input the position on all available slots where they want to place an X' do expect(new_game.prompt_user_for_input).to eq("Enter a number 0, 1, 2, 3, 4, 5, 6, 7, 8 to place an X") end end describe '#get_user_input' do it 'takes in a user input and returns an integer' do allow(new_game).to receive(:gets).and_return("2") expect(new_game.get_user_input).to eq(2) end end end
require 'stringio' require './lib/game.rb' require './lib/tic_tac_toe.rb' describe Game do let(:ttt){TicTacToe.new} let(:new_game){Game.new(ttt)} describe '#initialize' do it 'with a new instance of TicTacToe' do expect(new_game.gametype).to eq(ttt) end end describe '#prompt_user_for_input' do it 'ask users to input the position on all available slots where they want to place an X' do expect(new_game.prompt_user_for_input).to eq("Enter a number 0, 1, 2, 3, 4, 5, 6, 7, 8 to place an X") end end describe '#get_user_input' do it 'takes in a user input and returns an integer' do allow(new_game).to receive(:gets).and_return("2") expect(new_game.get_user_input).to eq(2) end end end
Set fixture paths for unit tests
require 'puppetlabs_spec_helper/module_spec_helper' require 'shared_examples' require 'puppet-openstack_spec_helper/facts' RSpec.configure do |c| c.alias_it_should_behave_like_to :it_configures, 'configures' c.alias_it_should_behave_like_to :it_raises, 'raises' end at_exit { RSpec::Puppet::Coverage.report! }
require 'puppetlabs_spec_helper/module_spec_helper' require 'shared_examples' require 'puppet-openstack_spec_helper/facts' fixture_path = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures')) RSpec.configure do |c| c.alias_it_should_behave_like_to :it_configures, 'configures' c.alias_it_should_behave_like_to :it_raises, 'raises' c.module_path = File.join(fixture_path, 'modules') c.manifest_dir = File.join(fixture_path, 'manifests') end at_exit { RSpec::Puppet::Coverage.report! }
Initialize AppData instead of creating the yaml file manually.
require 'rspec' require 'fileutils' require 'mgit' require 'stringio' # Require support files Dir["#{File.absolute_path(File.dirname(__FILE__))}/support/**/*.rb"].each { |f| require f } RSpec.configure do |config| config.order = 'random' config.before(:each) do @root = File.expand_path('../root', __FILE__) @repofile = File.expand_path('../root/mgit.yml', __FILE__) # Create test data directory. FileUtils.mkdir(@root) # Create the repofile. FileUtils.touch(@repofile) # Stub the XDG home. class << @root; def to_path; Pathname.new(self); end; end XDG.stub(:[]).and_return(@root) end config.after(:each) do # Clean up test data. FileUtils.rm_rf(@root) end end
require 'rspec' require 'fileutils' require 'mgit' require 'stringio' # Require support files Dir["#{File.absolute_path(File.dirname(__FILE__))}/support/**/*.rb"].each { |f| require f } RSpec.configure do |config| config.order = 'random' config.before(:each) do @root = File.expand_path('../root', __FILE__) @repofile = File.expand_path('../root/mgit.yml', __FILE__) # Create test data directory. FileUtils.mkdir(@root) # Stub the XDG home. class << @root; def to_path; Pathname.new(self); end; end XDG.stub(:[]).and_return(@root) # Initialize the application data. MGit::AppData.update end config.after(:each) do # Clean up test data. FileUtils.rm_rf(@root) end end
Disable template digesting for Active Storage controllers
# frozen_string_literal: true # The base class for all Active Storage controllers. class ActiveStorage::BaseController < ActionController::Base include ActiveStorage::SetCurrent protect_from_forgery with: :exception private def stream(blob) blob.download do |chunk| response.stream.write chunk end ensure response.stream.close end end
# frozen_string_literal: true # The base class for all Active Storage controllers. class ActiveStorage::BaseController < ActionController::Base include ActiveStorage::SetCurrent protect_from_forgery with: :exception self.etag_with_template_digest = false private def stream(blob) blob.download do |chunk| response.stream.write chunk end ensure response.stream.close end end
Make sure that the seed records are loaded before the tests run
ENV["RAILS_ENV"] = "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' class ActiveSupport::TestCase # Add more helper methods to be used by all tests here... end
ENV["RAILS_ENV"] = "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' class ActiveSupport::TestCase setup { load "#{Rails.root}/db/seeds.rb" } end
Fix failing tests assuming localizeCurrency has no "delimiter"
module Spree module MoneyHelper def with_currency(amount, options = {}) Spree::Money.new(amount, {delimiter: ''}.merge(options)).to_s # Delimiter is to match js localizeCurrency end end end
module Spree module MoneyHelper def with_currency(amount, options = {}) Spree::Money.new(amount, options).to_s end end end
Return strings are now utf-8
require "execjs/runtime" require "json" module ExecJS class DuktapeRuntime < Runtime class Context < Runtime::Context def initialize(runtime, source = "") @ctx = Duktape::Context.new exec(source) end def exec(source, options = {}) eval "(function(){#{encode(source)}})()" end def eval(source, options = {}) source = encode(source) if /\S/ =~ source unwrap(@ctx.eval_string("(#{source})", '(execjs)')) end rescue Duktape::SyntaxError => e raise RuntimeError, e.message rescue Duktape::Error => e raise ProgramError, e.message rescue Duktape::InternalError => e raise RuntimeError, e.message end def call(identifier, *args) eval "#{identifier}.apply(this, #{::JSON.generate(args)})" end def unwrap(obj) case obj when ::Duktape::ComplexObject nil when Array obj.map { |v| unwrap(v) } when Hash obj.inject({}) do |vs, (k, v)| v = unwrap(v) vs[k] = v if v vs end when String obj.force_encoding('UTF-8') else obj end end end def name "Duktape" end def available? require "duktape" true rescue LoadError false end end end
require "execjs/runtime" require "json" module ExecJS class DuktapeRuntime < Runtime class Context < Runtime::Context def initialize(runtime, source = "") @ctx = Duktape::Context.new exec(source) end def exec(source, options = {}) eval "(function(){#{encode(source)}})()" end def eval(source, options = {}) source = encode(source) if /\S/ =~ source unwrap(@ctx.eval_string("(#{source})", '(execjs)')) end rescue Duktape::SyntaxError => e raise RuntimeError, e.message rescue Duktape::Error => e raise ProgramError, e.message rescue Duktape::InternalError => e raise RuntimeError, e.message end def call(identifier, *args) eval "#{identifier}.apply(this, #{::JSON.generate(args)})" end def unwrap(obj) case obj when ::Duktape::ComplexObject nil when Array obj.map { |v| unwrap(v) } when Hash obj.inject({}) do |vs, (k, v)| v = unwrap(v) vs[k] = v if v vs end else obj end end end def name "Duktape" end def available? require "duktape" true rescue LoadError false end end end
Fix dangling libevent cookbook rename
name 'libevent' # maintainer 'Takeshi KOMIYA' # maintainer_email 'i.tkomiya@gmail.com' maintainer 'Travis CI GmbH' maintainer_email 'contact+travis-cookbooks-libevent@travis-ci.org' license 'Apache 2.0' description 'Installs libevent (from source)' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.2.0' %w(fedora redhat centos ubuntu debian amazon).each do |os| supports os end depends 'build-essential'
name 'travis_libevent' # maintainer 'Takeshi KOMIYA' # maintainer_email 'i.tkomiya@gmail.com' maintainer 'Travis CI GmbH' maintainer_email 'contact+travis-cookbooks-libevent@travis-ci.org' license 'Apache 2.0' description 'Installs libevent (from source)' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.2.0' %w(fedora redhat centos ubuntu debian amazon).each do |os| supports os end depends 'build-essential'
Use a correct auth token from header
module AuthenticationHelper PUBLIC_ROUTES = { 'POST' => [ '/api/users', '/api/authenticate' ] } def authenticate_user if api_token.blank? json_error("API token required", 401) end @api_user = User.find_by_api_token(api_token) if @api_user.nil? json_error("Invalid API token", 401) end end def api_token @api_token ||= request['X-API-TOKEN'] || params[:api_token] end def require_authentication? route = PUBLIC_ROUTES[request.request_method] || [] !route.include?(request.path) end end
module AuthenticationHelper PUBLIC_ROUTES = { 'POST' => [ '/api/users', '/api/authenticate' ] } def authenticate_user if api_token.blank? json_error("API token required", 401) end @api_user = User.find_by_api_token(api_token) if @api_user.nil? json_error("Invalid API token", 401) end end def api_token @api_token ||= request.env['HTTP_X_API_TOKEN'] || params[:api_token] end def require_authentication? route = PUBLIC_ROUTES[request.request_method] || [] !route.include?(request.path) end end
Update postal_zone for Cap plugin
# = Informations # # == License # # Ekylibre - Simple agricultural ERP # Copyright (C) 2008-2009 Brice Texier, Thibaud Merigon # Copyright (C) 2010-2012 Brice Texier # Copyright (C) 2012-2018 Brice Texier, David Joulin # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see http://www.gnu.org/licenses. # # == Table: registered_postal_zones # # city_centroid :geometry({:srid=>4326, :type=>"st_point"}) # city_delivery_detail :string # city_delivery_name :string # city_name :string not null # code :string not null # country :string not null # postal_code :string not null # class RegisteredPostalZone < ActiveRecord::Base include Lexiconable self.id_column = :code end
Add flexible_geolocation attribute to EffortSerializer.
# frozen_string_literal: true class EffortSerializer < BaseSerializer attributes :id, :event_id, :person_id, :participant_id, :bib_number, :first_name, :last_name, :full_name, :gender, :age, :city, :state_code, :country_code, :beacon_url, :report_url, :start_offset %i[phone email birthdate emergency_contact emergency_phone].each { |att| attribute att, if: :show_personal_info? } link(:self) { api_v1_effort_path(object) } has_many :split_times, if: :split_times_loaded? def split_times_loaded? object.split_times.loaded? end end
# frozen_string_literal: true class EffortSerializer < BaseSerializer attributes :id, :event_id, :person_id, :participant_id, :bib_number, :first_name, :last_name, :full_name, :gender, :age, :city, :state_code, :country_code, :flexible_geolocation, :beacon_url, :report_url, :start_offset %i[phone email birthdate emergency_contact emergency_phone].each { |att| attribute att, if: :show_personal_info? } link(:self) { api_v1_effort_path(object) } has_many :split_times, if: :split_times_loaded? def split_times_loaded? object.split_times.loaded? end end
Add some implementation for CapsuleObserver
class CapsuleObserver def self.register SyncCapsuleData.add_observer(self) end # Receives data updates from CapsuleCRM # # data - hash of data from CapsuleCRM # active => Whether the membership is active or not (will be shown in the public directory) # email => The contact email for the membership # name => The organization name # description => The organization description # url => The organization's homepage # product_name => The membership level # membership_id => The membership ID (if this is nil, it must be a new member) # def self.update(data) # Is there a membership ID? # If so, update the data in the appropriate member # If not, create a new member with the synced data # When we are creating a new member, we need to look at what it queues up; we don't want # to send an invoice, for instance. We will probably have to rewrite some of the member#after_create # stuff. end end CapsuleObserver.register
class CapsuleObserver def self.register SyncCapsuleData.add_observer(self) end # Receives data updates from CapsuleCRM # # data - hash of data from CapsuleCRM # active => Whether the membership is active or not (will be shown in the public directory) # email => The contact email for the membership # name => The organization name # description => The organization description # url => The organization's homepage # product_name => The membership level # membership_id => The membership ID (if this is nil, it must be a new member) # def self.update(data) # Is there a membership ID? if data['membership_id'] # If so, update the data in the appropriate member member = Member.where(:membership_number => membership_id).first if member # Member data member.cached_active = (data['active'] == "true") member.product_name = data['product_name'] # member.save TODO we need a way of saving without callbacks happening # Update organization data if org = member.organization org.name = data['name'] org.description = data['description'] org.url = data['url'] # org.save TODO we need a way of saving without callbacks happening end end else # If not, create a new member with the synced data # When we are creating a new member, we need to look at what it queues up; we don't want # to send an invoice, for instance. We will probably have to rewrite some of the member#after_create # stuff. end end end CapsuleObserver.register
Add back pending in before(:all) to test for @myronmarston
# -*- encoding : utf-8 -*- require 'spec_helper' describe StalenessNotificationJob do # NOTE: commented out because now RSpec exists with 1 on pending specs # which is super annoying. # # before(:all) { skip "Staleness notification jobs have been disabled for now." } # before do # allow(ArticleMailer).to receive(:notify_author_of_staleness) { mailer } # end # let(:mailer) { double("ArticleMailer", deliver: true) } # let(:articles) { [create(:article, :stale)] } # subject(:perform_job) { StalenessNotificationJob.new(articles).perform } # it "sends an ArticleMailer" do # expect(mailer).to receive(:deliver) # perform_job # end # context "as side-effects" do # before { perform_job } # it "sets each article's last_notified_author_at to the date the job is run" do # expect(articles.last.reload.last_notified_author_at).to eq Date.today # end # it "does not modify the updated_at value" do # expect(articles.last.updated_at).to be_within(0.1).of(articles.last.created_at) # end # end end
# -*- encoding : utf-8 -*- require 'spec_helper' describe StalenessNotificationJob do before(:all) { skip "Staleness notification jobs have been disabled for now." } before do allow(ArticleMailer).to receive(:notify_author_of_staleness) { mailer } end let(:mailer) { double("ArticleMailer", deliver: true) } let(:articles) { [create(:article, :stale)] } subject(:perform_job) { StalenessNotificationJob.new(articles).perform } it "sends an ArticleMailer" do expect(mailer).to receive(:deliver) perform_job end context "as side-effects" do before { perform_job } it "sets each article's last_notified_author_at to the date the job is run" do expect(articles.last.reload.last_notified_author_at).to eq Date.today end it "does not modify the updated_at value" do expect(articles.last.updated_at).to be_within(0.1).of(articles.last.created_at) end end end
Use acts_as touch option in acts_as_discussion_topic
# frozen_string_literal: true module Extensions::DiscussionTopic::ActiveRecord::Base module ClassMethods # Declare this in model, for it to support discussions. # # @option options [Boolean] :display_globally Set to true if the topic need to be displayed in # comments center. # @option options [Boolean] :touch Set to true if the topic need to be touched upon updating. def acts_as_discussion_topic(display_globally: false, touch: false) acts_as :discussion_topic, class_name: Course::Discussion::Topic.name # For autoload to work correctly after class changed, we store the model name first and # constantize later. Course::Discussion::Topic.global_topic_model_names << name if display_globally # This can be removed after https://github.com/hzamani/active_record-acts_as/pull/78 define_method(:touch_actable) {} unless touch end end end
# frozen_string_literal: true module Extensions::DiscussionTopic::ActiveRecord::Base module ClassMethods # Declare this in model, for it to support discussions. # # @option options [Boolean] :display_globally Set to true if the topic need to be displayed in # comments center. # @option options [Boolean] :touch Set to true if the topic need to be touched upon updating. def acts_as_discussion_topic(display_globally: false, touch: false) acts_as :discussion_topic, class_name: Course::Discussion::Topic.name, touch: touch # For autoload to work correctly after class changed, we store the model name first and # constantize later. Course::Discussion::Topic.global_topic_model_names << name if display_globally end end end
Create the bucket class to represent a rate limit bucket
module Discordrb::Commands class RateLimiter end end
module Discordrb::Commands class Bucket # Makes a new bucket # @param limit [Integer, nil] How many requests the user may perform in the given time_span, or nil if there should be no limit. # @param time_span [Integer, nil] The time span after which the request count is reset, in seconds, or nil if the bucket should never be reset. (If this is nil, limit should be nil too) # @param delay [Integer, nil] The delay for which the user has to wait after performing a request, in seconds, or nil if the user shouldn't have to wait. def initialize(limit, time_span, delay) fail ArgumentError, '`limit` and `time_span` have to either both be set or both be nil!' if !limit != !time_span @limit = limit @time_span = time_span @delay = delay @bucket = {} end end class RateLimiter def initialize end end end
Remove obsolete flux types from Appender.
module KeplerProcessor class Appender < MultifileTaskBase attr_accessor :output_data include Saveable def execute! super do check_consistent_kic_number sort_runners_by_season collate_input_data reinsert_header save! end end private def check_consistent_kic_number raise(RuntimeError, "All files must be for the same star") if @runners.map { |r| r.attributes[:kic_number] }.uniq.count > 1 end def sort_runners_by_season @runners.sort! { |a,b| a.attributes[:season] <=> b.attributes[:season] } end def collate_input_data @output_data = @runners.map { |runner| runner.input_data }.flatten 1 end def reinsert_header @output_data.insert 0, ["# KIC number: #{@runners.first.attributes[:kic_number]}"] @output_data.insert 0, ["# Season: #{season_range}"] end def season_range @season_range ||= "#{@runners.first.attributes[:season]}-#{@runners.last.attributes[:season]}" end def output_filename flux_type = @options[:file_columns] == [0, 1] ? :Rflux : :Cflux @runners.first.input_filename_without_path.sub(/\d{13}/, "#{flux_type}_appended_#{season_range}") # Timestamp always has 13 digits end end end
module KeplerProcessor class Appender < MultifileTaskBase attr_accessor :output_data include Saveable def execute! super do check_consistent_kic_number sort_runners_by_season collate_input_data reinsert_header save! end end private def check_consistent_kic_number raise(RuntimeError, "All files must be for the same star") if @runners.map { |r| r.attributes[:kic_number] }.uniq.count > 1 end def sort_runners_by_season @runners.sort! { |a,b| a.attributes[:season] <=> b.attributes[:season] } end def collate_input_data @output_data = @runners.map { |runner| runner.input_data }.flatten 1 end def reinsert_header @output_data.insert 0, ["# KIC number: #{@runners.first.attributes[:kic_number]}"] @output_data.insert 0, ["# Season: #{season_range}"] end def season_range @season_range ||= "#{@runners.first.attributes[:season]}-#{@runners.last.attributes[:season]}" end def output_filename flux_type = @options[:file_columns] == [0, 1] ? :SAP : :msMAP @runners.first.input_filename_without_path.sub(/\d{13}/, "#{flux_type}_appended_#{season_range}") # Timestamp always has 13 digits end end end
Add delete stack on CF
module StackMaster module AwsDriver class CloudFormation def set_region(region) @region = region @cf = nil end def describe_stacks(options) cf.describe_stacks(options) end def get_template(options) cf.get_template(options) end def describe_stack_events(options) cf.describe_stack_events(options) end def update_stack(options) cf.update_stack(options) end def create_stack(options) cf.create_stack(options) end def validate_template(options) cf.validate_template(options) end private def cf @cf ||= Aws::CloudFormation::Client.new(region: @region) end end end end
module StackMaster module AwsDriver class CloudFormation def set_region(region) @region = region @cf = nil end def delete_stack(options) cf.delete_stack(options) end def describe_stacks(options) cf.describe_stacks(options) end def get_template(options) cf.get_template(options) end def describe_stack_events(options) cf.describe_stack_events(options) end def update_stack(options) cf.update_stack(options) end def create_stack(options) cf.create_stack(options) end def validate_template(options) cf.validate_template(options) end private def cf @cf ||= Aws::CloudFormation::Client.new(region: @region) end end end end
Add an Initial UpsellPage Model
class UpsellPage < ActiveRecord::Base attr_accessible :basic_articles_desc, :basic_courses_desc, :discussion_forums_desc, :exclusive_articles_desc, :heading, :in_depth_courses_desc, :sub_heading belongs_to :club validates :heading, :presence => { :message => "for upsell page can't be blank" } validates :sub_heading, :presence => { :message => "for upsell page can't be blank" } validates :basic_articles_desc, :presence => { :message => "for upsell page can't be blank" } validates :exclusive_articles_desc, :presence => { :message => "for upsell page can't be blank" } validates :basic_courses_desc, :presence => { :message => "for upsell page can't be blank" } validates :in_depth_courses_desc, :presence => { :message => "for upsell page can't be blank" } validates :discussion_forums_desc, :presence => { :message => "for upsell page can't be blank" } end
Fix RJS templates broken by render_with_remotipart alias
module Remotipart # Responder used to automagically wrap any non-xml replies in a text-area # as expected by iframe-transport. module RenderOverrides include ERB::Util def self.included(base) base.class_eval do # Use neither alias_method_chain nor prepend for compatibility alias render_without_remotipart render alias render render_with_remotipart end end def render_with_remotipart *args render_without_remotipart(*args) if remotipart_submitted? textarea_body = response.content_type == 'text/html' ? html_escape(response.body) : response.body response.body = %{<script type=\"text/javascript\">try{window.parent.document;}catch(err){document.domain=document.domain;}</script> <textarea data-type=\"#{response.content_type}\" data-status=\"#{response.response_code}\" data-statusText=\"#{response.message}\">#{textarea_body}</textarea>} response.content_type = ::Rails.version >= '5' ? Mime[:html] : Mime::HTML end response_body end end end
module Remotipart # Responder used to automagically wrap any non-xml replies in a text-area # as expected by iframe-transport. module RenderOverrides include ERB::Util def self.included(base) base.class_eval do # Use neither alias_method_chain nor prepend for compatibility alias render_without_remotipart render alias render render_with_remotipart end end def render_with_remotipart(*args, &block) render_without_remotipart(*args, &block) if remotipart_submitted? textarea_body = response.content_type == 'text/html' ? html_escape(response.body) : response.body response.body = %{<script type=\"text/javascript\">try{window.parent.document;}catch(err){document.domain=document.domain;}</script> <textarea data-type=\"#{response.content_type}\" data-status=\"#{response.response_code}\" data-statusText=\"#{response.message}\">#{textarea_body}</textarea>} response.content_type = ::Rails.version >= '5' ? Mime[:html] : Mime::HTML end response_body end end end
Fix call with second argument, using template source
module ActionView class Template module Handlers class Tex def handles_encoding?; true; end class_attribute :default_format self.default_format = Mime[:pdf] def erb_handler @@erb_handler ||= ActionView::Template.registered_template_handler(:erb) end def self.call(template) new.call(template) end def call(template) compiled_source = erb_handler.call(template) "Latexpdf::compile(begin;#{compiled_source};end)" end end end end end
module ActionView class Template module Handlers class Tex def handles_encoding?; true; end class_attribute :default_format self.default_format = Mime[:pdf] def erb_handler @@erb_handler ||= ActionView::Template.registered_template_handler(:erb) end def self.call(template, source) new.call(template, source) end def call(template, source) compiled_source = erb_handler.call(template, source) "Latexpdf::compile(begin;#{compiled_source};end)" end end end end end
Add Ryan Bates patch to use config from config folder
require 'yaml' class SeleniumOnRailsConfig @@defaults = {:environments => ['test']} def self.get var, default = nil value = configs[var.to_s] value ||= @@defaults[var] value ||= default value ||= yield if block_given? value end private def self.configs unless defined? @@configs file = File.expand_path(File.dirname(__FILE__) + '/../config.yml') @@configs = File.exist?(file) ? YAML.load_file(file) : {} end @@configs end end
require 'yaml' require 'erb' class SeleniumOnRailsConfig @@defaults = {:environments => ['test']} def self.get var, default = nil value = configs[var.to_s] value ||= @@defaults[var] value ||= default value ||= yield if block_given? value end private def self.configs unless defined? @@configs files = [File.expand_path(File.dirname(__FILE__) + '/../config.yml')] files << File.join(RAILS_ROOT, 'config', 'selenium.yml') files.each do |file| @@configs = YAML.load(ERB.new(IO.read(file)).result) if File.exist?(file) end @@configs ||= {} end @@configs end end
Revert "chore: Automatic aliases for permitted_Attributes_for in policies"
# frozen_string_literal: true module Ditty class ApplicationPolicy attr_reader :user, :record def initialize(user, record) @user = user @record = record end def permitted_attributes [] end def method_missing(method_name, *args, &block) return super unless method_name.to_s.start_with? 'permitted_attributes_for_' permitted_attributes end def respond_to_missing?(method_name, _include_private = false) return super unless method_name.to_s.start_with? 'permitted_attributes_for_' true end def response_attributes permitted_attributes end class Scope attr_reader :user, :scope def initialize(user, scope) @user = user @scope = scope end end end end
# frozen_string_literal: true module Ditty class ApplicationPolicy attr_reader :user, :record def initialize(user, record) @user = user @record = record end class Scope attr_reader :user, :scope def initialize(user, scope) @user = user @scope = scope end end end end
Bump the worker docker image to v2.4.0
default['travis_worker_wrapper']['install_type'] = 'docker' override['travis_worker']['environment']['TRAVIS_WORKER_SELF_IMAGE'] = 'quay.io/travisci/worker:v2.3.1-61-g76a687b'
default['travis_worker_wrapper']['install_type'] = 'docker' override['travis_worker']['environment']['TRAVIS_WORKER_SELF_IMAGE'] = 'quay.io/travisci/worker:v2.4.0'
Fix for products having video thumbnail
module ShopFinder module Shops class Wildberries def self.parse_attributes(page) raise 'Not implemented' end def self.parse_images(page) uri = page.uri page.search('ul.carousel/li/a').map do |a| uri.scheme + ':' + a.attributes['rev'].value end end end end end
module ShopFinder module Shops class Wildberries def self.parse_attributes(page) raise 'Not implemented' end def self.parse_images(page) uri = page.uri page.search('ul.carousel/li/a.enabledZoom').map do |a| uri.scheme + ':' + a.attributes['rev'].value unless a.attributes['rev'].nil? end.compact end end end end
Add has_secure_password to User model for newer Rails-Bcrypt integration. Remove unneeded Bcrypt User model methods. Change User model validation to check :password_digest instead of :password_hash.
class User < ActiveRecord::Base include BCrypt validates :email, :password_hash, presence: true validates :email, length: { minimum: 1 } validates :email, uniqueness: true has_many :projects def password @password ||= Password.new(password_hash) end def password=(new_password) @password = Password.create(new_password) self.password_hash = @password end end
class User < ActiveRecord::Base has_secure_password validates :email, :password_digest, presence: true validates :email, length: { minimum: 1 } validates :email, uniqueness: true has_many :projects end
Update SalesPage Model for video Attribute
class SalesPage < ActiveRecord::Base attr_accessible :call_to_action, :heading, :sub_heading belongs_to :club validates :heading, :presence => { :message => "for sales page can't be blank" } validates :sub_heading, :presence => { :message => "for sales page can't be blank" } validates :call_to_action, :presence => { :message => "for sales page can't be blank" } def assign_defaults self.heading = Settings.sales_pages[:default_heading] self.sub_heading = Settings.sales_pages[:default_sub_heading] self.call_to_action = Settings.sales_pages[:default_call_to_action] end end
class SalesPage < ActiveRecord::Base attr_accessible :call_to_action, :heading, :sub_heading, :video belongs_to :club validates :heading, :presence => { :message => "for sales page can't be blank" } validates :sub_heading, :presence => { :message => "for sales page can't be blank" } validates :call_to_action, :presence => { :message => "for sales page can't be blank" } validate :url_exists def assign_defaults self.heading = Settings.sales_pages[:default_heading] self.sub_heading = Settings.sales_pages[:default_sub_heading] self.call_to_action = Settings.sales_pages[:default_call_to_action] end private def url_exists errors.add(:base, "URL is not reachable or malformed - please check your video URL") unless VideoManipulator.validate_url(video) end end
Revert "Revert "Check that publication attachments were actually created.""
require 'csv' logger = Logger.new($stdout) affected_files = [ '20121029125200_upload_dft_publications.csv', '20121029160239_upload_dclg_publications.csv', '20121030160045_upload_brac_publications.csv', '20121030160102_upload_pins_publications.csv' ].map { |filename| Rails.root.join('db/data_migration/', filename) } affected_files.each do |affected_file| logger.info "Processing file #{affected_file}" csv = CSV.read(affected_file, headers: true) csv.each_with_index do |data_row, ix| row = Whitehall::Uploader::PublicationRow.new(data_row.to_hash, ix + 1, logger) begin attachment_urls = (1..50).map { |x| data_row["attachment_#{x}_url"] }.compact document_source = DocumentSource.find_by_url(row.legacy_url) found, missing = attachment_urls.partition { |url| AttachmentSource.find_by_url(url) } if missing.any? edition = if found.any? AttachmentSource.find_by_url(found.first).attachment.editions.last elsif document_source document_source.document.latest_edition end if edition logger.warn "Row #{ix + 2} '#{row.legacy_url}' missing attachments (Edition #{edition.id}) - #{missing.inspect}" else logger.warn "Row #{ix + 2} '#{row.legacy_url}' missing attachments - #{missing.inspect}" end end end end logger.info "Finished processing file #{affected_file}" end
Revert "Revert "Need to pass through a content-type when using upload_image to appease paperclip""
module Spree module Api module TestingSupport module Helpers def json_response case body = JSON.parse(response.body) when Hash body.with_indifferent_access when Array body end end def assert_not_found! expect(json_response).to eq({ "error" => "The resource you were looking for could not be found." }) expect(response.status).to eq 404 end def assert_unauthorized! expect(json_response).to eq({ "error" => "You are not authorized to perform that action." }) expect(response.status).to eq 401 end def stub_authentication! allow(Spree.user_class).to receive(:find_by).with(hash_including(:spree_api_key)) { current_api_user } end # This method can be overriden (with a let block) inside a context # For instance, if you wanted to have an admin user instead. def current_api_user @current_api_user ||= stub_model(Spree::LegacyUser, email: "spree@example.com") end def image(filename) File.open(Spree::Api::Engine.root + "spec/fixtures" + filename) end def upload_image(filename) fixture_file_upload(image(filename).path) end end end end end
module Spree module Api module TestingSupport module Helpers def json_response case body = JSON.parse(response.body) when Hash body.with_indifferent_access when Array body end end def assert_not_found! expect(json_response).to eq({ "error" => "The resource you were looking for could not be found." }) expect(response.status).to eq 404 end def assert_unauthorized! expect(json_response).to eq({ "error" => "You are not authorized to perform that action." }) expect(response.status).to eq 401 end def stub_authentication! allow(Spree.user_class).to receive(:find_by).with(hash_including(:spree_api_key)) { current_api_user } end # This method can be overriden (with a let block) inside a context # For instance, if you wanted to have an admin user instead. def current_api_user @current_api_user ||= stub_model(Spree::LegacyUser, email: "spree@example.com") end def image(filename) File.open(Spree::Api::Engine.root + "spec/fixtures" + filename) end def upload_image(filename) fixture_file_upload(image(filename).path, 'image/jpg') end end end end end
Make sure the hook says something about itself.
require 'cucumber/core/test/mapping' module Cucumber module Core module Test class HookStep def initialize(source, &block) @mapping = Test::Mapping.new(&block) @source = source end def describe_to(visitor, *args) visitor.test_step(self, *args) end def describe_source_to(visitor, *args) visitor.hook(*args) end def execute @mapping.execute end def skip execute end def map self end def match_locations?(locations) false end def inspect "<#{self.class}: #{@mapping.location}>" end end BeforeHook = Class.new(HookStep) AfterHook = Class.new(HookStep) class AroundHook def initialize(source, &block) @source = source @block = block end def call(continue) @block.call(continue) end def describe_to(visitor, *args, &continue) visitor.around_hook(self, *args, &continue) end end end end end
require 'cucumber/core/test/mapping' module Cucumber module Core module Test class HookStep def initialize(source, &block) @mapping = Test::Mapping.new(&block) @source = source end def describe_to(visitor, *args) visitor.test_step(self, *args) end def describe_source_to(visitor, *args) visitor.hook(@mapping.location, *args) end def execute @mapping.execute end def skip execute end def map self end def match_locations?(locations) false end def inspect "<#{self.class}: #{@mapping.location}>" end end BeforeHook = Class.new(HookStep) AfterHook = Class.new(HookStep) class AroundHook def initialize(source, &block) @source = source @block = block end def call(continue) @block.call(continue) end def describe_to(visitor, *args, &continue) visitor.around_hook(self, *args, &continue) end end end end end
Add validation tests to Review model spec
require 'rails_helper' RSpec.describe Review, type: :model do let(:review) { Review.new(title: 'Good Movie', body: 'This was a fantastic film', user_id: User.last.id, film_id: Film.first.id) } describe 'validations' do it 'is valid with valid attributes' do expect(review).to be_valid end it 'is not valid without a title' do review.title = '' expect(review).to_not be_valid end it 'is not valid without a body' do review.body = '' expect(review).to_not be_valid end it 'is not valid without a user' do review.user = nil expect(review).to_not be_valid end it 'is not valid without a film' do review.film = nil expect(review).to_not be_valid end end describe 'associations' do end end
Update the order of the cash flows
module GSkrilla class Base URL = "https://www.google.com/finance?fstype=ii&q=" attr_reader :doc, :income_statements, :cash_flows, :balance_sheets def income_statements @income_statements ||= {} end def cash_flows @cash_flows ||= {} end def balance_sheets @balance_sheets ||= {} end def initialize(symbol) @doc = Nokogiri::HTML(open("#{URL}#{symbol}")) set_statements end private def set_statements income_statements["qtr"] = IncomeStatement.new(to_ary[0]) income_statements["yr"] = IncomeStatement.new(to_ary[1]) cash_flows["qtr"] = CashFlow.new(to_ary[2]) cash_flows["yr"] = CashFlow.new(to_ary[3]) balance_sheets["qtr"] = BalanceSheet.new(to_ary[4]) balance_sheets["yr"] = BalanceSheet.new(to_ary[5]) income_statements.class.send(:include, HashExt) cash_flows.class.send(:include, HashExt) balance_sheets.class.send(:include, HashExt) end def to_ary @to_ary ||= doc.css("table.gf-table").map do |table| table.children.text.split(/\n/).delete_if { |cell| cell.empty? } end end end end
module GSkrilla class Base URL = "https://www.google.com/finance?fstype=ii&q=" attr_reader :doc, :income_statements, :cash_flows, :balance_sheets def income_statements @income_statements ||= {} end def cash_flows @cash_flows ||= {} end def balance_sheets @balance_sheets ||= {} end def initialize(symbol) @doc = Nokogiri::HTML(open("#{URL}#{symbol}")) set_statements end private def set_statements income_statements["qtr"] = IncomeStatement.new(to_ary[0]) income_statements["yr"] = IncomeStatement.new(to_ary[1]) balance_sheets["qtr"] = BalanceSheet.new(to_ary[2]) balance_sheets["yr"] = BalanceSheet.new(to_ary[3]) cash_flows["qtr"] = CashFlow.new(to_ary[4]) cash_flows["yr"] = CashFlow.new(to_ary[5]) income_statements.class.send(:include, HashExt) cash_flows.class.send(:include, HashExt) balance_sheets.class.send(:include, HashExt) end def to_ary @to_ary ||= doc.css("table.gf-table").map do |table| table.children.text.split(/\n/).delete_if { |cell| cell.empty? } end end end end
Work around Time parsing for bad NPR data
require 'time' ## # NPR::Concern::AttrTypecast # module NPR #------------------ # Attributes that are being typecast to Ruby classes ATTR_TYPES = { "id" => :string_to_i, "partnerId" => :string_to_i, "storyDate" => :string_time_parse, "pubDate" => :string_time_parse, "lastModifiedDate" => :string_time_parse, "showDate" => :string_time_parse, "date" => :string_time_parse, "segNum" => :string_to_i, "num" => :string_to_i, "timestamp" => :string_time_at, "duration" => :string_to_i } module Concern module AttrTypecast private #------------------ # Typecasting methods def string_to_i(value) value.to_i end #------------------ def string_time_parse(value) !value.empty? ? Time.parse(value) : nil end #------------------ def string_time_at(value) Time.at(value.to_f) end #------------------ def attr_typecast(key, value) if method = NPR::ATTR_TYPES[key] send method, value else value end end end # AttrTypecast end # Concern end # NPR
require 'time' ## # NPR::Concern::AttrTypecast # module NPR #------------------ # Attributes that are being typecast to Ruby classes ATTR_TYPES = { "id" => :string_to_i, "partnerId" => :string_to_i, "storyDate" => :string_time_parse, "pubDate" => :string_time_parse, "lastModifiedDate" => :string_time_parse, "showDate" => :string_time_parse, "date" => :string_time_parse, "segNum" => :string_to_i, "num" => :string_to_i, "timestamp" => :string_time_at, "duration" => :string_to_i } module Concern module AttrTypecast private #------------------ # Typecasting methods def string_to_i(value) value.to_i end #------------------ def string_time_parse(value) begin !value.empty? ? Time.parse(value) : nil rescue ArgumentError nil end end #------------------ def string_time_at(value) Time.at(value.to_f) end #------------------ def attr_typecast(key, value) if method = NPR::ATTR_TYPES[key] send method, value else value end end end # AttrTypecast end # Concern end # NPR
Solve the unknown branch problem
namespace :git do desc 'Deploy via git pull' task :pull do on roles :app do within release_path do execute :git, :checkout, '--', 'db/schema.rb', 'Gemfile.lock' execute :git, :checkout, (fetch(:branch) || fetch(:stage)) execute :git, :pull end end end end
namespace :git do desc 'Deploy via git pull' task :pull do on roles :app do within release_path do execute :git, :checkout, '--', 'db/schema.rb', 'Gemfile.lock' execute :git, :checkout, "origin/#{(fetch(:branch) || fetch(:stage))}" execute :git, :pull end end end end
Use !(regex =~ str).nil? rather than (regex =~ str) != nil
require 'rbconfig' module Overcommit # Methods relating to the current operating system module OS class << self def windows? (/mswin|msys|mingw|bccwin|wince|emc/ =~ host_os) != nil end def cygwin? (/cygwin/ =~ host_os) != nil end def mac? (/darwin|mac os/ =~ host_os) != nil end def unix? !windows? end def linux? unix? && !mac? && !cygwin? end private def host_os @os ||= ::RbConfig::CONFIG['host_os'] end end end end
require 'rbconfig' module Overcommit # Methods relating to the current operating system module OS class << self def windows? !(/mswin|msys|mingw|bccwin|wince|emc/ =~ host_os).nil? end def cygwin? !(/cygwin/ =~ host_os).nil? end def mac? !(/darwin|mac os/ =~ host_os).nil? end def unix? !windows? end def linux? unix? && !mac? && !cygwin? end private def host_os @os ||= ::RbConfig::CONFIG['host_os'] end end end end
Refactor HW path into method
require "fileutils" require "uri" module TiyoHw class Setup attr_accessor :url def initialize(url) @url = url end def sha matches = /\b[0-9a-f]{5,40}\b/.match(url) matches.to_s if matches && !gist? end def git_url final_url = url.split("/tree/").first "#{final_url}#{'.git' unless final_url.end_with?('.git')}" end def gist? /gist\.github\.com/.match(url) end def dir_name git_url.split(%r{[\/\.]})[-3..-2].join("-") end def clean_dir FileUtils.rm_rf(File.join(File.expand_path(HOMEWORK_DIR), dir_name)) end def setup FileUtils.mkdir_p HOMEWORK_DIR end def cmd setup clean_dir cmds = [] cmds << "cd #{File.expand_path( HOMEWORK_DIR )}" cmds << "git clone #{git_url} #{dir_name}" cmds << "cd #{dir_name}" cmds << "git checkout #{sha} -b submitted_assignment" if sha cmds << "#{EDITOR} ." cmds.join(" && ") end end end
require "fileutils" require "uri" module TiyoHw class Setup attr_accessor :url def initialize(url) @url = url end def sha matches = /\b[0-9a-f]{5,40}\b/.match(url) matches.to_s if matches && !gist? end def git_url final_url = url.split("/tree/").first "#{final_url}#{'.git' unless final_url.end_with?('.git')}" end def gist? /gist\.github\.com/.match(url) end def dir_name git_url.split(%r{[\/\.]})[-3..-2].join("-") end def clean_dir FileUtils.rm_rf(File.join(homework_path, dir_name)) end def homework_path File.expand_path(HOMEWORK_DIR) end def setup FileUtils.mkdir_p homework_path end def cmd setup clean_dir cmds = [] cmds << "cd #{homework_path}" cmds << "git clone #{git_url} #{dir_name}" cmds << "cd #{dir_name}" cmds << "git checkout #{sha} -b submitted_assignment" if sha cmds << "#{EDITOR} ." cmds.join(" && ") end end end
Add controller tests for institutions
require 'rails_helper' RSpec.describe Admin::InstitutionsController, type: :controller do include Devise::TestHelpers # This should return the minimal set of attributes required to create a valid # Admin::Institution. As you add validations to Admin::InstitutionSet, be sure to # adjust the attributes here as well. let(:valid_attributes) { { name: "San Francisco State University" } } before(:each) do # Admin login @request.env["devise.mapping"] = Devise.mappings[:admin] sign_in FactoryGirl.create(:admin_user) # Set parent action @actionPage = FactoryGirl.create(:action_page_with_petition) end describe "GET #index" do it "assigns all actionPage.institutions as @institutions" do institution = Institution.create! valid_attributes @actionPage.institutions << institution get :index, {:action_page_id => @actionPage.id} expect(assigns(:institutions)).to eq([institution]) end it "does not show institutions not linked to the action page" do institution = Institution.create! valid_attributes get :index, { :action_page_id => @actionPage.id } expect(assigns(:institutions)).to be_empty end end describe "POST #create" do context "with valid params" do it "creates a new institution" do expect { post :create, {:action_page_id => @actionPage.id, :institution => valid_attributes} }.to change(Institution, :count).by(1) end it "adds the institution to the action" do expect { post :create, {:action_page_id => @actionPage.id, :institution => valid_attributes} }.to change(@actionPage.institutions, :count).by(1) end it "redirects to the action's institutions overview" do post :create, {:action_page_id => @actionPage.id, :institution => valid_attributes} expect(response).to redirect_to([:admin, @actionPage, Institution]) end end end describe "DELETE #destroy" do it "unlinks the institution from the action" do institution = Institution.create! valid_attributes @actionPage.institutions << institution expect { delete :destroy, {:action_page_id => @actionPage.id, :id => institution.to_param} }.to change(@actionPage.institutions, :count).by(-1) end it "doesn't delete the institution" do institution = Institution.create! valid_attributes @actionPage.institutions << institution expect { delete :destroy, {:action_page_id => @actionPage.id, :id => institution.to_param} }.to_not change(Institution, :count) end it "redirects to the institution_sets list" do institution = Institution.create! valid_attributes @actionPage.institutions << institution delete :destroy, {:action_page_id => @actionPage.id, :id => institution.to_param} expect(response).to redirect_to([:admin, @actionPage, Institution]) end end end
Fix reference to converter positions file
module Api module V3 class TopologyPresenter def initialize(scenario) @scenario = scenario @gql = @scenario.gql(prepare: true) @converters = @gql.present_graph.converters end # Creates a Hash suitable for conversion to JSON by Rails. # # @return [Hash{Symbol=>Object}] # The Hash containing the scenario attributes. # def as_json(*) json = Hash.new json[:converters] = converters json[:links] = links json end ####### private ####### def converters @converters.map do |c| position = positions.find(c) { key: c.key, x: position[:x], y: position[:y], fill_color: ConverterPositions::FILL_COLORS[c.sector_key], stroke_color: '#999', sector: c.sector_key, use: c.use_key } end end def links @converters.map(&:input_links).flatten.uniq.map do |l| { left: l.lft_converter.key, right: l.rgt_converter.key, color: l.carrier.graphviz_color || '#999', type: l.link_type } end end def positions ConverterPositions.new( Rails.root.join('config/converter_positions.yml')) end end end end
module Api module V3 class TopologyPresenter def initialize(scenario) @scenario = scenario @gql = @scenario.gql(prepare: true) @converters = @gql.present_graph.converters end # Creates a Hash suitable for conversion to JSON by Rails. # # @return [Hash{Symbol=>Object}] # The Hash containing the scenario attributes. # def as_json(*) json = Hash.new json[:converters] = converters json[:links] = links json end ####### private ####### def converters @converters.map do |c| position = positions.find(c) { key: c.key, x: position[:x], y: position[:y], fill_color: ConverterPositions::FILL_COLORS[c.sector_key], stroke_color: '#999', sector: c.sector_key, use: c.use_key } end end def links @converters.map(&:input_links).flatten.uniq.map do |l| { left: l.lft_converter.key, right: l.rgt_converter.key, color: l.carrier.graphviz_color || '#999', type: l.link_type } end end def positions ConverterPositions.new(Atlas.data_dir.join('config/node_positions.yml')) end end end end
Remove additional link in business breadcrumbs
class CoronavirusLandingPageController < ApplicationController skip_before_action :set_expiry before_action -> { set_expiry(5.minutes) } def show @content_item = content_item.to_hash breadcrumbs = [{ title: "Home", url: "/", is_page_parent: true }] render "show", locals: { breadcrumbs: breadcrumbs, details: presenter, special_announcement: special_announcement } end def business @content_item = content_item.to_hash breadcrumbs = [ { title: "Home", url: "/" }, { title: "Coronavirus (COVID-19)", url: "/coronavirus", is_page_parent: true }, ] render "business", locals: { breadcrumbs: breadcrumbs, details: business_presenter, } end private def content_item ContentItem.find!(request.path) end def presenter CoronavirusLandingPagePresenter.new(@content_item) end def special_announcement SpecialAnnouncementPresenter.new(@content_item) end def business_presenter BusinessSupportPagePresenter.new(@content_item) end end
class CoronavirusLandingPageController < ApplicationController skip_before_action :set_expiry before_action -> { set_expiry(5.minutes) } def show @content_item = content_item.to_hash breadcrumbs = [{ title: "Home", url: "/", is_page_parent: true }] render "show", locals: { breadcrumbs: breadcrumbs, details: presenter, special_announcement: special_announcement } end def business @content_item = content_item.to_hash breadcrumbs = [{ title: "Home", url: "/" }] render "business", locals: { breadcrumbs: breadcrumbs, details: business_presenter, } end private def content_item ContentItem.find!(request.path) end def presenter CoronavirusLandingPagePresenter.new(@content_item) end def special_announcement SpecialAnnouncementPresenter.new(@content_item) end def business_presenter BusinessSupportPagePresenter.new(@content_item) end end
Add favicon to precompile list
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module GdiMainSite class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
require File.expand_path('../boot', __FILE__) require 'rails/all' config.assets.precompile += [ 'favicon.ico' ] # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module GdiMainSite class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
Move login code to its own method.
# encoding: UTF-8 # Sessions controller. class SessionsController < ApplicationController def create user = User.auth_case_insens(params[:email], params[:password]) if user session[:user_id] = user.id return_to = session.delete(:return_to) redirect_to(return_to || my_url, notice: 'Logged in.') else flash[:error] = 'Login failed.' render :new end end def destroy if session[:user_id] session.delete :user_id redirect_to root_url, notice: 'Logged out.' else redirect_to root_url end end end
# encoding: UTF-8 # Sessions controller. class SessionsController < ApplicationController def create user = User.auth_case_insens(params[:email], params[:password]) if user login(user) else flash[:error] = 'Login failed.' render :new end end def destroy if session[:user_id] session.delete :user_id redirect_to root_url, notice: 'Logged out.' else redirect_to root_url end end private def login(user) session[:user_id] = user.id return_to = session.delete(:return_to) redirect_to(return_to || my_url, notice: 'Logged in.') end end
Make sure step 3 create works
class SettingsController < ApplicationController layout 'settings' helper_method :step def new case step when "1" @user = User.new when "2" @site = Site.new when "3" @messageboard = Messageboard.new when "4" @setting = Setting.new end end def edit end def show end def create case step when "1" @user = User.create(params[:user]) redirect_to '/2' if @user.valid? flash[:error] = "There were errors creating your user." and render :action => :new unless @user.valid? when "2" @user = User.last @site = Site.create params[:site].merge!({:user => @user}) redirect_to '/3' if @site.valid? when "3" @user = User.last @site = Site.last @messageboard = Messageboard.create(params[:messageboard].merge!( {:user => @user, :site => @site} )) redirect_to '/4' if @messageboard.valid? end end def update end private def step @step ||= params[:step] || "1" end end
class SettingsController < ApplicationController layout 'settings' helper_method :step def new case step when "1" @user = User.new when "2" @site = Site.new when "3" @messageboard = Messageboard.new when "4" @setting = Setting.new end end def edit end def show end def create case step when "1" @user = User.create(params[:user]) redirect_to '/2' if @user.valid? flash[:error] = "There were errors creating your user." and render :action => :new unless @user.valid? when "2" @user = User.last @site = Site.create params[:site].merge!({:user => @user}) redirect_to '/3' if @site.valid? when "3" @user = User.last @site = Site.last @messageboard = Messageboard.create(params[:messageboard].merge!( {:theme => "default", :site => @site} )) redirect_to '/4' if @messageboard.valid? end end def update end private def step @step ||= params[:step] || "1" end end
Update controller instance variable from parameter
class ReportController < ApplicationController include Concerns::Repository helper_method :metric_score, :record def repository load_repositories(:show) @score = average_score(@repository) end def metric load_repositories(:repository) @metric = params[:show].underscore.to_sym @record1 = @repository.best_record(@metric) @record2 = @repository.worst_record(@metric) end def metric_score(metric) value = @repository.send(metric) unless value.nil? value = value[:average] value = Metrics::normalize(metric, [value]).first '%.2f' % (value * 100) else '' end end def average_score(repository) metrics = Metrics::IDENTIFIERS sum = metrics.inject(0.0) do |sum, metric| score = repository.send(metric) unless score.nil? value = score[:average] if Metrics::NORMALIZE.include?(metric) value = Metrics::normalize(metric, [value]).first end else value = 0.0 end sum + value end sum / metrics.length end def record(i) instance_variable_get("@record#{i + 1}") end end
class ReportController < ApplicationController include Concerns::Repository helper_method :metric_score, :record def repository load_repositories(:show) @score = average_score(@repository) end def metric load_repositories(:repository) @metric = params[:show].underscore.to_sym @record1 = @repository.best_record(@metric) @record2 = @repository.worst_record(@metric) 2.times do |i| parameter = "record#{i + 1}".to_sym unless params[parameter].nil? record = @repository.get_record(params[parameter]) instance_variable_set("@record#{i + 1}", record) end end end def metric_score(metric) value = @repository.send(metric) unless value.nil? value = value[:average] value = Metrics::normalize(metric, [value]).first '%.2f' % (value * 100) else '' end end def average_score(repository) metrics = Metrics::IDENTIFIERS sum = metrics.inject(0.0) do |sum, metric| score = repository.send(metric) unless score.nil? value = score[:average] if Metrics::NORMALIZE.include?(metric) value = Metrics::normalize(metric, [value]).first end else value = 0.0 end sum + value end sum / metrics.length end def record(i) instance_variable_get("@record#{i + 1}") end end
Add license to new style gemspec.
# -*- encoding: utf-8 -*- require File.expand_path('../lib/jisho/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Erol Fornoles"] gem.email = ["erol.fornoles@gmail.com"] gem.description = %q{Ruby wrapper for Hunspell} gem.summary = %q{Ruby wrapper for Hunspell} gem.homepage = "http://erol.github.com/jisho" gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } gem.files = `git ls-files`.split("\n") gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") gem.name = "jisho" gem.require_paths = ["lib"] gem.version = Jisho::VERSION gem.add_development_dependency 'rspec' end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'yomu/version' Gem::Specification.new do |spec| spec.name = "jisho" spec.version = Jisho::VERSION spec.authors = ["Erol Fornoles"] spec.email = ["erol.fornoles@gmail.com"] spec.description = %q{Ruby wrapper for Hunspell} spec.summary = %q{Ruby wrapper for Hunspell} spec.homepage = "http://erol.github.com/jisho" 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 "rspec", "~> 2.14" end
Use an environment variable so we can point to private data.
require_relative 'test_helper' class ImporterTest < Minitest::Test def setup @i = Transmogriffy::Importer.new(:lighthouse_export_path => './americano') end def test_it_should_accept_options assert @i.lighthouse_export_path end end
require_relative 'test_helper' class ImporterTest < Minitest::Test def setup @i = Transmogriffy::Importer.new(:lighthouse_export_path => ENV['LIGHTHOUSE_EXPORT_PATH']) end def test_it_should_accept_options assert @i.lighthouse_export_path end end
Delete password field from migration
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :name t.integer :age t.string :gender t.string :location t.string :password t.string :password_digest t.string :email t.string :pic_url t.string :tagline t.text :about t.timestamps end end end
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :name t.integer :age t.string :gender t.string :location t.string :password_digest t.string :email t.string :pic_url t.string :tagline t.text :about t.timestamps end end end
Test that flat projects install and boot correctly
RSpec.describe "new app", type: :cli do it "boots and displays a welcome page" do with_project do run_app do |app| expect(app.get("/")).to eq "<html><body><h1>Welcome to dry-web-roda!</h1></body></html>" end end end end
RSpec.describe "new app", type: :cli do describe "umbrella project" do it "boots and displays a welcome page" do with_project do run_app do |app| expect(app.get("/")).to eq "<html><body><h1>Welcome to dry-web-roda!</h1></body></html>" end end end end describe "flat project" do it "boots and displays a welcome page" do with_project arch: "flat" do run_app do |app| expect(app.get("/")).to eq "<html><body><h1>Welcome to dry-web-roda!</h1></body></html>" end end end end end
Update endpoints used by WP OAuth Server 3.1.3
require 'omniauth-oauth2' module OmniAuth module Strategies class WordpressHosted < OmniAuth::Strategies::OAuth2 # Give your strategy a name. option :name, 'wordpress_hosted' # This is where you pass the options you would pass when # initializing your consumer from the OAuth gem. option :client_options, { token_url: "/oauth/token", access_url: "/oauth/authorize" } # These are called after authentication has succeeded. If # possible, you should try to set the UID without making # additional calls (if the user id is returned with the token # or as a URI parameter). This may not be possible with all # providers. uid{ raw_info['ID'] } info do { name: raw_info['display_name'], email: raw_info['user_email'], nickname: raw_info['user_nicename'], urls: { "Website" => raw_info['user_url'] } } end extra do { :raw_info => raw_info } end def raw_info access_token.get(options[:client_options][:access_url]).parsed || {} end end end end
require 'omniauth-oauth2' module OmniAuth module Strategies class WordpressHosted < OmniAuth::Strategies::OAuth2 # Give your strategy a name. option :name, 'wordpress_hosted' # This is where you pass the options you would pass when # initializing your consumer from the OAuth gem. option :client_options, { token_url: "/oauth/token", authorize_url: "/oauth/authorize" } # These are called after authentication has succeeded. If # possible, you should try to set the UID without making # additional calls (if the user id is returned with the token # or as a URI parameter). This may not be possible with all # providers. uid{ raw_info['ID'] } info do { name: raw_info['display_name'], email: raw_info['user_email'], nickname: raw_info['user_nicename'], urls: { "Website" => raw_info['user_url'] } } end extra do { :raw_info => raw_info } end def raw_info access_token.get(options[:client_options][:access_url]).parsed || {} end end end end
Create test for ruby aggregation
require_relative '../../spec_helper' RSpec.describe Languages::Ruby::AggregationRuby do before :all do @rubyAggr = Languages::Ruby::AggregationRuby.new @singleResult = "abc" end context "When is a single aggregation with @" do it "Simple case with @" do captured = @rubyAggr.get_aggregation("abc.new\n") expect(captured).to eq(@singleResult) end it "Whitespace before" do captured = @rubyAggr.get_aggregation(" abc.new\n") expect(captured).to eq(@singleResult) end it "With whitespace before and after" do captured = @rubyAggr.get_aggregation(" abc.new \n") expect(captured).to eq(@singleResult) end it "Whitespace before dot" do captured = @rubyAggr.get_aggregation("abc .new\n") expect(captured).to eq(@singleResult) end it "Whitespace after dot" do captured = @rubyAggr.get_aggregation("abc. new\n") expect(captured).to eq(@singleResult) end it "Between whitespace" do captured = @rubyAggr.get_aggregation("abc . new\n") expect(captured).to eq(@singleResult) end end context "When there is an aggregation with parameters" do it "With a single parameter" do captured = @rubyAggr.get_aggregation("abc.new a") expect(captured).to eq(@singleResult) end it "With multiple parameters" do captured = @rubyAggr.get_aggregation("abc.new a b c") expect(captured).to eq(@singleResult) end it "With single parameter with parenthesis" do captured = @rubyAggr.get_aggregation("abc.new(a)") expect(captured).to eq(@singleResult) end it "With multiple parameter with parenthesis" do captured = @rubyAggr.get_aggregation("abc.new(a,b, c)") expect(captured).to eq(@singleResult) end end context "When there is an aggregation with parameters" do it "Method calling with new on it" do captured = @rubyAggr.get_aggregation("abc.newton") expect(captured).to eq(nil) end end after :all do @rubyAggr = nil @singleResult = nil end end
Bump minimum coverage to 100%
require 'simplecov-rcov' require 'coveralls' require 'coverage/kit' Coverage::Kit.setup(minimum_coverage: 95.2)
require 'simplecov-rcov' require 'coveralls' require 'coverage/kit' Coverage::Kit.setup(minimum_coverage: 100)
Fix email template demo page
class PagesController < ApplicationController skip_authorization_check skip_before_action :authenticate_user! # Preview html email template def email tpl = (params[:layout] || 'hero').to_sym tpl = :hero unless [:email, :hero, :simple].include? tpl file = 'users/mailer/welcome' @user = User.first || User.new render file, layout: "emails/#{tpl}" if params[:premail] == 'true' puts "\n!!! USING PREMAILER !!!\n\n" pre = Premailer.new(response_body[0], warn_level: Premailer::Warnings::SAFE) reset_response # pre.warnings render text: pre.to_inline_css, layout: false end end def error redirect_to root_path if flash.empty? end end
class PagesController < ApplicationController skip_authorization_check skip_before_action :authenticate_user! # Preview html email template def email tpl = (params[:layout] || 'hero').to_sym tpl = :hero unless [:email, :hero, :simple].include? tpl file = 'user_mailer/welcome_email' @user = User.first || User.new render file, layout: "emails/#{tpl}" if params[:premail] == 'true' puts "\n!!! USING PREMAILER !!!\n\n" pre = Premailer.new(response_body[0], warn_level: Premailer::Warnings::SAFE) reset_response # pre.warnings render text: pre.to_inline_css, layout: false end end def error redirect_to root_path if flash.empty? end end
Write post test for new ticket
require 'test_helper' class TicketsTest < ActiveSupport::TestCase include Rack::Test::Methods include TestHelpers::AuthHelper include TestHelpers::JsonHelper def app Rails.application end # POST /helpdesk/ticket def test_post_helpdesk_ticket project_id = Project.first.id description = "jake renzella's comment :)" post with_auth_token "/api/helpdesk/ticket?project_id=#{project_id}&description=#{description}", Project.first.user actual_ticket = JSON.parse(last_response.body)[0] end # GET /helpdesk/ticket def test_get_unresolved_helpdesk_tickets get with_auth_token "/api/helpdesk/ticket" assert_json_equal HelpdeskTicket.all_unresolved, last_response_body end # GET /helpdesk/ticket?filter=resolved def test_get_resolved_helpdesk_tickets get with_auth_token "/api/helpdesk/ticket?filter=resolved" assert_json_equal HelpdeskTicket.all_resolved, last_response_body end # GET /helpdesk/ticket/:id # id = 1 def test_get_helpdesk_ticket_with_id id = 1 get with_auth_token "/api/helpdesk/ticket/#{id}" assert_json_equal HelpdeskTicket.find(id), last_response_body end end
require 'test_helper' class TicketsTest < ActiveSupport::TestCase include Rack::Test::Methods include TestHelpers::AuthHelper include TestHelpers::JsonHelper def app Rails.application end # POST /helpdesk/ticket def test_post_helpdesk_ticket project = Randomizer.random_record_for_model(Project) ticket = { project_id: project.id, description: Populator.words(5..10), task_definition_id: rand > 0.33 ? Randomizer.random_task_def_for_project(project).id : nil } data_to_post = add_auth_token ticket, project.user post_json "/api/helpdesk/ticket", data_to_post expected_ticket = HelpdeskTicket.last assert_json_equal expected_ticket, last_response_body end # GET /helpdesk/ticket def test_get_unresolved_helpdesk_tickets get with_auth_token "/api/helpdesk/ticket" assert_json_equal HelpdeskTicket.all_unresolved, last_response_body end # GET /helpdesk/ticket?filter=resolved def test_get_resolved_helpdesk_tickets get with_auth_token "/api/helpdesk/ticket?filter=resolved" assert_json_equal HelpdeskTicket.all_resolved, last_response_body end # GET /helpdesk/ticket/:id # id = 1 def test_get_helpdesk_ticket_with_id id = 1 get with_auth_token "/api/helpdesk/ticket/#{id}" assert_json_equal HelpdeskTicket.find(id), last_response_body end end
Set identity on new landlord contact
class ApartmentsController < MyplaceonlineController def model Apartment end def display_obj(obj) obj.location.name end protected def sorts ["apartments.updated_at DESC"] end def new_build @obj.location = Location.new @obj.landlord = Contact.new @obj.landlord.ref = Identity.new end def obj_params params.require(:apartment).permit( location_attributes: LocationsController.param_names.push(:id), landlord_attributes: ContactsController.param_names.push(:id) ) end def create_presave @obj.location.identity = current_user.primary_identity end def presave set_from_existing(:location_selection, Location, :location) set_from_existing(:landlord_selection, Contact, :landlord) end end
class ApartmentsController < MyplaceonlineController def model Apartment end def display_obj(obj) obj.location.name end protected def sorts ["apartments.updated_at DESC"] end def new_build @obj.location = Location.new @obj.landlord = Contact.new @obj.landlord.ref = Identity.new end def obj_params params.require(:apartment).permit( location_attributes: LocationsController.param_names.push(:id), landlord_attributes: ContactsController.param_names.push(:id) ) end def create_presave @obj.location.identity = current_user.primary_identity @obj.landlord.identity = current_user.primary_identity end def presave set_from_existing(:location_selection, Location, :location) set_from_existing(:landlord_selection, Contact, :landlord) end end
Update to require yum-epel for all repository releases
# # Author:: Andy Thompson (<andy@webtatic.com>) # Recipe:: yum-epel::default # # Copyright 2014, Andy Thompson # # 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 %w( webtatic webtatic-debuginfo webtatic-source webtatic-archive webtatic-archive-debuginfo webtatic-archive-source webtatic-testing webtatic-testing-debuginfo webtatic-testing-source ).each do |repo| next unless node['yum'][repo]['managed'] case node['platform_family'] when 'rhel' case node['platform_version'].to_i when 7 include_recipe 'yum-epel' unless run_context.loaded_recipe?('yum-epel') end end yum_repository repo do node['yum'][repo].each do |key, value| next if key == 'managed' send key, value end action :create end end
# # Author:: Andy Thompson (<andy@webtatic.com>) # Recipe:: yum-epel::default # # Copyright 2014, Andy Thompson # # 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 %w( webtatic webtatic-debuginfo webtatic-source webtatic-archive webtatic-archive-debuginfo webtatic-archive-source webtatic-testing webtatic-testing-debuginfo webtatic-testing-source ).each do |repo| next unless node['yum'][repo]['managed'] include_recipe 'yum-epel' unless run_context.loaded_recipe?('yum-epel') yum_repository repo do node['yum'][repo].each do |key, value| next if key == 'managed' send key, value end action :create end end
Update DBeaver community to v3.3.0
cask :v1 => 'dbeaver-community' do version '3.2.0' if Hardware::CPU.is_32_bit? sha256 '707e83f17e2dd0906d82f95b440064142424fbe18aceb1c1c1f66a78425c9ffc' url "http://dbeaver.jkiss.org/files/dbeaver-#{version}-macosx.cocoa.x86.zip" else sha256 'b2789cd47d440fbafb251c12e3319947c20ccb35eac25fc95426c0da784888ec' url "http://dbeaver.jkiss.org/files/dbeaver-#{version}-macosx.cocoa.x86_64.zip" end name 'DBeaver Community Edition' homepage 'http://dbeaver.jkiss.org/' license :oss app 'dbeaver/dbeaver.app' end
cask :v1 => 'dbeaver-community' do version '3.3.0' if Hardware::CPU.is_32_bit? sha256 'd91acbac3dc2c86d20f3562f2b7ef5e5a87229a9f32f7bc8f4542d135c5eb31e' url "http://dbeaver.jkiss.org/files/dbeaver-#{version}-macosx.cocoa.x86.zip" else sha256 'c8dbf2f6f86c64ea4e2812336ef0f4d35af6659ece26a2afdcb4de95d6d991cd' url "http://dbeaver.jkiss.org/files/dbeaver-#{version}-macosx.cocoa.x86_64.zip" end name 'DBeaver Community Edition' homepage 'http://dbeaver.jkiss.org/' license :oss app 'dbeaver/dbeaver.app' end
TEST CASE: Trying to delete a sequence used within an `_if` block.
require 'spec_helper' describe Api::SequencesController do before :each do request.headers["accept"] = 'application/json' end include Devise::Test::ControllerHelpers describe '#destroy' do let(:user) { FactoryGirl.create(:user) } let(:device) { user.device } let(:sequence) { FactoryGirl.create(:sequence, device: device) } it 'destroys a sequence' do sign_in user input = { id: sequence.id } delete :destroy, params: input expect(response.status).to eq(200) expect { sequence.reload } .to(raise_error(ActiveRecord::RecordNotFound)) end it 'doesnt destroy other peoples sequence' do sign_in user other_dudes = FactoryGirl.create(:sequence) input = { id: other_dudes.id } delete :destroy, params: input expect(response.status).to eq(403) end end end
require 'spec_helper' describe Api::SequencesController do before :each do request.headers["accept"] = 'application/json' end include Devise::Test::ControllerHelpers describe '#destroy' do let(:user) { FactoryGirl.create(:user) } let(:device) { user.device } let(:sequence) { FactoryGirl.create(:sequence, device: device) } it 'destroys a sequence' do sign_in user input = { id: sequence.id } delete :destroy, params: input expect(response.status).to eq(200) expect { sequence.reload } .to(raise_error(ActiveRecord::RecordNotFound)) end it 'doesnt destroy other peoples sequence' do sign_in user other_dudes = FactoryGirl.create(:sequence) input = { id: other_dudes.id } delete :destroy, params: input expect(response.status).to eq(403) end it 'does not destroy a sequence when in use by a sequence' do before = SequenceDependency.count program = [ { kind: "_if", args: { lhs:"x", op:"is", rhs:0, _then: { kind: "execute", args: { sub_sequence_id: sequence.id } }, _else: { kind: "execute", args: { sub_sequence_id: sequence.id } }, } } ] Sequences::Create.run!(name: "Dep. tracking", device: user.device, body: program) expect(SequenceDependency.count).to be > before sd = SequenceDependency.last newest = Sequence.last expect(sd.dependency).to eq(sequence) expect(sd.sequence).to eq(newest) sign_in user before = Sequence.count delete :destroy, params: { id: sequence.id } after = Sequence.count expect(response.status).to eq(422) expect(before).to eq(after) expect(json[:sequence]).to include("sequences are still relying on this sequence") end end end
Fix error with converting nil to markdown
# frozen_string_literal: true #= Helpers for campaigns views module CampaignHelper def nav_link(link_text, link_path) class_name = current_page?(link_path) ? 'active' : '' content_tag(:li, class: 'nav__item', id: "#{params[:action]}-link") do content_tag(:p) do link_to(link_text, link_path, class: class_name) end end end def html_from_markdown(markdown) converter = Redcarpet::Markdown.new(Redcarpet::Render::HTML) raw converter.render(markdown) end end
# frozen_string_literal: true #= Helpers for campaigns views module CampaignHelper def nav_link(link_text, link_path) class_name = current_page?(link_path) ? 'active' : '' content_tag(:li, class: 'nav__item', id: "#{params[:action]}-link") do content_tag(:p) do link_to(link_text, link_path, class: class_name) end end end def html_from_markdown(markdown) return unless markdown converter = Redcarpet::Markdown.new(Redcarpet::Render::HTML) raw converter.render(markdown) end end
Add spec testing users promotion rule search
require 'spec_helper' feature 'Promotion with user rule', js: true do stub_authorization! given(:promotion) { create :promotion } background do visit spree.edit_admin_promotion_path(promotion) end context "with an attempted XSS" do let(:xss_string) { %(<script>throw("XSS")</script>) } given!(:user) { create(:user, email: xss_string) } scenario "adding an option value rule" do select2 "User", from: "Add rule of type" within("#rules_container") { click_button "Add" } select2_search "<script>", from: "Choose users" expect(page).to have_content(xss_string) end end end
require 'spec_helper' feature 'Promotion with user rule', js: true do stub_authorization! given(:promotion) { create :promotion } background do visit spree.edit_admin_promotion_path(promotion) end context "multiple users" do let!(:user) { create(:user, email: 'foo@example.com') } let!(:other_user) { create(:user, email: 'bar@example.com') } scenario "searching a user" do select2 "User", from: "Add rule of type" within("#rules_container") { click_button "Add" } select2_search "foo", from: "Choose users", select: false expect(page).to have_content('foo@example.com') expect(page).not_to have_content('bar@example.com') end end context "with an attempted XSS" do let(:xss_string) { %(<script>throw("XSS")</script>) } given!(:user) { create(:user, email: xss_string) } scenario "adding an option value rule" do select2 "User", from: "Add rule of type" within("#rules_container") { click_button "Add" } select2_search "<script>", from: "Choose users" expect(page).to have_content(xss_string) end end end