Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix NPE when no search results found.
class Api::V1::GeocoderController < ApplicationController respond_to :json MAPZEN_HOST = 'http://search.mapzen.com' API_KEY = 'api_key=' + ENV['MAPZEN_API_KEY'] def structured_geocode render json: call_mapzen('/v1/search/structured') end def autocomplete render json: call_mapzen('/v1/autocomplete') end def search render json: call_mapzen('/v1/search') end def combined_search places = Place.fuzzy_search(name: params[:text]) locations = call_mapzen('/v1/autocomplete') places = places.map { |p| {name: p.name, lat: p.latitude, lon: p.longitude, type: p.type.downcase, id: p.id} } render json: places.concat(locations) end private def call_mapzen(url) response = HTTParty.get(MAPZEN_HOST + url + '?' + API_KEY + '&' + params.to_query) JSON.parse(response.body)['features'].map { |l| {name: l['properties']['label'].gsub(/, Germany/, ''), lat: l['geometry']['coordinates'][1], lon: l['geometry']['coordinates'][0], id: l['properties']['id'], type: 'location'} } end end
class Api::V1::GeocoderController < ApplicationController respond_to :json MAPZEN_HOST = 'http://search.mapzen.com' API_KEY = 'api_key=' + ENV['MAPZEN_API_KEY'] def structured_geocode render json: call_mapzen('/v1/search/structured') end def autocomplete render json: call_mapzen('/v1/autocomplete') end def search render json: call_mapzen('/v1/search') end def combined_search places = Place.fuzzy_search(name: params[:text]) locations = call_mapzen('/v1/autocomplete') places = places.map { |p| {name: p.name, lat: p.latitude, lon: p.longitude, type: p.type.downcase, id: p.id} } render json: places.concat(locations) end private def call_mapzen(url) response = HTTParty.get(MAPZEN_HOST + url + '?' + API_KEY + '&' + params.to_query) results = JSON.parse(response.body)['features'] if results results.map { |l| {name: l['properties']['label'].gsub(/, Germany/, ''), lat: l['geometry']['coordinates'][1], lon: l['geometry']['coordinates'][0], id: l['properties']['id'], type: 'location'} } else [] end end end
Enforce https on main site
require 'bundler' Bundler.require(:default) base = File.dirname(__FILE__) ['api/v1', 'web/app'].each do |app| require File.join(base, 'app', app) end map '/v1' do # setup ssl requirements use Rack::SslEnforcer, Evercam::Config[:api][:ssl] # allow requests from anywhere use Rack::Cors do allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post, :put, :delete, :options] end end # ensure cookies work across subdomains use Rack::Session::Cookie, Evercam::Config[:cookies] run Evercam::APIv1 end map '/' do run Evercam::WebApp end
require 'bundler' Bundler.require(:default) base = File.dirname(__FILE__) ['api/v1', 'web/app'].each do |app| require File.join(base, 'app', app) end map '/v1' do # setup ssl requirements use Rack::SslEnforcer, Evercam::Config[:api][:ssl] # allow requests from anywhere use Rack::Cors do allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post, :put, :delete, :options] end end # ensure cookies work across subdomains use Rack::Session::Cookie, Evercam::Config[:cookies] run Evercam::APIv1 end map '/' do # setup ssl requirements use Rack::SslEnforcer, Evercam::Config[:api][:ssl] run Evercam::WebApp end
Make sure that the binary-builder pipeline fails loudly when it fails to build a binary
#!/usr/bin/env ruby require 'yaml' binary_name = ENV['BINARY_NAME'] builds_dir = File.join(Dir.pwd, 'builds-yaml') builds_path = File.join(builds_dir, "#{binary_name}-builds.yml") builds = YAML.load_file(builds_path) version = builds[binary_name].shift unless version puts "There are no new builds for #{binary_name} requested." exit end system(<<-EOF) cd binary-builder ./bin/binary-builder #{binary_name} #{version} echo "#{builds.to_yaml}" > #{builds_path} cd #{builds_dir} git config --global user.email "ci@localhost" git config --global user.name "CI Bot" git commit -am "Complete building #{binary_name} - #{version} and remove it from builds" EOF
#!/usr/bin/env ruby require 'yaml' binary_name = ENV['BINARY_NAME'] builds_dir = File.join(Dir.pwd, 'builds-yaml') builds_path = File.join(builds_dir, "#{binary_name}-builds.yml") builds = YAML.load_file(builds_path) version = builds[binary_name].shift unless version puts "There are no new builds for #{binary_name} requested." exit end exit system(<<-EOF) set -e cd binary-builder ./bin/binary-builder #{binary_name} #{version} echo "#{builds.to_yaml}" > #{builds_path} cd #{builds_dir} git config --global user.email "ci@localhost" git config --global user.name "CI Bot" git commit -am "Complete building #{binary_name} - #{version} and remove it from builds" EOF
Fix spec that started failing because of change history of this repo
require 'spec_helper' module Pronto describe Rubocop do let(:rubocop) { Rubocop.new } describe '#run' do subject { rubocop.run(patches) } context 'patches are nil' do let(:patches) { nil } it { should == [] } end context 'no patches' do let(:patches) { [] } it { should == [] } end context 'pronto-rubocop repo itself' do let(:repo) { Rugged::Repository.init_at('.') } let(:patches) { repo.diff('f8d5f2c', repo.head.target) } its(:count) { should > 4 } its(:'first.level') { should == :info } its(:'first.msg') { should == 'Missing top-level class documentation comment.' } end end describe '#level' do subject { rubocop.level(severity) } ::Rubocop::Cop::Offence::SEVERITIES.each do |severity| let(:severity) { severity } context "severity '#{severity}' conversion to Pronto level" do it { should_not be_nil } end end end end end
require 'spec_helper' module Pronto describe Rubocop do let(:rubocop) { Rubocop.new } describe '#run' do subject { rubocop.run(patches) } context 'patches are nil' do let(:patches) { nil } it { should == [] } end context 'no patches' do let(:patches) { [] } it { should == [] } end context 'pronto-rubocop repo itself' do let(:repo) { Rugged::Repository.init_at('.') } let(:patches) { repo.diff('f8d5f2c', repo.head.target) } its(:count) { should > 3 } its(:'first.level') { should == :info } its(:'first.msg') { should =~ /Missing.*comment./ } end end describe '#level' do subject { rubocop.level(severity) } ::Rubocop::Cop::Offence::SEVERITIES.each do |severity| let(:severity) { severity } context "severity '#{severity}' conversion to Pronto level" do it { should_not be_nil } end end end end end
Fix wsse-header: remove unwanted spaces
module Emarsys class Client def username raise ArgumentError, "Emarsys.api_username is not set" if Emarsys.api_username.nil? Emarsys.api_username end def password raise ArgumentError, "Emarsys.api_password is not set" if Emarsys.api_password.nil? Emarsys.api_password end def x_wsse_string string = 'UsernameToken ' string += 'Username = "' + username + '", ' string += 'PasswordDigest = "' + header_password_digest + '", ' string += 'Nonce = "' + header_nonce + '", ' string += 'Created = "' + header_created + '"' string end def header_password_digest Base64.encode64(calculated_digest).gsub("\n", "") end def header_nonce Digest::MD5.hexdigest(header_created) end def header_created Time.now.utc.iso8601 end def calculated_digest Digest::SHA1.hexdigest(header_nonce + header_created + password) end end end
module Emarsys class Client def username raise ArgumentError, "Emarsys.api_username is not set" if Emarsys.api_username.nil? Emarsys.api_username end def password raise ArgumentError, "Emarsys.api_password is not set" if Emarsys.api_password.nil? Emarsys.api_password end def x_wsse_string string = 'UsernameToken ' string += 'Username="' + username + '", ' string += 'PasswordDigest="' + header_password_digest + '", ' string += 'Nonce="' + header_nonce + '", ' string += 'Created="' + header_created + '"' string end def header_password_digest Base64.encode64(calculated_digest).gsub("\n", "") end def header_nonce Digest::MD5.hexdigest(header_created) end def header_created Time.now.utc.iso8601 end def calculated_digest Digest::SHA1.hexdigest(header_nonce + header_created + password) end end end
Switch debug to be a different color and add a success color
require 'highline' module Opsicle module Output def self.terminal HighLine.color_scheme = color_scheme @terminal ||= HighLine.new end def self.color_scheme @color_scheme ||= HighLine::ColorScheme.new( :normal => [], :error => [:bold, :red], :warning => [:bold, :yellow], :verbose => [:bold, :magenta], :debug => [:bold, :green], ) end def self.say(msg, log_style=:normal) if $color terminal.say "<%= color('#{msg}', '#{log_style}') %>" else terminal.say msg end end def self.say_verbose(msg) terminal.say "<%= color('#{msg}', 'verbose') %>" if $verbose end def self.ask(*args) terminal.ask(*args) end end end
require 'highline' module Opsicle module Output def self.terminal HighLine.color_scheme = color_scheme @terminal ||= HighLine.new end def self.color_scheme @color_scheme ||= HighLine::ColorScheme.new( :normal => [], :error => [:bold, :red], :warning => [:bold, :yellow], :verbose => [:bold, :magenta], :debug => [:bold, :cyan], :success => [:bold, :green], ) end def self.say(msg, log_style=:normal) if $color terminal.say "<%= color('#{msg}', '#{log_style}') %>" else terminal.say msg end end def self.say_verbose(msg) terminal.say "<%= color('#{msg}', 'verbose') %>" if $verbose end def self.ask(*args) terminal.ask(*args) end end end
Make sure a valid authentication method has been specified.
#!/usr/bin/ruby -w require 'rubygems'; require 'cgi'; require 'yaml' require 'authenticate'; require 'engine'; require 'twitter' # configuration is done entirely through config.yaml CONFIG_FILE = 'config.yaml' if File.exist?(CONFIG_FILE) && File.ftype(CONFIG_FILE) == 'file' CONFIG = YAML::load(File.read('config.yaml')) else abort "\n\nPlease edit config-example.yaml and save it as config.yaml\n\n" end # don't check in more than once every three minutes UPDATE_EVERY = CONFIG['update_every'] < 3 ? 3 : CONFIG['update_every'] DEBUG_MODE = false AUTH_MODE = CONFIG['auth_mode'] if AUTH_MODE == 'oauth' require 'twitter_oauth' else # OAuth mode automatically gets these gems from twitter_oauth. require 'json'; require 'rest-open-uri' end # engines on! $turp = Engine.new if ARGV[0] == 'out' until 1 == 2 print '> ' status = STDIN.gets.chomp! $turp.post_new_status(status) unless status.empty? puts end else until 1 == 2 since_id = $turp.get_all_timelines(since_id) sleep(UPDATE_EVERY * 60) end end
#!/usr/bin/ruby -w require 'rubygems'; require 'cgi'; require 'yaml' require 'authenticate'; require 'engine'; require 'twitter' # configuration is done entirely through config.yaml CONFIG_FILE = 'config.yaml' if File.exist?(CONFIG_FILE) && File.ftype(CONFIG_FILE) == 'file' CONFIG = YAML::load(File.read('config.yaml')) else abort "\n\nPlease edit config-example.yaml and save it as config.yaml\n\n" end DEBUG_MODE = false # don't check in more than once every three minutes UPDATE_EVERY = CONFIG['update_every'] < 3 ? 3 : CONFIG['update_every'] AUTH_MODE = CONFIG['auth_mode'] if AUTH_MODE == 'basic' # OAuth mode automatically gets these gems from twitter_oauth. require 'json'; require 'rest-open-uri' elsif AUTH_MODE == 'oauth' require 'twitter_oauth' else abort 'Invalid authentication mode. You must use basic or oauth.' end # engines on! $turp = Engine.new if ARGV[0] == 'out' until 1 == 2 print '> ' status = STDIN.gets.chomp! $turp.post_new_status(status) unless status.empty? puts end else until 1 == 2 since_id = $turp.get_all_timelines(since_id) sleep(UPDATE_EVERY * 60) end end
Monitor overall CPU usage, and disk0 throughput (assumed capacity of 750MB/s).
#!/usr/bin/env ruby # require "bignum" require "rubygems" require "bundler/setup" Bundler.require(:default, :development) require "launchpad" # "Each element has a brightness value from 00h – 3Fh (0 – 63), where 0 is off and 3Fh is full brightness." def set_color(device, x, y, r, g, b) output = device.instance_variable_get(:@output) led = (y * 10) + x + 11 x = output.write_sysex([ # SysEx Begin: 0xF0, # Manufacturer/Device: 0x00, 0x20, 0x29, 0x02, 0x18, # Command: 0x0B, # LED: led, # Red, Green, Blue: r, g, b, # SysEx End: 0xF7, ]) puts "ERROR: #{x}" if x != 0 x end def goodbye(interaction) (0..7).each do |x| (0..7).each do |y| set_color(interaction.device, x, y, 0x00, 0x00, 0x00) sleep 0.001 end end end def bar(interaction, x, val, r, g, b) (0..val).each do |y| set_color(interaction.device, x, y, r, g, b) end ((val+1)..7).each do |y| set_color(interaction.device, x, y, 0x00, 0x00, 0x00) end end interaction = Launchpad::Interaction.new(device_name: "Launchpad MK2") monitor = Thread.new do loop do fields = `iostat -c 2 disk0`.split(/\n/).last.strip.split(/\s+/) cpu_pct = 100 - fields[-4].to_i cpu_usage = ((cpu_pct / 100.0) * 8.0).round.to_i disk_pct = (fields[2].to_f / 750.0) * 100.0 disk_usage = ((disk_pct / 100.0) * 8.0).round.to_i puts "io=#{disk_pct}%, cpu=#{cpu_pct}%" bar(interaction, 0, cpu_usage, 0x3F, 0x00, 0x00) bar(interaction, 1, disk_usage, 0x00, 0x3F, 0x00) end end interaction.response_to(:mixer, :down) do |_interaction, action| puts "Shutting down" begin monitor.kill goodbye(interaction) interaction.stop rescue Exception => e puts e.inspect end end interaction.start
Add a more complex spec that ties the various mixins together
require 'spec_helper' describe IPTables::Rule do context "when creating complex rules" do describe "like allow traffic in on eth1 from 10.0.0.0/24 on port 443 with a new state" do subject do rule = IPTables::Rule.new rule.chain = :input rule.target = :accept rule.protocol = :tcp rule.source = '10.0.0.0/24' rule.destination_port = 443 rule.add_module 'state' rule.state = :new rule.in_interface = 'eth1' rule end its(:to_iptables) { should == '-A INPUT -i eth1 -s 10.0.0.0/24 -p tcp --dport 443 -m state --state NEW -j ACCEPT' } end end end
Rename duplicate pacbio id lims
# frozen_string_literal: true namespace :pac_bio_run_table do desc 'Update pac_bio_run_name column with the values from id_pac_bio_run_lims' task rename_duplicate_pac_bio_runs: :environment do list_of_runs = [70_489, 99_999] PacBioRun.where(id_pac_bio_run_lims: list_of_runs).each do |pac_bio_run| pac_bio_run.update(id_pac_bio_run_lims: 'MIGRATED_DPL269_' + pac_bio_run.id_pac_bio_run_lims) end end end
Use correct names for LWRPs
bash_it_version = version_string_for('bash_it') git "#{Chef::Config[:file_cache_path]}/bash_it" do repository node['bash_it']['repository'] revision bash_it_version destination "#{Chef::Config[:file_cache_path]}/bash_it" action :sync end directory node['bash_it']['dir'] do owner node['current_user'] mode "0777" end execute "Copying bash-it's .git to #{node['bash_it']['dir']}" do command "rsync -axSH #{Chef::Config[:file_cache_path]}/bash_it/ #{node['bash_it']['dir']}" user node['current_user'] end template node['bash_it']['bashrc_path'] do source "bash_it/bashrc.erb" cookbook 'sprout-base' owner node['current_user'] mode "0777" end node['bash_it']['enabled_plugins'].each do |feature_type, features| features.each do |feature_name| sprout_base_bash_it_enable_feature "#{feature_type}/#{feature_name}" end end node['bash_it']['custom_plugins'].each do |cookbook_name, custom_plugins| custom_plugins.each do |custom_plugin| sprout_base_bash_it_custom_plugin custom_plugin do cookbook cookbook_name end end end
bash_it_version = version_string_for('bash_it') git "#{Chef::Config[:file_cache_path]}/bash_it" do repository node['bash_it']['repository'] revision bash_it_version destination "#{Chef::Config[:file_cache_path]}/bash_it" action :sync end directory node['bash_it']['dir'] do owner node['current_user'] mode "0777" end execute "Copying bash-it's .git to #{node['bash_it']['dir']}" do command "rsync -axSH #{Chef::Config[:file_cache_path]}/bash_it/ #{node['bash_it']['dir']}" user node['current_user'] end template node['bash_it']['bashrc_path'] do source "bash_it/bashrc.erb" cookbook 'sprout-base' owner node['current_user'] mode "0777" end node['bash_it']['enabled_plugins'].each do |feature_type, features| features.each do |feature_name| sprout_bash_it_enable_feature "#{feature_type}/#{feature_name}" end end node['bash_it']['custom_plugins'].each do |cookbook_name, custom_plugins| custom_plugins.each do |custom_plugin| sprout_bash_it_custom_plugin custom_plugin do cookbook cookbook_name end end end
Simplify this condition since we're only using the one ENV variable for the moment
module Neo4j module Core module TxMethods def tx_methods(*methods) methods.each do |method| tx_method = "#{method}_in_tx" send(:alias_method, tx_method, method) send(:define_method, method) do |*args, &block| session = args.last.is_a?(Neo4j::Session) ? args.pop : Neo4j::Session.current! Neo4j::Transaction.run(session.auto_commit?) { send(tx_method, *args, &block) } end end end end module Config def self.using_new_session? !ENV.key?('LEGACY_NEO4J_SESSIONS') || ENV.key?('NEW_NEO4J_SESSIONS') end end end end
module Neo4j module Core module TxMethods def tx_methods(*methods) methods.each do |method| tx_method = "#{method}_in_tx" send(:alias_method, tx_method, method) send(:define_method, method) do |*args, &block| session = args.last.is_a?(Neo4j::Session) ? args.pop : Neo4j::Session.current! Neo4j::Transaction.run(session.auto_commit?) { send(tx_method, *args, &block) } end end end end module Config def self.using_new_session? ENV.key?('NEW_NEO4J_SESSIONS') end end end end
Add created_at and updated_at to ResponseMap
class UpdateResponseMaps < ActiveRecord::Migration def self.up add_column :response_maps, :created_at, :datetime add_column :response_maps, :updated_at, :datetime end def self.down remove_column :courses, :created_at remove_column :courses, :updated_at end end
Add research area uniqueness validation
class ResearchArea < ActiveRecord::Base has_many :courses has_many :professors, :through => :professor_research_areas validates :name, :presence => true validates :code, :presence => true def to_label "#{code} - #{name}" end end
class ResearchArea < ActiveRecord::Base has_many :courses has_many :professors, :through => :professor_research_areas validates :name, :presence => true, :uniqueness => true validates :code, :presence => true, :uniqueness => true def to_label "#{code} - #{name}" end end
Update bundler requirement for new version
# -*- encoding: utf-8 -*- $:.push File.expand_path('../lib', __FILE__) require 'rolify/version' Gem::Specification.new do |s| s.name = 'rolify' s.summary = %q{Roles library with resource scoping} s.description = %q{Very simple Roles library without any authorization enforcement supporting scope on resource objects (instance or class). Supports ActiveRecord and Mongoid ORMs.} s.version = Rolify::VERSION s.platform = Gem::Platform::RUBY s.homepage = 'https://github.com/RolifyCommunity/rolify' s.rubyforge_project = s.name s.license = 'MIT' s.authors = ['Florent Monbillard'] s.email = ['f.monbillard@gmail.com'] s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- spec/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ['lib'] s.add_development_dependency 'ammeter', '~> 1.1.2' # Spec generator s.add_development_dependency 'bundler', '~> 1.7.12' # packaging feature s.add_development_dependency 'rake', '~> 10.4.2' # Tasks manager s.add_development_dependency 'rspec-rails', '2.99.0' end
# -*- encoding: utf-8 -*- $:.push File.expand_path('../lib', __FILE__) require 'rolify/version' Gem::Specification.new do |s| s.name = 'rolify' s.summary = %q{Roles library with resource scoping} s.description = %q{Very simple Roles library without any authorization enforcement supporting scope on resource objects (instance or class). Supports ActiveRecord and Mongoid ORMs.} s.version = Rolify::VERSION s.platform = Gem::Platform::RUBY s.homepage = 'https://github.com/RolifyCommunity/rolify' s.rubyforge_project = s.name s.license = 'MIT' s.authors = ['Florent Monbillard'] s.email = ['f.monbillard@gmail.com'] s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- spec/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ['lib'] s.add_development_dependency 'ammeter', '~> 1.1.2' # Spec generator s.add_development_dependency 'bundler', '>= 1.7.12' # packaging feature s.add_development_dependency 'rake', '~> 10.4.2' # Tasks manager s.add_development_dependency 'rspec-rails', '2.99.0' end
Remove the config as it is in the wrong place
# Technique caged from http://stackoverflow.com/questions/4460800/how-to-monkey-patch-code-that-gets-auto-loaded-in-rails Rails.configuration.to_prepare do Asset.class_eval do include TransamSignAsset set_rgeo_factory_for_column(:geometry, RGeo::Geographic.spherical_factory(:srid => 4326)) end end
# Technique caged from http://stackoverflow.com/questions/4460800/how-to-monkey-patch-code-that-gets-auto-loaded-in-rails Rails.configuration.to_prepare do Asset.class_eval do include TransamSignAsset end end
Use MiniTest::Unit::TestCase instead of Minitest::Test
# Activate the gem you are reporting the issue against. gem 'activerecord', '4.0.0' require 'active_record' require 'minitest/autorun' require 'logger' # This connection will do for database-independent bug reports. ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Schema.define do create_table :posts do |t| end create_table :comments do |t| t.integer :post_id end end class Post < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base belongs_to :post end class BugTest < Minitest::Test def test_association_stuff post = Post.create! post.comments << Comment.create! assert_equal 1, post.comments.count assert_equal 1, Comment.count assert_equal post.id, Comment.first.post.id end end
# Activate the gem you are reporting the issue against. gem 'activerecord', '4.0.0' require 'active_record' require 'minitest/autorun' require 'logger' # This connection will do for database-independent bug reports. ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Schema.define do create_table :posts do |t| end create_table :comments do |t| t.integer :post_id end end class Post < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base belongs_to :post end class BugTest < MiniTest::Unit::TestCase def test_association_stuff post = Post.create! post.comments << Comment.create! assert_equal 1, post.comments.count assert_equal 1, Comment.count assert_equal post.id, Comment.first.post.id end end
Build system: use new SmartFileTask interface in MustacheTask
# encoding: UTF-8 require 'rake/smart_file_task' require 'mustache' module Rake # Rake task to generate files from Mustache templates using a CLI-like approach # (but without actually using the broken mess the CLI is as of 0.99.5). class MustacheTask < SmartFileTask attr_accessor :data # restrict `actions` access to r/o protected :action= def initialize(target, template_file: nil, data: nil, **kwargs, &block) @target = target @template = template_file @data = data action = ->(*_){ puts "Rendering Mustache template '#{template.pathmap('%f')}' to '#{@target.pathmap('%f')}'..." Mustache.template_file = template File.write(@target, Mustache.render(@data.respond_to?(:call) ? @data.call(self) : @data)) } super(target, template, action, **kwargs, &block) end def template @template ||= "#{@target}.mustache" end def template=(template_file) @base = @base.reject {|e| e == @template} unless @template.nil? @template = template_file @base = @base.push(@template) end end end
# encoding: UTF-8 require 'rake/smart_file_task' require 'mustache' module Rake # Rake task to generate files from Mustache templates using a CLI-like approach # (but without actually using the broken mess the CLI is as of 0.99.5). class MustacheTask < SmartFileTask attr_accessor :data protected :on_run # set by MustacheTask def initialize(target, template_file: nil, data: nil, &block) @target = target self.template = template_file self.on_run do puts "Rendering Mustache template '#{self.template.pathmap('%f')}' to '#{self.target.pathmap('%f')}'..." Mustache.template_file = self.template File.write(self.target, Mustache.render(self.data.respond_to?(:call) ? self.data.call(self) : self.data)) end super(target, template, &block) end def template @template ||= "#{@target}.mustache" end def template=(template_file) @base = @base.reject {|e| e == @template} unless @template.nil? @template = template_file @base = @base.push(@template) end end end
Add a ContainerOrchestrator class for communicating with the OpenShift API
class ContainerOrchestrator TOKEN_FILE = "/run/secrets/kubernetes.io/serviceaccount/token".freeze def scale(deployment_config_name, replicas) connection.patch_deployment_config(deployment_config_name, { :spec => { :replicas => replicas } }, ENV["MY_POD_NAMESPACE"]) end private def connection require 'kubeclient' @connection ||= Kubeclient::Client.new( manager_uri, :auth_options => { :bearer_token_file => TOKEN_FILE }, :ssl_options => { :verify_ssl => OpenSSL::SSL::VERIFY_NONE } ) end def manager_uri URI::HTTPS.build( :host => ENV["KUBERNETES_SERVICE_HOST"], :port => ENV["KUBERNETES_SERVICE_PORT"], :path => "/oapi" ) end end
Update Node.js documentation (6.7.0, 4.6.0)
module Docs class Node < UrlScraper self.name = 'Node.js' self.slug = 'node' self.type = 'node' self.links = { home: 'https://nodejs.org/', code: 'https://github.com/nodejs/node' } html_filters.push 'node/clean_html', 'node/entries', 'title' options[:title] = false options[:root_title] = 'Node.js' options[:container] = '#apicontent' options[:skip] = %w(index.html all.html documentation.html synopsis.html) options[:attribution] = <<-HTML &copy; Joyent, Inc. and other Node contributors<br> Licensed under the MIT License.<br> Node.js is a trademark of Joyent, Inc. and is used with its permission.<br> We are not endorsed by or affiliated with Joyent. HTML version do self.release = '6.6.0' self.base_url = 'https://nodejs.org/api/' end version '4 LTS' do self.release = '4.5.0' self.base_url = "https://nodejs.org/dist/v#{release}/docs/api/" end end end
module Docs class Node < UrlScraper self.name = 'Node.js' self.slug = 'node' self.type = 'node' self.links = { home: 'https://nodejs.org/', code: 'https://github.com/nodejs/node' } html_filters.push 'node/clean_html', 'node/entries', 'title' options[:title] = false options[:root_title] = 'Node.js' options[:container] = '#apicontent' options[:skip] = %w(index.html all.html documentation.html synopsis.html) options[:attribution] = <<-HTML &copy; Joyent, Inc. and other Node contributors<br> Licensed under the MIT License.<br> Node.js is a trademark of Joyent, Inc. and is used with its permission.<br> We are not endorsed by or affiliated with Joyent. HTML version do self.release = '6.7.0' self.base_url = 'https://nodejs.org/dist/latest-v6.x/docs/api/' end version '4 LTS' do self.release = '4.6.0' self.base_url = 'https://nodejs.org/dist/latest-v4.x/docs/api/' end end end
Use ridley.search instead of ridley.<thing>.all
## # Class: Cleaver::Model::Cluster # require "ridley" require "cleaver/model/entity" module Cleaver module Model ## # Cluster Entity ## class Cluster < Cleaver::Model::Entity attribute :name attribute :server_url attribute :ssl_verify attribute :admin_client attribute :admin_client_key attribute :validation_client attribute :validation_client_key def initialize(name) @name = name end def client @client ||= Ridley.new( :server_url => server_url, :ssl => { :verify => ssl_verify }, :client_name => admin_client, :client_key => admin_client_key ) end def nodes(select = nil) if select.nil? || select.empty? ## Fetch all nodes in the cluster client.node.all.map { |node| node.reload } else ## Fetch specific nodes select.map { |node| client.node.find(node) }.select { |node| !node.nil? } end end export :name, :server_url, :admin_client, :admin_client_key, :validation_client, :validation_client_key end end end
## # Class: Cleaver::Model::Cluster # require "ridley" require "cleaver/model/entity" module Cleaver module Model ## # Cluster Entity ## class Cluster < Cleaver::Model::Entity attribute :name attribute :server_url attribute :ssl_verify attribute :admin_client attribute :admin_client_key attribute :validation_client attribute :validation_client_key def initialize(name) @name = name end def client @client ||= Ridley.new( :server_url => server_url, :ssl => { :verify => ssl_verify }, :client_name => admin_client, :client_key => admin_client_key ) end def nodes(select = nil) query = select.nil? || select.empty? ? "*:*" : select.map { |s| "name:#{ s }"}.join(" ") client.search(:node, query) end export :name, :server_url, :admin_client, :admin_client_key, :validation_client, :validation_client_key end end end
Refactor expression specs to more clearly represent the wrapped atom
require 'spec_helper' describe Calyx::Production::Expression do let(:production) do double(:production) end it 'evaluates a value' do allow(production).to receive(:evaluate).and_return([:atom, 'hello']) rule = Calyx::Production::Expression.new(production, []) expect(rule.evaluate).to eq([:expression, 'hello']) end it 'evaluates a value with modifier' do allow(production).to receive(:evaluate).and_return([:atom, 'hello']) rule = Calyx::Production::Expression.new(production, ['upcase']) expect(rule.evaluate).to eq([:expression, 'HELLO']) end it 'evaluates a value with modifier chain' do allow(production).to receive(:evaluate).and_return([:atom, 'hello']) rule = Calyx::Production::Expression.new(production, ['upcase', 'swapcase']) expect(rule.evaluate).to eq([:expression, 'hello']) end end
require 'spec_helper' describe Calyx::Production::Expression do let(:atom) do double(:atom) end it 'evaluates a value' do allow(atom).to receive(:evaluate).and_return([:atom, 'hello']) rule = Calyx::Production::Expression.new(atom, []) expect(rule.evaluate).to eq([:expression, 'hello']) end it 'evaluates a value with modifier' do allow(atom).to receive(:evaluate).and_return([:atom, 'hello']) rule = Calyx::Production::Expression.new(atom, ['upcase']) expect(rule.evaluate).to eq([:expression, 'HELLO']) end it 'evaluates a value with modifier chain' do allow(atom).to receive(:evaluate).and_return([:atom, 'hello']) rule = Calyx::Production::Expression.new(atom, ['upcase', 'swapcase']) expect(rule.evaluate).to eq([:expression, 'hello']) end end
Use KriKri as a development dependency
$LOAD_PATH.push File.expand_path('../lib', __FILE__) require 'krikri/spec/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = 'krikri-spec' s.version = Krikri::Spec::VERSION s.authors = ['Audrey Altman', 'Mark Breedlove', 'Tom Johnson', 'Mark Matienzo', 'Scott Williams'] s.email = ['tech@dp.la'] s.homepage = 'http://github.com/dpla/krikri-spec' s.summary = "Shared tests for Krikri's metadata aggregation, " \ 'enhancement, and quality control functionality.' s.description = 'Sharable test suite components for apps based on ' \ 'the Krikri engine.' s.license = 'MIT' s.files = Dir['lib/**/*', 'README.md'] s.test_files = Dir['spec/**/*'] s.add_dependency 'krikri' s.add_dependency 'rspec', '~> 3.3' s.add_development_dependency 'yard' end
$LOAD_PATH.push File.expand_path('../lib', __FILE__) require 'krikri/spec/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = 'krikri-spec' s.version = Krikri::Spec::VERSION s.authors = ['Audrey Altman', 'Mark Breedlove', 'Tom Johnson', 'Mark Matienzo', 'Scott Williams'] s.email = ['tech@dp.la'] s.homepage = 'http://github.com/dpla/krikri-spec' s.summary = "Shared tests for Krikri's metadata aggregation, " \ 'enhancement, and quality control functionality.' s.description = 'Sharable test suite components for apps based on ' \ 'the Krikri engine.' s.license = 'MIT' s.files = Dir['lib/**/*', 'README.md'] s.test_files = Dir['spec/**/*'] s.add_dependency 'rspec', '~> 3.3' s.add_development_dependency 'krikri' s.add_development_dependency 'yard' end
Fix tests to work in Rails 3.2
describe 'comable/admin/themes/index' do helper Comable::ApplicationHelper let!(:themes) { create_list(:theme, 2) } before { assign(:themes, Comable::Theme.all) } it 'renders a list of themes' do render expect(rendered).to include(*themes.map(&:name)) end end
describe 'comable/admin/themes/index' do helper Comable::ApplicationHelper let!(:themes) { create_list(:theme, 2) } before { assign(:themes, (Rails::VERSION::MAJOR == 3) ? Comable::Theme.scoped : Comable::Theme.all) } it 'renders a list of themes' do render expect(rendered).to include(*themes.map(&:name)) end end
Fix `Workflow`s access to `command_service`
require_relative 'helpers/self_applier' module Sequent module Core class Workflow include Helpers::SelfApplier def execute_commands(*commands) Sequent.configuration.instance.command_service.execute_commands(*commands) end end end end
require_relative 'helpers/self_applier' module Sequent module Core class Workflow include Helpers::SelfApplier def execute_commands(*commands) Sequent.configuration.command_service.execute_commands(*commands) end end end end
Fix invalid html in comments list.
module CommentsHelper def comments_list_for(resource) haml_tag 'ol.unstyled#comments-list' do haml_concat(render(resource.comments)) if resource.comments.empty? haml_tag 'i.muted', 'No Comments' end end end end
module CommentsHelper def comments_list_for(resource) haml_tag 'ol.unstyled#comments-list' do haml_concat(render(resource.comments)) if resource.comments.empty? haml_tag 'li' do haml_tag 'i.muted', 'No Comments' end end end end end
Refactor setting teams in controller
module Oversight module Concerns::Controllers::TeamsController extend ActiveSupport::Concern included { before_action :set_user } def index @teams = if @user @user.teams else Oversight::Team.all end end def show @team = if @user @user.teams.find params[:id] else Oversight::Team.find params[:id] end end private def set_user @user = Oversight::User.find params[:user_id] if params[:user_id] end end end
module Oversight module Concerns::Controllers::TeamsController extend ActiveSupport::Concern included do before_action :set_user before_action :set_teams, only: :index before_action :set_team, only: [ :show, :edit, :update ] end def index end def show end private def set_user @user = Oversight::User.find params[:user_id] if params[:user_id] end def set_teams @teams = if @user @user.teams else Oversight::Team.all end end def set_team @team = if @user @user.teams.find params[:id] else Oversight::Team.find params[:id] end end end end
Comment out SubnetTopologyService from SubnetTopologyController
class SubnetTopologyController < TopologyController @layout = "subnet_topology" @service_class = SubnetTopologyService end
class SubnetTopologyController < TopologyController @layout = "subnet_topology" # @service_class = SubnetTopologyService end
Add parser for cli arguments
require 'rubygems' require 'mixlib/cli' class CliParser include Mixlib::CLI option :output, :short => "-o OUTPUT", :long => "--output OUTPUT", :description => "Name of the file to write the converted markdown into" option :preview, :short => "-p", :long => "--preview", :description => "Displays the output markdown in a browser", :boolean => true def run(argv=ARGV) parse_options(argv) end end
Remove the NavBar builder from coverage metrics
class NavbarTabBuilder < TabsOnRails::Tabs::Builder def open_tabs(options = {}) options[:class] ||= "nav navbar-nav" @context.tag("ul", options, open = true) end def close_tabs(options = {}) "</ul>".html_safe end def tab_for(tab, name, options, item_options = {}) li_options = {} if current_tab?(tab) li_options[:class] = "active" end @context.content_tag(:li, li_options) do @context.link_to(name, options, item_options) end end end
class NavbarTabBuilder < TabsOnRails::Tabs::Builder #:nocov: def open_tabs(options = {}) options[:class] ||= "nav navbar-nav" @context.tag("ul", options, open = true) end def close_tabs(options = {}) "</ul>".html_safe end def tab_for(tab, name, options, item_options = {}) li_options = {} if current_tab?(tab) li_options[:class] = "active" end @context.content_tag(:li, li_options) do @context.link_to(name, options, item_options) end end #:nocov: end
Remove logger from windows hostname cap
require "log4r" module VagrantPlugins module GuestWindows module Cap module ChangeHostName def self.change_host_name(machine, name) change_host_name_and_wait(machine, name, machine.config.vm.graceful_halt_timeout) end def self.change_host_name_and_wait(machine, name, sleep_timeout) # If the configured name matches the current name, then bail # We cannot use %ComputerName% because it truncates at 15 chars return if machine.communicate.test("if ([System.Net.Dns]::GetHostName() -eq '#{name}') { exit 0 } exit 1") @logger = Log4r::Logger.new("vagrant::windows::change_host_name") # Rename and reboot host if rename succeeded script = <<-EOH $computer = Get-WmiObject -Class Win32_ComputerSystem $retval = $computer.rename("#{name}").returnvalue exit $retval EOH machine.communicate.execute( script, error_class: Errors::RenameComputerFailed, error_key: :rename_computer_failed) machine.guest.capability(:reboot) end end end end end
require "log4r" module VagrantPlugins module GuestWindows module Cap module ChangeHostName def self.change_host_name(machine, name) change_host_name_and_wait(machine, name, machine.config.vm.graceful_halt_timeout) end def self.change_host_name_and_wait(machine, name, sleep_timeout) # If the configured name matches the current name, then bail # We cannot use %ComputerName% because it truncates at 15 chars return if machine.communicate.test("if ([System.Net.Dns]::GetHostName() -eq '#{name}') { exit 0 } exit 1") # Rename and reboot host if rename succeeded script = <<-EOH $computer = Get-WmiObject -Class Win32_ComputerSystem $retval = $computer.rename("#{name}").returnvalue exit $retval EOH machine.communicate.execute( script, error_class: Errors::RenameComputerFailed, error_key: :rename_computer_failed) machine.guest.capability(:reboot) end end end end end
Add case for progress event
# encoding: utf-8 RSpec.describe TTY::ProgressBar, 'events' do let(:output) { StringIO.new('', 'w+') } it "emits :done event" do events = [] bar = TTY::ProgressBar.new("[:bar]", output: output, total: 5) bar.on(:done) { events << :done } bar.finish expect(events).to eq([:done]) end it "emits :stopped event" do events = [] bar = TTY::ProgressBar.new("[:bar]", output: output, total: 5) bar.on(:stopped) { events << :stopped } bar.stop expect(events).to eq([:stopped]) end end
# encoding: utf-8 RSpec.describe TTY::ProgressBar, 'events' do let(:output) { StringIO.new('', 'w+') } it "emits :progress event when advancing" do events = [] bar = TTY::ProgressBar.new("[:bar]", output: output, total: 5) bar.on(:progress) { events << :progress } bar.advance expect(events).to eq([:progress]) end it "emits :done event when finished" do events = [] bar = TTY::ProgressBar.new("[:bar]", output: output, total: 5) bar.on(:done) { events << :done } bar.finish expect(events).to eq([:done]) end it "emits :stopped event" do events = [] bar = TTY::ProgressBar.new("[:bar]", output: output, total: 5) bar.on(:stopped) { events << :stopped } bar.stop expect(events).to eq([:stopped]) end end
Remove Unnecessary disabling of Metrics/AbcSize
module Users module OrderManipulator extend ActiveSupport::Concern def can_create_order_at?(organization) super_admin? || member_at?(organization) end def create_order(params) # rubocop:disable Metrics/AbcSize transaction do organization = Organization.find(params[:order][:organization_id]) raise PermissionError unless can_create_order_at?(organization) order = Order.new(organization: organization, user: self, order_date: Time.zone.now, status: :select_ship_to, ship_to_name: name) OrderDetailsUpdater.new(order, params).update order.save! order end end def update_order(params) # rubocop:disable Metrics/AbcSize transaction do order = Order.find params[:id] OrderDetailsUpdater.new(order, params).update order.add_shipments(params) if params[:order][:shipments].present? order.ship_to_address = params[:order][:ship_to_address] if params[:order][:ship_to_address].present? order.update_status(params[:order][:status]) order.save! order end end end end
module Users module OrderManipulator extend ActiveSupport::Concern def can_create_order_at?(organization) super_admin? || member_at?(organization) end def create_order(params) transaction do organization = Organization.find(params[:order][:organization_id]) raise PermissionError unless can_create_order_at?(organization) order = Order.new(organization: organization, user: self, order_date: Time.zone.now, status: :select_ship_to, ship_to_name: name) OrderDetailsUpdater.new(order, params).update order.save! order end end def update_order(params) # rubocop:disable Metrics/AbcSize transaction do order = Order.find params[:id] OrderDetailsUpdater.new(order, params).update order.add_shipments(params) if params[:order][:shipments].present? order.ship_to_address = params[:order][:ship_to_address] if params[:order][:ship_to_address].present? order.update_status(params[:order][:status]) order.save! order end end end end
Tackle gzip error for when using Faraday >= 0.9.2
require "google/api_client" require "google_apis/core_ext" require "google_apis/connection" require "google_apis/api" require "google_apis/version" module GoogleApis class Error < StandardError; end def self.connect(options) @config = options.symbolize_keys @connection = Connection.new config end def self.config @config || {} end def self.connection @connection end end Faraday.default_adapter = :httpclient
require "google/api_client" require "google_apis/core_ext" require "google_apis/connection" require "google_apis/api" require "google_apis/version" module GoogleApis class Error < StandardError; end def self.connect(options) @config = options.symbolize_keys @connection = Connection.new config end def self.config @config || {} end def self.connection @connection end end # Use httpclient to avoid broken pipe errors with large uploads Faraday.default_adapter = :httpclient # Only add the following statement if using Faraday >= 0.9.2 # Override gzip middleware with no-op for httpclient if (Faraday::VERSION.split(".").collect(&:to_i) <=> [0, 9, 2]) > -1 Faraday::Response.register_middleware :gzip => Faraday::Response::Middleware end
Update nfs client test for redhat
require_relative "../../../../base" describe "VagrantPlugins::GuestRedHat::Cap:NFSClient" do let(:caps) do VagrantPlugins::GuestRedHat::Plugin .components .guest_capabilities[:redhat] end let(:machine) { double("machine") } let(:comm) { VagrantTests::DummyCommunicator::Communicator.new(machine) } before do allow(machine).to receive(:communicate).and_return(comm) end after do comm.verify_expectations! end describe ".nfs_client_install" do let(:cap) { caps.get(:nfs_client_install) } it "installs nfs client" do cap.nfs_client_install(machine) expect(comm.received_commands[0]).to match(/install nfs-utils/) expect(comm.received_commands[0]).to match(/\/bin\/systemctl restart rpcbind nfs/) end end end
require_relative "../../../../base" describe "VagrantPlugins::GuestRedHat::Cap:NFSClient" do let(:caps) do VagrantPlugins::GuestRedHat::Plugin .components .guest_capabilities[:redhat] end let(:machine) { double("machine") } let(:comm) { VagrantTests::DummyCommunicator::Communicator.new(machine) } before do allow(machine).to receive(:communicate).and_return(comm) end after do comm.verify_expectations! end describe ".nfs_client_install" do let(:cap) { caps.get(:nfs_client_install) } it "installs nfs client" do cap.nfs_client_install(machine) expect(comm.received_commands[0]).to match(/install nfs-utils/) expect(comm.received_commands[0]).to match(/\/bin\/systemctl restart rpcbind nfs-server/) end end end
Add tests for organizations commands.
# encoding: utf-8 require 'spec_helper' describe GithubCLI::Commands::Organizations do let(:format) { {'format' => 'table'} } let(:user) { 'peter-murach' } let(:org) { 'github' } let(:api_class) { GithubCLI::Organization } it "invokes org:list" do api_class.should_receive(:list).with({}, format) subject.invoke "org:list", [] end it "invokes org:list --user" do api_class.should_receive(:list).with({'user' => user}, format) subject.invoke "org:list", [], {:user => user} end it "invokes org:get" do api_class.should_receive(:get).with(org, {}, format) subject.invoke "org:get", [org] end it "invokes org:edit" do api_class.should_receive(:edit).with(org, {'name' => 'new'}, format) subject.invoke "org:edit", [org], {'name' => 'new'} end end
Install libcurl4-openssl-dev as part of networking_basic
# # Cookbook Name:: debian_basic # Recipe:: default # # Copyright 2010, fredz # # All rights reserved - Do Not Redistribute # packages = [ 'lsof', 'iptables', 'jwhois', 'whois', 'curl', 'wget', 'rsync', 'jnettop', 'nmap', 'traceroute', 'ethtool', 'iproute', 'iputils-ping', 'netcat-openbsd', 'tcpdump', 'elinks', 'lynx', 'bind9-host' ] case node[:platform] when "debian", "ubuntu" packages.each do |pkg| package pkg do action :install end end end
# # Cookbook Name:: debian_basic # Recipe:: default # # Copyright 2010, fredz # # All rights reserved - Do Not Redistribute # packages = [ 'lsof', 'iptables', 'jwhois', 'whois', 'curl', 'wget', 'rsync', 'jnettop', 'nmap', 'traceroute', 'ethtool', 'iproute', 'iputils-ping', 'netcat-openbsd', 'tcpdump', 'elinks', 'lynx', 'bind9-host', "libcurl4-openssl-dev" ] case node[:platform] when "debian", "ubuntu" packages.each do |pkg| package pkg do action :install end end end
Set poltergeist as default javascript driver
require 'simplecov' SimpleCov.start 'rails' ENV['RAILS_ENV'] = 'test' require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' require 'minitest/rails' require 'minitest/rails/capybara' require 'minitest/focus' require 'minitest/colorize' require 'webmock/minitest' require 'database_cleaner' module Minitest::Expectations infect_an_assertion :assert_redirected_to, :must_redirect_to infect_an_assertion :assert_template, :must_render_template infect_an_assertion :assert_response, :must_respond_with end Dir[Rails.root.join('test/support/**/*.rb')].each{ |file| require file } class ActiveSupport::TestCase fixtures :all end class Minitest::Unit::TestCase class << self alias_method :context, :describe end end Capybara.javascript_driver = :poltergeist WebMock.disable_net_connect!(allow_localhost: true)
require 'simplecov' SimpleCov.start 'rails' ENV['RAILS_ENV'] = 'test' require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' require 'minitest/rails' require 'minitest/rails/capybara' require 'capybara/poltergeist' require 'minitest/focus' require 'minitest/colorize' require 'webmock/minitest' require 'database_cleaner' module Minitest::Expectations infect_an_assertion :assert_redirected_to, :must_redirect_to infect_an_assertion :assert_template, :must_render_template infect_an_assertion :assert_response, :must_respond_with end Dir[Rails.root.join('test/support/**/*.rb')].each{ |file| require file } class ActiveSupport::TestCase fixtures :all end class Minitest::Unit::TestCase class << self alias_method :context, :describe end end Capybara.javascript_driver = :poltergeist Capybara.default_driver = :poltergeist WebMock.disable_net_connect!(allow_localhost: true)
Upgrade Slack Beta to 1.00 (2352)
class SlackBeta < Cask version '0.69 (2350)' sha256 '7a6be7418e27970b38f20c8e2516386e346e7b731ee814d15f5a40794b440cdd' url 'https://rink.hockeyapp.net/api/2/apps/06bd6493684f65a3b8f47aca92c9006e/app_versions/14?format=zip&avtoken=991dc9c0a3318d490712fb26e821ff2ab0a5fe24' homepage 'https://slack.com/' license :closed app 'Slack.app' caveats do puts 'Initial beta version with multiple team support' os_version_only('10.6', '10.7', '10.8', '10.9', '10.10') end end
class SlackBeta < Cask version '1.00 (2352)' sha256 '21e079794bbbc67b5cbd7b2edd259559440b15d721f72d365ba19f3c7bf9ee40' url 'https://rink.hockeyapp.net/api/2/apps/06bd6493684f65a3b8f47aca92c9006e/app_versions/16?format=zip&avtoken=a32358a50d1ab00f818e7533d60cfa68c8fd6b64' homepage 'https://slack.com/' license :closed app 'Slack.app' caveats do puts 'Initial beta version with multiple team support' os_version_only('10.6', '10.7', '10.8', '10.9', '10.10') end end
Use .capture3 not .popen3 for external parsers
require "open3" require "timeout" module CC module Engine module Analyzers class CommandLineRunner DEFAULT_TIMEOUT = 300 def initialize(command, timeout = DEFAULT_TIMEOUT) @command = command @timeout = timeout end def run(input) Timeout.timeout(timeout) do Open3.popen3 command, "r+" do |stdin, stdout, stderr, wait_thr| stdin.puts input stdin.close exit_code = wait_thr.value output = stdout.gets stdout.close err_output = stderr.gets stderr.close if 0 == exit_code yield output else raise ::CC::Engine::Analyzers::ParserError, "Python parser exited with code #{exit_code}:\n#{err_output}" end end end end private attr_reader :command, :timeout end end end end
require "open3" require "timeout" module CC module Engine module Analyzers class CommandLineRunner DEFAULT_TIMEOUT = 300 def initialize(command, timeout = DEFAULT_TIMEOUT) @command = command @timeout = timeout end def run(input) Timeout.timeout(timeout) do out, err, status = Open3.capture3(command, stdin_data: input) if status.success? yield out else raise ::CC::Engine::Analyzers::ParserError, "`#{command}` exited with code #{status.exitstatus}:\n#{err}" end end end private attr_reader :command, :timeout end end end end
Revert "Disable plugin test for Travis, need investigation"
require 'serverspec' if ENV['TRAVIS'] set :backend, :exec end describe 'vagrant Ansible role' do # Declare variables executable = '' packages = Array[] if ['debian', 'ubuntu'].include?(os[:family]) executable = '/usr/bin/vagrant' packages = Array[ 'vagrant' ] end it 'install role packages' do packages.each do |pkg_name| expect(package(pkg_name)).to be_installed end end describe file(executable) do it { should exist } it { should be_mode 755 } end if not ENV['TRAVIS'] describe command('vagrant plugin list') do its(:stdout) { should match /.*vagrant-serverspec.*/m should match /.*vagrant-triggers.*/m } end end end
require 'serverspec' if ENV['TRAVIS'] set :backend, :exec end describe 'vagrant Ansible role' do # Declare variables executable = '' packages = Array[] if ['debian', 'ubuntu'].include?(os[:family]) executable = '/usr/bin/vagrant' packages = Array[ 'vagrant' ] end it 'install role packages' do packages.each do |pkg_name| expect(package(pkg_name)).to be_installed end end describe file(executable) do it { should exist } it { should be_mode 755 } end describe command('vagrant plugin list') do its(:stdout) { should match /.*vagrant-serverspec.*/m should match /.*vagrant-triggers.*/m } end end
Add integration test for event filtering within student school year modeling
require 'rails_helper' RSpec.describe StudentSchoolYearEvents, type: :model do let(:student) { FactoryGirl.create(:student) } let(:events) { [ Absence.create!(student: student, occurred_at: DateTime.new(2016, 8, 15)), Absence.create!(student: student, occurred_at: DateTime.new(2016, 8, 20)), Absence.create!(student: student, occurred_at: DateTime.new(2016, 8, 25)), ] } subject { StudentSchoolYearEvents.new(name: '2016-2017', events: events) } describe '#filtered_absences' do let(:filter_from_date) { DateTime.new(2016, 8, 1) } let(:filter_to_date) { DateTime.new(2016, 8, 22) } let(:filtered) { subject.filtered_absences(filter_from_date, filter_to_date) } it 'filters absences correctly' do expect(filtered.count).to eq 2 end end end
Revert "rails logging added for workers debugging"
# Load the Rails application. require File.expand_path('../application', __FILE__) # Initialize the Rails application. Rails.application.initialize! Rails.logger = Logger.new(cwalog)
# Load the Rails application. require File.expand_path('../application', __FILE__) # Initialize the Rails application. Rails.application.initialize!
Remove user_registration_forms.token value from Slack notification
module Admin class UserRegistrationFormsController < AdminController before_action -> { require_scope('write:user_registration_forms') } permits :active_days def index @user_registration_forms = UserRegistrationForm.includes(admin: { user: { member: :avatar } }).all.reverse_order end def new @user_registration_form = current_user.admin.user_registration_forms.new end def create(user_registration_form) @user_registration_form = current_user.admin.user_registration_forms.new(user_registration_form) if @user_registration_form.save AdminActivityNotifyJob.perform_later( user: current_user, operation: '作成しました', object: @user_registration_form, detail: @user_registration_form.as_json, url: admin_user_registration_forms_url, ) redirect_to admin_user_registration_forms_path, notice: "ID: #{@user_registration_form.id} を作成しました" else render :new, status: :unprocessable_entity end end def destroy(id) user_registration_form = UserRegistrationForm.find(id) user_registration_form.destroy! AdminActivityNotifyJob.perform_now( user: current_user, operation: '削除しました', object: user_registration_form, detail: user_registration_form.as_json, ) redirect_to admin_user_registration_forms_path, notice: "ID: #{user_registration_form.id} を削除しました" end end end
module Admin class UserRegistrationFormsController < AdminController before_action -> { require_scope('write:user_registration_forms') } permits :active_days def index @user_registration_forms = UserRegistrationForm.includes(admin: { user: { member: :avatar } }).all.reverse_order end def new @user_registration_form = current_user.admin.user_registration_forms.new end def create(user_registration_form) @user_registration_form = current_user.admin.user_registration_forms.new(user_registration_form) if @user_registration_form.save AdminActivityNotifyJob.perform_later( user: current_user, operation: '作成しました', object: @user_registration_form, detail: @user_registration_form.as_json(except: :token), url: admin_user_registration_forms_url, ) redirect_to admin_user_registration_forms_path, notice: "ID: #{@user_registration_form.id} を作成しました" else render :new, status: :unprocessable_entity end end def destroy(id) user_registration_form = UserRegistrationForm.find(id) user_registration_form.destroy! AdminActivityNotifyJob.perform_now( user: current_user, operation: '削除しました', object: user_registration_form, detail: user_registration_form.as_json, ) redirect_to admin_user_registration_forms_path, notice: "ID: #{user_registration_form.id} を削除しました" end end end
Remove upper bound for Rails gems
# frozen_string_literal: true $LOAD_PATH.push File.expand_path("../lib", __FILE__) require "active_resource/version" Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = "activeresource" s.version = ActiveResource::VERSION::STRING s.summary = "REST modeling framework (part of Rails)." s.description = "REST on Rails. Wrap your RESTful web app with Ruby classes and work with them like Active Record models." s.license = "MIT" s.author = "David Heinemeier Hansson" s.email = "david@loudthinking.com" s.homepage = "http://www.rubyonrails.org" s.files = Dir["MIT-LICENSE", "README.md", "lib/**/*"] s.require_path = "lib" s.required_ruby_version = ">= 2.2.2" s.add_dependency("activesupport", ">= 5.0", "< 8") s.add_dependency("activemodel", ">= 5.0", "< 8") s.add_dependency("activemodel-serializers-xml", "~> 1.0") s.add_development_dependency("rake") s.add_development_dependency("mocha", ">= 0.13.0") s.add_development_dependency("rexml") end
# frozen_string_literal: true $LOAD_PATH.push File.expand_path("../lib", __FILE__) require "active_resource/version" Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = "activeresource" s.version = ActiveResource::VERSION::STRING s.summary = "REST modeling framework (part of Rails)." s.description = "REST on Rails. Wrap your RESTful web app with Ruby classes and work with them like Active Record models." s.license = "MIT" s.author = "David Heinemeier Hansson" s.email = "david@loudthinking.com" s.homepage = "http://www.rubyonrails.org" s.files = Dir["MIT-LICENSE", "README.md", "lib/**/*"] s.require_path = "lib" s.required_ruby_version = ">= 2.2.2" s.add_dependency("activesupport", ">= 5.0") s.add_dependency("activemodel", ">= 5.0") s.add_dependency("activemodel-serializers-xml", "~> 1.0") s.add_development_dependency("rake") s.add_development_dependency("mocha", ">= 0.13.0") s.add_development_dependency("rexml") end
Add module for overriding some ANSIColor behaviour.
require 'cucumber/term/ansicolor' FORCE_COLOUR_ENV_VARS = [ 'VAGRANT_CUCUMBER_FORCE_COLOR', 'VAGRANT_CUCUMBER_FORCE_COLOUR', ] module VagrantPlugins module Cucumber module Term module ANSIColor include ::Cucumber::Term::ANSIColor force_colour = false FORCE_COLOUR_ENV_VARS.each { |k| if ENV.has_key?(k) force_colour = true break end } if force_colour ::Cucumber::Term::ANSIColor.coloring = true end def self.coloring? if force_colour true else @coloring end end def self.coloring=(val) if force_color @coloring = true else @coloring = val end end end end end end
Use jalalidate v0.3.3 and bump version
# coding: utf-8 Gem::Specification.new do |spec| spec.name = "jekyll-jalali" spec.version = "0.1.0" spec.authors = ["Mehdi Sadeghi"] spec.email = ["mehdi@mehdix.org"] spec.summary = %q{Jalali date plugin for Jekyll.} spec.homepage = "https://github.com/mehdisadeghi/jekyll-jalali" spec.license = "MIT" spec.files = ["lib/jekyll-jalali.rb"] spec.add_runtime_dependency "jalalidate", "~> 0.3" spec.add_development_dependency "bundler", "~> 1.12" spec.add_development_dependency "rake", "~> 10.0" end
# coding: utf-8 Gem::Specification.new do |spec| spec.name = "jekyll-jalali" spec.version = "0.1.1" spec.authors = ["Mehdi Sadeghi"] spec.email = ["mehdi@mehdix.org"] spec.summary = %q{Jalali date plugin for Jekyll.} spec.homepage = "https://github.com/mehdisadeghi/jekyll-jalali" spec.license = "MIT" spec.files = ["lib/jekyll-jalali.rb"] spec.add_runtime_dependency "jalalidate", "= 0.3.3" spec.add_development_dependency "bundler", "~> 1.12" spec.add_development_dependency "rake", "~> 10.0" end
Change to use the log_type
class DisclaimerInfo attr_accessor :log_id, :log_label_arr, :log_start_page_index_arr, :log_level_arr, :purl, :catalogue_arr, :title_arr, :subtitle_arr, :bycreator, :publisher, :place_publish, :year_publish_string, :genre_arr, :dc_arr, :subject_arr, :year_publisher, :shelfmark_arr, :rights_owner_arr, :parentdoc_work, :parentdoc_label, :parentdoc_type end
class DisclaimerInfo attr_accessor :log_id, :log_label_arr, :log_start_page_index_arr, :log_level_arr, :log_type_arr, :purl, :catalogue_arr, :title_arr, :subtitle_arr, :bycreator, :publisher, :place_publish, :year_publish_string, :genre_arr, :dc_arr, :subject_arr, :year_publisher, :shelfmark_arr, :rights_owner_arr, :parentdoc_work, :parentdoc_label, :parentdoc_type end
Update for Bunto 2 support
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'bunto-paginate/version' Gem::Specification.new do |spec| spec.name = "bunto-paginate" spec.version = Bunto::Paginate::VERSION spec.authors = ["Parker Moore", "Suriyaa Kudo"] spec.email = ["parkrmoore@gmail.com", "SuriyaaKudoIsc@users.noreply.github.com"] spec.summary = %q{Built-in Pagination Generator for Bunto} spec.homepage = "https://github.com/bunto/bunto-paginate" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bunto" spec.add_development_dependency "bundler", "~> 1.5" spec.add_development_dependency "rake" spec.add_development_dependency "rspec", "~> 3.0" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'bunto-paginate/version' Gem::Specification.new do |spec| spec.name = "bunto-paginate" spec.version = Bunto::Paginate::VERSION spec.authors = ["Parker Moore", "Suriyaa Kudo"] spec.email = ["parkrmoore@gmail.com", "SuriyaaKudoIsc@users.noreply.github.com"] spec.summary = %q{Built-in Pagination Generator for Bunto} spec.homepage = "https://github.com/bunto/bunto-paginate" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bunto", ">= 1.0", "< 2.0" spec.add_development_dependency "bundler", "~> 1.5" spec.add_development_dependency "rake" spec.add_development_dependency "rspec", "~> 3.0" end
Fix platform version in suse spec
require 'spec_helper' describe 'build-essential::_suse' do let(:chef_run) do ChefSpec::Runner.new(platform: 'suse', version: '11.03') .converge(described_recipe) end it 'installs the correct packages' do expect(chef_run).to install_package('autoconf') expect(chef_run).to install_package('bison') expect(chef_run).to install_package('flex') expect(chef_run).to install_package('gcc') expect(chef_run).to install_package('gcc-c++') expect(chef_run).to install_package('kernel-default-devel') expect(chef_run).to install_package('make') expect(chef_run).to install_package('m4') end end
require 'spec_helper' describe 'build-essential::_suse' do let(:chef_run) do ChefSpec::Runner.new(platform: 'suse', version: '11.3') .converge(described_recipe) end it 'installs the correct packages' do expect(chef_run).to install_package('autoconf') expect(chef_run).to install_package('bison') expect(chef_run).to install_package('flex') expect(chef_run).to install_package('gcc') expect(chef_run).to install_package('gcc-c++') expect(chef_run).to install_package('kernel-default-devel') expect(chef_run).to install_package('make') expect(chef_run).to install_package('m4') end end
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, 'image/jpg') 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) end end end end end
Handle soft deleted products when refreshing cache
Spree::Classification.class_eval do belongs_to :product, :class_name => "Spree::Product", touch: true after_save :refresh_products_cache before_destroy :dont_destroy_if_primary_taxon after_destroy :refresh_products_cache private def refresh_products_cache product.refresh_products_cache end def dont_destroy_if_primary_taxon if product.primary_taxon == taxon errors.add :base, I18n.t(:spree_classification_primary_taxon_error, taxon: taxon.name, product: product.name) return false end end end
Spree::Classification.class_eval do belongs_to :product, class_name: "Spree::Product", touch: true before_destroy :dont_destroy_if_primary_taxon after_destroy :refresh_products_cache after_save :refresh_products_cache private def refresh_products_cache Spree::Product.with_deleted.find(product_id).refresh_products_cache end def dont_destroy_if_primary_taxon if product.primary_taxon == taxon errors.add :base, I18n.t(:spree_classification_primary_taxon_error, taxon: taxon.name, product: product.name) return false end end end
Initialize without .env for Travis-CI
#------------------------------------------------------------------------- # # Copyright (c) Microsoft and contributors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------- require 'dotenv' Dotenv.load require 'minitest/autorun' require 'mocha/mini_test' require 'minitest/reporters' Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new require 'timecop' require 'logger' require 'stringio' # add to the MiniTest DSL module Kernel def need_tests_for(name) describe "##{name}" do it 'needs unit tests' do skip '' end end end end Dir['./test/support/**/*.rb'].each { |dep| require dep } # mock configuration setup require 'azure/storage' Azure::Storage.config.storage_account_name = 'mockaccount' Azure::Storage.config.storage_access_key = 'YWNjZXNzLWtleQ=='
#------------------------------------------------------------------------- # # Copyright (c) Microsoft and contributors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------- require 'dotenv' Dotenv.load ENV["AZURE_STORAGE_ACCOUNT"] = 'mockaccount' unless ENV["AZURE_STORAGE_ACCOUNT"] ENV["AZURE_STORAGE_ACCESS_KEY"] = 'YWNjZXNzLWtleQ==' unless ENV["AZURE_STORAGE_ACCESS_KEY"] require 'minitest/autorun' require 'mocha/mini_test' require 'minitest/reporters' Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new require 'timecop' require 'logger' require 'stringio' # add to the MiniTest DSL module Kernel def need_tests_for(name) describe "##{name}" do it 'needs unit tests' do skip '' end end end end Dir['./test/support/**/*.rb'].each { |dep| require dep } # mock configuration setup require 'azure/storage' Azure::Storage.config.storage_account_name = 'mockaccount' Azure::Storage.config.storage_access_key = 'YWNjZXNzLWtleQ=='
Update spec to new gem version number
require 'spec_helper' describe Oboe do it 'should return correct version string' do Oboe::Version::STRING.should == "1.4.0.1" end end
require 'spec_helper' describe Oboe do it 'should return correct version string' do Oboe::Version::STRING.should == "2.0.0" end end
Remove obsolete code in Product Advertising Endpoint
module Vacuum module Endpoint # A Product Advertising API endpoint. class ProductAdvertising < Base # A list of Product Advertising API hosts. HOSTS = { 'CA' => 'ecs.amazonaws.ca', 'CN' => 'webservices.amazon.cn', 'DE' => 'ecs.amazonaws.de', 'ES' => 'webservices.amazon.es', 'FR' => 'ecs.amazonaws.fr', 'IT' => 'webservices.amazon.it', 'JP' => 'ecs.amazonaws.jp', 'UK' => 'ecs.amazonaws.co.uk', 'US' => 'ecs.amazonaws.com' } # Returns a String Product Advertising API host. # # Raises an Argument Error if the API locale is not valid. def host HOSTS[locale] or raise ArgumentError, 'invalid locale' end # Sets the String Associate tag. # # Raises a Missing Tag error if tag is missing. def tag @tag or raise MissingTag end # Sets the String Associate tag. attr_writer :tag end end end
module Vacuum module Endpoint # A Product Advertising API endpoint. class ProductAdvertising < Base # A list of Product Advertising API hosts. HOSTS = { 'CA' => 'ecs.amazonaws.ca', 'CN' => 'webservices.amazon.cn', 'DE' => 'ecs.amazonaws.de', 'ES' => 'webservices.amazon.es', 'FR' => 'ecs.amazonaws.fr', 'IT' => 'webservices.amazon.it', 'JP' => 'ecs.amazonaws.jp', 'UK' => 'ecs.amazonaws.co.uk', 'US' => 'ecs.amazonaws.com' } # Returns a String Product Advertising API host. def host HOSTS[locale] end # Sets the String Associate tag. # # Raises a Missing Tag error if tag is missing. def tag @tag or raise MissingTag end # Sets the String Associate tag. attr_writer :tag end end end
Use page caching on ImagesController
# encoding: utf-8 class PagesCore::ImagesController < ApplicationController include DynamicImage::Controller private def model Image end end
# encoding: utf-8 class PagesCore::ImagesController < ApplicationController include DynamicImage::Controller caches_page :show, :uncropped, :original private def model Image end end
Stop caching included_modules if they are empty
module Domgen module Ruby class RubyClass < Domgen.ParentedElement(:object_type) attr_writer :classname def included_modules @included_modules ||= [] end def include_module(module_name) self.included_modules << module_name end def classname @classname || object_type.name end def qualified_name "::#{object_type.data_module.ruby.module_name}::#{classname}" end def filename fqn = qualified_name underscore(fqn[2..fqn.length]) end end class RubyModule < Domgen.ParentedElement(:data_module) attr_writer :module_name def module_name @module_name || data_module.name end end end FacetManager.define_facet(:ruby, ObjectType => Domgen::Ruby::RubyClass, DataModule => Domgen::Ruby::RubyModule ) end
module Domgen module Ruby class RubyClass < Domgen.ParentedElement(:object_type) attr_writer :classname def included_modules @included_modules || [] end def include_module(module_name) (@included_modules ||= []) << module_name end def classname @classname || object_type.name end def qualified_name "::#{object_type.data_module.ruby.module_name}::#{classname}" end def filename fqn = qualified_name underscore(fqn[2..fqn.length]) end end class RubyModule < Domgen.ParentedElement(:data_module) attr_writer :module_name def module_name @module_name || data_module.name end end end FacetManager.define_facet(:ruby, ObjectType => Domgen::Ruby::RubyClass, DataModule => Domgen::Ruby::RubyModule ) end
Add herokuapp to the description
#encoding: UTF-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'standalone_typograf/version' Gem::Specification.new do |spec| spec.name = 'standalone_typograf' spec.version = StandaloneTypograf::VERSION spec.authors = 'Alex Shilov' spec.email = 'sashapashamasha@gmail.com' spec.description = "Standalone (offline) client of the ArtLebedev's Studio Typograf service." spec.summary = 'Very Fast&Simple Typograf fot the Russian text.' spec.homepage = 'https://github.com/shlima/StandaloneTypograf' spec.license = 'MIT' spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '~> 1.3' spec.add_development_dependency 'rake' end
#encoding: UTF-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'standalone_typograf/version' Gem::Specification.new do |spec| spec.name = 'standalone_typograf' spec.version = StandaloneTypograf::VERSION spec.authors = 'Alex Shilov' spec.email = 'sashapashamasha@gmail.com' spec.description = "Standalone (offline) client of the ArtLebedev's Studio Typograf service. http://typograf.herokuapp.com" spec.summary = 'Very Fast&Simple Typograf fot the Russian text.' spec.homepage = 'https://github.com/shlima/StandaloneTypograf' spec.license = 'MIT' spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '~> 1.3' spec.add_development_dependency 'rake' end
Include favorited and created_at attributes in favorite serializer
# frozen_string_literal: true module GobiertoData class FavoriteSerializer < ActiveModel::Serializer attributes :id, :user_id, :favorited_type, :favorited_id belongs_to :user, unless: :exclude_relationships? belongs_to :favorited, polymorphic: true, unless: :exclude_relationships? def current_site Site.find(object.site.id) end def exclude_relationships? instance_options[:exclude_relationships] end end end
# frozen_string_literal: true module GobiertoData class FavoriteSerializer < ActiveModel::Serializer attributes :id, :user_id, :favorited_type, :favorited_id, :favorited, :created_at belongs_to :user, unless: :exclude_relationships? belongs_to :favorited, polymorphic: true, unless: :exclude_relationships? def current_site Site.find(object.site.id) end def exclude_relationships? instance_options[:exclude_relationships] end end end
Add read timeout to BlockchainAdapter::Base.http_request
module StraightEngine module BlockchainAdapter # An almost abstract class, providing guidance for the interfaces of # all blockchain adapters as well as supplying some useful methods. # Raised when blockchain data cannot be retrived for any reason. # We're not really intereste in the precise reason, although it is # stored in the message. class RequestError < Exception; end class Base require 'json' require 'uri' require 'open-uri' require 'yaml' class << self # Returns transaction info for the tid def fetch_transaction(tid) end # Returns all transactions for the address def fetch_transactions_for(address) end # This method is a wrapper for creating an HTTP request # to various services that ancestors of this class may use # to retrieve blockchain data. Why do we need a wrapper? # Because it respects timeouts. def http_request(url) uri = URI.parse(url) begin http = uri.read rescue OpenURI::HTTPError => e raise RequestError, YAML::dump(e) end end private # Converts transaction info received from the source into the # unified format expected by users of BlockchainAdapter instances. def straighten_transaction(transaction) end end end end end
module StraightEngine module BlockchainAdapter # An almost abstract class, providing guidance for the interfaces of # all blockchain adapters as well as supplying some useful methods. # Raised when blockchain data cannot be retrived for any reason. # We're not really intereste in the precise reason, although it is # stored in the message. class RequestError < Exception; end class Base require 'json' require 'uri' require 'open-uri' require 'yaml' class << self # Returns transaction info for the tid def fetch_transaction(tid) end # Returns all transactions for the address def fetch_transactions_for(address) end # This method is a wrapper for creating an HTTP request # to various services that ancestors of this class may use # to retrieve blockchain data. Why do we need a wrapper? # Because it respects timeouts. def http_request(url) uri = URI.parse(url) begin http = uri.read(read_timeout: 4) rescue OpenURI::HTTPError => e raise RequestError, YAML::dump(e) end end private # Converts transaction info received from the source into the # unified format expected by users of BlockchainAdapter instances. def straighten_transaction(transaction) end end end end end
Make ruby 1.9.2 tests success on my mac. Should be investigated later...
require "spec_helper" describe "daemonzier after start" do before :each do @pid_files = simple_daemonfile( :name => :test1, :pid_file =>"#{tmp_dir}/test1.pid", :on_start => "loop { sleep 1 }", :workers => 3, :poll_period => 1) daemonizer :start sleep 5 end after :each do daemonizer :stop end it "should create 3 forks" do children_count(pid(@pid_files[0])).should == 3 end describe "after one worker died" do before :each do Process.kill("KILL", children_pids(pid(@pid_files[0])).first.to_i) sleep 5 end it "should restore it" do children_count(pid(@pid_files[0])).should == 3 end end end
require "spec_helper" describe "daemonzier after start" do before :each do @pid_files = simple_daemonfile( :name => :test1, :pid_file =>"#{tmp_dir}/test1.pid", :on_start => "loop { sleep 1 }", :workers => 3, :poll_period => 1) daemonizer :start sleep 8 end after :each do daemonizer :stop end it "should create 3 forks" do children_count(pid(@pid_files[0])).should == 3 end describe "after one worker died" do before :each do Process.kill("KILL", children_pids(pid(@pid_files[0])).first.to_i) sleep 5 end it "should restore it" do children_count(pid(@pid_files[0])).should == 3 end end end
Add specs for the toplevel Complex method.
require File.dirname(__FILE__) + '/../../spec_helper' require 'complex' describe "Complex when passed [Complex, Complex]" do it "returns a new Complex number based on the two given numbers" do Complex(Complex(3, 4), Complex(5, 6)).should == Complex.new(3 - 6, 4 + 5) Complex(Complex(1.5, 2), Complex(-5, 6.3)).should == Complex.new(1.5 - 6.3, 2 - 5) end end describe "Complex when passed [Complex]" do it "returns the passed Complex number" do Complex(Complex(1, 2)).should == Complex(1, 2) Complex(Complex(-3.4, bignum_value)).should == Complex(-3.4, bignum_value) end end describe "Complex when passed [Integer, Integer]" do it "returns a new Complex number" do Complex(1, 2).should == Complex.new(1, 2) Complex(-3, -5).should == Complex.new(-3, -5) Complex(3.5, -4.5).should == Complex.new(3.5, -4.5) Complex(bignum_value, 30).should == Complex.new(bignum_value, 30) end end describe "Complex when passed [Integer]" do it "returns a new Complex number with 0 as the imaginary component" do Complex(1).eql?(Complex.new(1, 0)).should == true Complex(-3).eql?(Complex.new(-3, 0)).should == true Complex(-4.5).eql?(Complex.new(-4.5, 0)).should == true Complex(bignum_value).eql?(Complex.new(bignum_value, 0)).should == true end it "returns the passed Integer when Complex::Unify is defined" do begin Complex::Unify = true Complex(1).eql?(1).should == true Complex(-3).eql?(-3).should == true Complex(-4.5).eql?(-4.5).should == true Complex(bignum_value).eql?(bignum_value).should == true ensure Complex.send :remove_const, :Unify end end end
Add source and issues url
name 'play' maintainer 'Dennis Hoer' maintainer_email 'dennis.hoer@gmail.com' license 'MIT' description 'Installs/Configures distribution artifact as a service.' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '1.0.0' supports 'centos' supports 'redhat' supports 'ubuntu' depends 'ark', '~> 0.9'
name 'play' maintainer 'Dennis Hoer' maintainer_email 'dennis.hoer@gmail.com' license 'MIT' description 'Installs/Configures Play distribution artifact as a service.' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '1.0.0' supports 'centos' supports 'redhat' supports 'ubuntu' depends 'ark', '~> 0.9' source_url 'https://github.com/dhoer/chef-play' if respond_to?(:source_url) issues_url 'https://github.com/dhoer/chef-play/issues' if respond_to?(:issues_url)
Update .podspec file according to the new framework name
Pod::Spec.new do |s| s.name = "MKHSequenceCtrl" s.version = "1.0.3" s.summary = "Lightweight implementation of async operations sequence controller" s.homepage = "https://github.com/maximkhatskevich/MKHSequenceCtrl" s.license = { :type => "MIT", :file => "LICENSE" } s.author = { "Maxim Khatskevich" => "maxim@khatskevi.ch" } s.platform = :ios, "6.0" s.source = { :git => "https://github.com/maximkhatskevich/MKHBlockSequence.git", :tag => "#{s.version}" } s.requires_arc = true s.source_files = "Src/*.{h,m}" end
Pod::Spec.new do |s| s.name = "MKHSequence" s.version = "1.0.3" s.summary = "Lightweight implementation of async operations sequence controller" s.homepage = "https://github.com/maximkhatskevich/#{s.name}" s.license = { :type => "MIT", :file => "LICENSE" } s.author = { "Maxim Khatskevich" => "maxim@khatskevi.ch" } s.platform = :ios, "6.0" s.source = { :git => "#{s.homepage}.git", :tag => "#{s.version}" } s.source_files = "Src/*.{h,m}" s.requires_arc = true s.social_media_url = "http://www.linkedin.com/in/maximkhatskevich" end
Include scripts directory when building pathname
require "vagrant" require 'vagrant/util/platform' module VagrantPlugins module HostWindows class Host < Vagrant.plugin("2", :host) def detect?(env) Vagrant::Util::Platform.windows? end # @return [Pathname] Path to scripts directory def self.scripts_path Pathname.new(File.expand_path("..", __FILE__)) end # @return [Pathname] Path to modules directory def self.modules_path scripts_path.join("utils") end end end end
require "vagrant" require 'vagrant/util/platform' module VagrantPlugins module HostWindows class Host < Vagrant.plugin("2", :host) def detect?(env) Vagrant::Util::Platform.windows? end # @return [Pathname] Path to scripts directory def self.scripts_path Pathname.new(File.expand_path("../scripts", __FILE__)) end # @return [Pathname] Path to modules directory def self.modules_path scripts_path.join("utils") end end end end
Update HandbrakeCLI Nightly to v7031svn
cask :v1 => 'handbrakecli-nightly' do version '7010svn' sha256 '1ab548fe2c78fa8115736e0c26091283e2ab990825385012bf652ce3803322ac' url "http://download.handbrake.fr/nightly/HandBrake-#{version}-MacOSX.6_CLI_x86_64.dmg" homepage 'http://handbrake.fr' license :gpl binary 'HandBrakeCLI' depends_on :macos => '>= :snow_leopard' end
cask :v1 => 'handbrakecli-nightly' do version '7031svn' sha256 '29584bd078000dc79c95c56aa9483e7bc5d6cce048349414e4016bcea68ef76d' url "http://download.handbrake.fr/nightly/HandBrake-#{version}-MacOSX.6_CLI_x86_64.dmg" homepage 'http://handbrake.fr' license :gpl binary 'HandBrakeCLI' depends_on :macos => '>= :snow_leopard' end
Return email in reset_password api response
class API::V2::PasswordsController < API::V2::BaseController skip_before_action :require_authentication # Request to send password reset instructions to user email # POST /reset_password def reset username = user_params[:username].try(:downcase) unless user_params.blank? @user = User.find_by(username: username) # Send a failure response if no account exists with the given email unless @user.present? render(fail_response(message: "User #{username} does not exist")) and return end @user.send_reset_password_instructions render(success_response(message: "Password reset email sent to #{@user.email}.")) end protected def user_params if params[:user] params.require(:user).permit( :username ) end end end
class API::V2::PasswordsController < API::V2::BaseController skip_before_action :require_authentication # Request to send password reset instructions to user email # POST /reset_password def reset username = user_params[:username].try(:downcase) unless user_params.blank? @user = User.find_by(username: username) # Send a failure response if no account exists with the given email unless @user.present? render(fail_response(message: "User #{username} does not exist")) and return end @user.send_reset_password_instructions render(success_response(message: "Password reset email sent to #{@user.email}.", email: @user.email )) end protected def user_params if params[:user] params.require(:user).permit( :username ) end end end
Test for profiling unit tests.
#!/usr/bin/env ruby require 'test/unit' require 'ruby-prof' require 'timeout' require 'test_helper' require 'ruby-prof/profile_test_case' # -- Tests ---- class ProfileTest < Test::Unit::TestCase def test_profile sleep(2) end def teardown profile_dir = output_directory assert(File.exists?(profile_dir)) file_path = File.join(profile_dir, 'test_profile_profile_test.html') assert(File.exists?(file_path)) end end
Change from name of PA entry mail
class SongMailer < ApplicationMailer default to: '"PA" <pa@ku-unplugged.net>' def entry(song, applicant) @song = song @applicant = applicant email_with_name = %("#{applicant.name}" <#{applicant.email}>) mail reply_to: email_with_name, subject: "#{song.live_name} 曲申請「#{song.title}」" end end
class SongMailer < ApplicationMailer default to: '"PA" <pa@ku-unplugged.net>' def entry(song, applicant) @song = song @applicant = applicant email_with_name = %("#{applicant.name}" <#{applicant.email}>) from_with_name = %("#{applicant.name}" <noreply@livelog.ku-unplugged.net>) mail from: from_with_name, reply_to: email_with_name, subject: "#{song.live_name} 曲申請「#{song.title}」" end end
Fix examples/native to use $global for window reference
require 'opal' $window.addEventListener 'DOMContentLoaded', proc { css = <<-CSS body { font-family: 'Arial'; } CSS title = $document.createElement 'h1' title.className = 'main-title' title.innerHTML = 'Opal Native Example' desc = $document.createElement 'p' desc.innerHTML = "Hello world! From Opal." target = $document.getElementById 'native-example' unless target raise "'native-example' doesn't exist?" end target.appendChild title target.appendChild desc styles = $document.createElement 'style' styles.type = 'text/css' if styles.respond_to? :styleSheet styles.styleSheet.cssText = css else styles.appendChild $document.createTextNode css end $document.getElementsByTagName('head')[0].appendChild(styles) }, false
require 'opal' $global.addEventListener 'DOMContentLoaded', proc { css = <<-CSS body { font-family: 'Arial'; } h1 { color: rgb(10, 94, 232); } CSS document = $global.document title = document.createElement 'h1' title.className = 'main-title' title.innerHTML = 'Opal Native Example' desc = document.createElement 'p' desc.innerHTML = "Hello world! From Opal." target = document.getElementById 'native-example' unless target raise "'native-example' doesn't exist?" end target.appendChild title target.appendChild desc styles = document.createElement 'style' styles.type = 'text/css' if styles.respond_to? :styleSheet styles.styleSheet.cssText = css else styles.appendChild document.createTextNode css end document.getElementsByTagName('head')[0].appendChild(styles) }, false
Update gemspec with new README in markdown
# encoding: utf-8 $: << File.expand_path('../lib', __FILE__) require 'i18n/version' Gem::Specification.new do |s| s.name = "i18n" s.version = I18n::VERSION s.authors = ["Sven Fuchs", "Joshua Harvey", "Matt Aimonetti", "Stephan Soller", "Saimon Moore"] s.email = "rails-i18n@googlegroups.com" s.homepage = "http://github.com/svenfuchs/i18n" s.summary = "New wave Internationalization support for Ruby" s.description = "New wave Internationalization support for Ruby." s.license = "MIT" s.files = Dir.glob("{ci,lib,test}/**/**") + %w(README.textile MIT-LICENSE) s.platform = Gem::Platform::RUBY s.require_path = 'lib' s.rubyforge_project = '[none]' s.required_rubygems_version = '>= 1.3.5' end
# encoding: utf-8 $: << File.expand_path('../lib', __FILE__) require 'i18n/version' Gem::Specification.new do |s| s.name = "i18n" s.version = I18n::VERSION s.authors = ["Sven Fuchs", "Joshua Harvey", "Matt Aimonetti", "Stephan Soller", "Saimon Moore"] s.email = "rails-i18n@googlegroups.com" s.homepage = "http://github.com/svenfuchs/i18n" s.summary = "New wave Internationalization support for Ruby" s.description = "New wave Internationalization support for Ruby." s.license = "MIT" s.files = Dir.glob("{ci,lib,test}/**/**") + %w(README.md MIT-LICENSE) s.platform = Gem::Platform::RUBY s.require_path = 'lib' s.rubyforge_project = '[none]' s.required_rubygems_version = '>= 1.3.5' end
Add specs for firewall_rules in refresh_parser
describe ManageIQ::Providers::Amazon::NetworkManager::RefreshParser do require 'aws-sdk' let(:ems) { FactoryGirl.create(:ems_amazon_with_authentication) } let(:parser) { described_class.new(ems.network_manager, Settings.ems_refresh.ec2_network) } describe "#parse_firewall_rule" do let(:perm) { Aws::EC2::Types::IpPermission.new(rule_options) } let(:ip_protocol) { "icmp" } let(:ip_ranges) { [] } let(:ipv_6_ranges) { [] } let(:rule_options) do { :ip_protocol => ip_protocol, :ip_ranges => ip_ranges.map { |ip| Aws::EC2::Types::IpRange.new(:cidr_ip => ip) }, :ipv_6_ranges => ipv_6_ranges.map { |ip| Aws::EC2::Types::Ipv6Range.new(:cidr_ipv_6 => ip) }, :user_id_group_pairs => [] } end subject { parser.send(:parse_firewall_rule, perm, 'inbound') } context "all ip_protocols" do let(:ip_protocol) { -1 } let(:ip_ranges) { ["1.1.1.0/24"] } it { is_expected.to all(include(:host_protocol => "All")) } end context "ipv6 ranges" do let(:ipv_6_ranges) { ["2001:DB8::0/120", "2001:DB8::80/122"] } it { expect(subject.length).to eq(2) } it { expect(subject.collect { |i| i[:source_ip_range] }).to eq(ipv_6_ranges) } end context "ipv4 ranges" do let(:ip_ranges) { ["10.0.0.0/24", "10.0.1.0/24"] } it { expect(subject.length).to eq(2) } it { expect(subject.collect { |i| i[:source_ip_range] }).to eq(ip_ranges) } end end end
Read in data location from rc, load overloads into a model
require_relative "rtasklib/version" require_relative "rtasklib/models" require_relative "rtasklib/execute" require_relative "rtasklib/controller" require_relative "rtasklib/serializer" require_relative "rtasklib/taskrc" require "open3" require "pathname" module Rtasklib class TaskWarrior attr_reader :version, :rc_location, :data_location, :override, :create_new, :config include Controller DEFAULT_CONFIG = { json: { array: 'true', }, verbose: 'nothing', confirmation: 'no', dependency: { confirmation: 'no', }, } LOWEST_VERSION = Gem::Version.new('2.4.0') def initialize rc="#{Dir.home}/.taskrc", data="#{Dir.home}/.task/", override=DEFAULT_CONFIG, create_new=false @rc_location = Pathname.new(rc) @data_location = Pathname.new(data) @override = DEFAULT_CONFIG.merge(override) @config = Rtasklib::Taskrc.new(rc_location) @create_new = create_new # Check TaskWarrior version, and throw warning begin @version = get_version check_version(version) rescue warn "Couldn't find TaskWarrior's version" @version = nil end end def check_version version if version < LOWEST_VERSION warn "The current TaskWarrior version, #{version}, is untested" end end end end
require_relative "rtasklib/version" require_relative "rtasklib/models" require_relative "rtasklib/execute" require_relative "rtasklib/controller" require_relative "rtasklib/serializer" require_relative "rtasklib/taskrc" require "open3" require "pathname" module Rtasklib class TaskWarrior attr_reader :version, :rc_location, :data_location, :override, :create_new, :taskrc include Controller DEFAULT_CONFIG = { json_array: 'true', verbose: 'nothing', confirmation: 'no', dependency_confirmation: 'no' } LOWEST_VERSION = Gem::Version.new('2.4.0') def initialize rc="#{Dir.home}/.taskrc", override=DEFAULT_CONFIG, create_new=false @rc_location = Pathname.new(rc) @taskrc = Rtasklib::Taskrc.new(rc_location) @data_location = taskrc.config.data_location @override = Rtasklib::Taskrc.new(DEFAULT_CONFIG.merge(override)) @create_new = create_new # Check TaskWarrior version, and throw warning begin @version = get_version check_version(version) rescue warn "Couldn't verify TaskWarrior's version" @version = nil end end def check_version version if version < LOWEST_VERSION warn "The current TaskWarrior version, #{version}, is untested" end end end end
Return full image when uploaded
class RedactorImagesController < ApplicationController skip_before_filter :verify_authenticity_token respond_to :json def index @redactor_images = RedactorImage.limit(25) render json: @redactor_images.map { |image| { 'thumb' => image.image.url(:normal), 'image' => image.image.url } } end def create @redactor_image = RedactorImage.new(image: params[:file]) if @redactor_image.save render text: "{\"filelink\":\"#{@redactor_image.image.url(:normal)}\"}" else render json: @redactor_image.errors end end def create_from_clipboard @redactor_image = RedactorImage.new_from_clipboard(params[:data]) if @redactor_image.save render text: "{\"filelink\":\"#{@redactor_image.image.url}\"}" else render json: @redactor_image.errors end end end
class RedactorImagesController < ApplicationController skip_before_filter :verify_authenticity_token respond_to :json def index @redactor_images = RedactorImage.limit(25) render json: @redactor_images.map { |image| { 'thumb' => image.image.url(:normal), 'image' => image.image.url } } end def create @redactor_image = RedactorImage.new(image: params[:file]) if @redactor_image.save render text: "{\"filelink\":\"#{@redactor_image.image.url}\"}" else render json: @redactor_image.errors end end def create_from_clipboard @redactor_image = RedactorImage.new_from_clipboard(params[:data]) if @redactor_image.save render text: "{\"filelink\":\"#{@redactor_image.image.url}\"}" else render json: @redactor_image.errors end end end
Raise RunTimeError when top-level pages are not present
require 'rails_helper' RSpec.describe RootBrowsePagePresenter do describe "#render_for_publishing_api" do it "is valid against the schema without browse pages", :schema_test => true do rendered = RootBrowsePagePresenter.new.render_for_publishing_api expect(rendered).to be_valid_against_schema('mainstream_browse_page') end context "with top level browse pages" do let!(:top_level_page_1) { create(:mainstream_browse_page)} let!(:top_level_page_2) { create(:mainstream_browse_page)} let(:rendered) { RootBrowsePagePresenter.new.render_for_publishing_api} it "is valid against the schema" do expect(rendered).to be_valid_against_schema('mainstream_browse_page') end it "includes all the top-level browse pages" do expect(rendered[:links]["top_level_browse_pages"]).to eq([ top_level_page_1.content_id, top_level_page_2.content_id, ]) end end end end
require 'rails_helper' RSpec.describe RootBrowsePagePresenter do describe "#render_for_publishing_api" do it "raises a RunTimeError if top-level browse pages are not present" do expect { RootBrowsePagePresenter.new.render_for_publishing_api }.to raise_error(RuntimeError) end context "with top level browse pages" do let!(:top_level_page_1) { create(:mainstream_browse_page)} let!(:top_level_page_2) { create(:mainstream_browse_page)} let(:rendered) { RootBrowsePagePresenter.new.render_for_publishing_api} it "is valid against the schema" do expect(rendered).to be_valid_against_schema('mainstream_browse_page') end it "includes all the top-level browse pages" do expect(rendered[:links]["top_level_browse_pages"]).to eq([ top_level_page_1.content_id, top_level_page_2.content_id, ]) end end end end
Add methods for checking and creating connections
class Relationship < ActiveRecord::Base belongs_to :partner belongs_to :student attr_accessible :status end
class Relationship < ActiveRecord::Base belongs_to :partner belongs_to :student attr_accessible :connected, :partner_id, :student_id #Make a pending relationship between a partner and user def self.pending(partner_id, student_id) new(partner_id: partner_id, student_id: student_id, connected: false) end def self.pending!(partner_id, student_id) pending(partner_id, student_id).save end #Make a connected relationship between a partner and user def self.connected(partner_id, student_id) new(partner_id: partner_id, student_id: student_id, connected: true) end def self.connected!(partner_id, student_id) connected(partner_id, student_id).save end def pending? self.connected? ? false : true end end
Remove header instead of setting to invalid value
# This mixin provides support for implementing the # embedded mode - as opposed to the standalone mode -in which # the mumuki pages # # * are displayed used a simplified layout, called `embedded.html.erb` # * are served using `X-Frame-Options` that allow them to be used within # an iframe # # Not all organizations can be emedded - only those that have the `embeddable?` # setting set. # # This mixin provides two sets of methods: # # * `embedded_mode?` / `standalone_mode?`, which are helpers aimed to be used by views # and change very specific rendering details in one or the other mode # * `enable_embedded_rendering`, which is designed to be called from main-views controller-methods that # actually support embedded mode. module Mumuki::Laboratory::Controllers::EmbeddedMode extend ActiveSupport::Concern included do helper_method :embedded_mode?, :standalone_mode? end def embedded_mode? @embedded_mode ||= params[:embed] == 'true' && Organization.current.embeddable? end def standalone_mode? !embedded_mode? end def enable_embedded_rendering return unless embedded_mode? allow_parent_iframe! render layout: 'embedded' end private def allow_parent_iframe! response.set_header 'X-Frame-Options', 'ALLOWALL' end end
# This mixin provides support for implementing the # embedded mode - as opposed to the standalone mode -in which # the mumuki pages # # * are displayed used a simplified layout, called `embedded.html.erb` # * are served using `X-Frame-Options` that allow them to be used within # an iframe # # Not all organizations can be emedded - only those that have the `embeddable?` # setting set. # # This mixin provides two sets of methods: # # * `embedded_mode?` / `standalone_mode?`, which are helpers aimed to be used by views # and change very specific rendering details in one or the other mode # * `enable_embedded_rendering`, which is designed to be called from main-views controller-methods that # actually support embedded mode. module Mumuki::Laboratory::Controllers::EmbeddedMode extend ActiveSupport::Concern included do helper_method :embedded_mode?, :standalone_mode? end def embedded_mode? @embedded_mode ||= params[:embed] == 'true' && Organization.current.embeddable? end def standalone_mode? !embedded_mode? end def enable_embedded_rendering return unless embedded_mode? allow_parent_iframe! render layout: 'embedded' end private def allow_parent_iframe! response.delete_header 'X-Frame-Options' end end
Add test coverage for PermittedAttributes::User
# frozen_string_literal: true require 'spec_helper' module PermittedAttributes describe User do describe "simple usage" do let(:user_permitted_attributes) { PermittedAttributes::User.new(params) } describe "permits basic attributes" do let(:params) { ActionController::Parameters.new(user: { name: "John", email: "email@example.com" } ) } it "keeps permitted and removes not permitted" do permitted_attributes = user_permitted_attributes.call expect(permitted_attributes[:name]).to be nil expect(permitted_attributes[:email]).to eq "email@example.com" end it "keeps extra permitted attributes" do permitted_attributes = user_permitted_attributes.call([:name]) expect(permitted_attributes[:name]).to eq "John" expect(permitted_attributes[:email]).to eq "email@example.com" end end end describe "with custom resource_name" do let(:user_permitted_attributes) { PermittedAttributes::User.new(params, :spree_user) } let(:params) { ActionController::Parameters.new(spree_user: { name: "John", email: "email@example.com" } ) } it "keeps permitted and removes not permitted" do permitted_attributes = user_permitted_attributes.call expect(permitted_attributes[:name]).to be nil expect(permitted_attributes[:email]).to eq "email@example.com" end end end end
Fix SQL Injection in moment search
class MomentRepository < Hanami::Repository relations :people associations do belongs_to :person has_many :locations end def all_with_influencers aggregate(:person) .as(Moment) .call.collection end def find_with_locations(id) aggregate(:locations) .where(moments__id: id) .as(Moment) .one end def add_location(moment, data) assoc(:locations, moment).add(data) end def search_by_date(params) moments .combine(:person, :locations) .where("year_begin <= #{params[:year]}") .where("year_end >= #{params[:year]}") .as(Moment) .call .collection end def all_available_years return [] if moments.count == 0 min_year = moments.min(:year_begin) max_year = if all_still_ocurring.count > 0 Time.now.year else moments.max(:year_end) end (min_year..max_year).to_a end def search_by_influencer(influencer) moments .combine(:person, :locations) .where("#{influencer.type}_id": influencer.id) .as(Moment) .call.collection end private def all_still_ocurring moments.where(year_end: nil) end end
class MomentRepository < Hanami::Repository relations :people associations do belongs_to :person has_many :locations end def all_with_influencers aggregate(:person) .as(Moment) .call.collection end def find_with_locations(id) aggregate(:locations) .where(moments__id: id) .as(Moment) .one end def add_location(moment, data) assoc(:locations, moment).add(data) end def search_by_date(params) moments .combine(:person, :locations) .where('year_begin <= ? AND (year_end >= ? OR year_end IS NULL)', params[:year], params[:year]) .as(Moment) .call .collection end def all_available_years return [] if moments.count == 0 min_year = moments.min(:year_begin) max_year = if all_still_ocurring.count > 0 Time.now.year else moments.max(:year_end) end (min_year..max_year).to_a end def search_by_influencer(influencer) moments .combine(:person, :locations) .where("#{influencer.type}_id": influencer.id) .as(Moment) .call.collection end private def all_still_ocurring moments.where(year_end: nil) end end
Update Money dependency to work with older versions
Gem::Specification.new do |s| s.name = "google_currency" s.version = "2.0.0" s.platform = Gem::Platform::RUBY s.authors = ["Shane Emmons", "Donald Ball"] s.email = ["semmons99+RubyMoney@gmail.com", "donald.ball@gmail.com"] s.homepage = "http://rubymoney.github.com/google_currency" s.summary = "Access the Google Currency exchange rate data." s.description = "GoogleCurrency extends Money::Bank::Base and gives you access to the current Google Currency exchange rates." s.required_rubygems_version = ">= 1.3.6" s.add_development_dependency "rspec", ">= 2.0.0" s.add_development_dependency "yard", ">= 0.5.8" s.add_development_dependency "json", ">= 1.4.0" s.add_development_dependency "yajl-ruby", ">= 1.0.0" s.add_dependency "money", "~> 4.0.0" s.add_dependency "multi_json", ">= 1.0.0" s.files = Dir.glob("{lib,spec}/**/*") s.files += %w(LICENSE README.md CHANGELOG.md) s.files += %w(Rakefile .gemtest google_currency.gemspec) s.require_path = "lib" end
Gem::Specification.new do |s| s.name = "google_currency" s.version = "2.0.0" s.platform = Gem::Platform::RUBY s.authors = ["Shane Emmons", "Donald Ball"] s.email = ["semmons99+RubyMoney@gmail.com", "donald.ball@gmail.com"] s.homepage = "http://rubymoney.github.com/google_currency" s.summary = "Access the Google Currency exchange rate data." s.description = "GoogleCurrency extends Money::Bank::Base and gives you access to the current Google Currency exchange rates." s.required_rubygems_version = ">= 1.3.6" s.add_development_dependency "rspec", ">= 2.0.0" s.add_development_dependency "yard", ">= 0.5.8" s.add_development_dependency "json", ">= 1.4.0" s.add_development_dependency "yajl-ruby", ">= 1.0.0" s.add_dependency "money", ">= 3.5" s.add_dependency "multi_json", ">= 1.0.0" s.files = Dir.glob("{lib,spec}/**/*") s.files += %w(LICENSE README.md CHANGELOG.md) s.files += %w(Rakefile .gemtest google_currency.gemspec) s.require_path = "lib" end
Remove debugging from tests :)
require 'helper' class TestSetDocumentRevision < ActiveSupport::TestCase context "A SugarCRM.connection" do should "Update a document revision" do file = File.read("test/config_test.yaml") # Create a new document, no file is attached or uploaded at this stage. d = SugarCRM::Document.create( :revision => 1, :active_date => Date.today, :filename => "config_test.yaml", :document_name=> "config_test.yaml", :uploadfile => "config_test.yaml" ) # Did we succeed? assert !d.new? # Create a new document revision, attaching the file to the document_revision, and associating the document # revision with parent document SugarCRM.connection.debug = true assert SugarCRM.connection.set_document_revision(d.id, d.revision + 1, {:file => file, :file_name => "config_test.yaml"}) SugarCRM.connection.debug = false # Delete the document assert d.delete # Remove any document revisions associated with that document SugarCRM::DocumentRevision.find_all_by_document_id(d.id).each do |dr| assert dr.delete end end end end
require 'helper' class TestSetDocumentRevision < ActiveSupport::TestCase context "A SugarCRM.connection" do should "Update a document revision" do file = File.read("test/config_test.yaml") # Create a new document, no file is attached or uploaded at this stage. d = SugarCRM::Document.create( :revision => 1, :active_date => Date.today, :filename => "config_test.yaml", :document_name=> "config_test.yaml", :uploadfile => "config_test.yaml" ) # Did we succeed? assert !d.new? # Create a new document revision, attaching the file to the document_revision, and associating the document # revision with parent document assert SugarCRM.connection.set_document_revision(d.id, d.revision + 1, {:file => file, :file_name => "config_test.yaml"}) # Delete the document assert d.delete # Remove any document revisions associated with that document SugarCRM::DocumentRevision.find_all_by_document_id(d.id).each do |dr| assert dr.delete end end end end
Add deployment for new staging internal server.
require "capistrano_nrel_ext/recipes/branches" # Set the servers for this stage. role :app, "devstage-int.nrel.gov" role :web, "devstage-int.nrel.gov" # Set the base path for deployment. set :deploy_to_base, "/srv/developer/devstage-int" # Set the accessible web domain for this site. set :base_domain, "devstage-int.nrel.gov" # Set the Rails environment. set :rails_env, "staging_int"
Add a variation to monthly active editors calculation script
# Quick version of https://stats.wikimedia.org/v2/#/en.wikipedia.org/contributing/editors/normal|table|2018-04-01~2019-04-01|activity_level~1..4-edits*5..24-edits*25..99-edits*100..-edits active_editors_by_month = [] 12.times do |i| month = i.months.ago.month year = i.months.ago.year active_editor_count = Revision.joins(:article).where(articles: { namespace: '0' }).where('extract(month from date) = ?', month).where('extract(year from date) = ?', year).group('user_id').having('count(*) > 4').count.count active_editors_by_month << ["#{year}-#{month}-01", active_editor_count] end
# Quick version of https://stats.wikimedia.org/v2/#/en.wikipedia.org/contributing/editors/normal|table|2018-04-01~2019-04-01|activity_level~1..4-edits*5..24-edits*25..99-edits*100..-edits active_editors_by_month = [] 12.times do |i| month = i.months.ago.month year = i.months.ago.year active_editor_count = Revision.joins(:article).where(articles: { namespace: '0' }).where('extract(month from date) = ?', month).where('extract(year from date) = ?', year).group('user_id').having('count(*) > 4').count.count active_editors_by_month << ["#{year}-#{month}-01", active_editor_count] end # Calendar year version active_editors_by_month = [] 12.times do |i| month = i + 1 year = 2020 pp month active_editor_count = Revision.joins(:article).where(articles: { namespace: '0' }).where('extract(month from date) = ?', month).where('extract(year from date) = ?', year).group('user_id').having('count(*) > 4').count.count active_editors_by_month << ["#{year}-#{month}", active_editor_count] end puts active_editors_by_month
Add homepage to gem specification
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'active_elastic_job/version' Gem::Specification.new do |spec| spec.platform = Gem::Platform::RUBY spec.name = 'active_elastic_job' spec.version = ActiveElasticJob::VERSION spec.authors = ['Tawan Sierek'] spec.email = ['tawan@sierek.com'] spec.description = 'Active Elastic Job is a simple to use Active Job backend for Rails applications deployed on the Amazon Elastic Beanstalk platform.' spec.summary = spec.description spec.license = 'MIT' spec.files = Dir.glob('lib/**/*') + [ 'active-elastic-job.gemspec' ] spec.executables = [] spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.required_ruby_version = '>= 1.9.3' spec.add_development_dependency 'bundler' spec.add_development_dependency 'rspec', '~> 3.4' spec.add_development_dependency 'dotenv' spec.add_development_dependency 'fuubar' spec.add_development_dependency 'rails', '~> 4.2' spec.add_development_dependency 'rdoc' spec.add_dependency 'aws-sdk', '~> 2' end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'active_elastic_job/version' Gem::Specification.new do |spec| spec.platform = Gem::Platform::RUBY spec.name = 'active_elastic_job' spec.version = ActiveElasticJob::VERSION spec.authors = ['Tawan Sierek'] spec.email = ['tawan@sierek.com'] spec.description = 'Active Elastic Job is a simple to use Active Job backend for Rails applications deployed on the Amazon Elastic Beanstalk platform.' spec.summary = spec.description spec.license = 'MIT' spec.homepage = 'https://github.com/tawan/active-elastic-job' spec.files = Dir.glob('lib/**/*') + [ 'active-elastic-job.gemspec' ] spec.executables = [] spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.required_ruby_version = '>= 1.9.3' spec.add_development_dependency 'bundler' spec.add_development_dependency 'rspec', '~> 3.4' spec.add_development_dependency 'dotenv' spec.add_development_dependency 'fuubar' spec.add_development_dependency 'rails', '~> 4.2' spec.add_development_dependency 'rdoc' spec.add_dependency 'aws-sdk', '~> 2' end
Load RSpec configuration before accessing it
require 'rails/generators/named_base' require 'rspec/core' require 'rspec/rails/feature_check' # @private # Weirdly named generators namespace (should be `RSpec`) for compatibility with # rails loading. module Rspec # @private module Generators # @private class Base < ::Rails::Generators::NamedBase include RSpec::Rails::FeatureCheck def self.source_root(path = nil) if path @_rspec_source_root = path else @_rspec_source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'rspec', generator_name, 'templates')) end end def target_path(*paths) File.join(RSpec.configuration.default_path, *paths) end end end end # @private module Rails module Generators # @private class GeneratedAttribute def input_type @input_type ||= if type == :text "textarea" else "input" end end end end end
require 'rails/generators/named_base' require 'rspec/core' require 'rspec/rails/feature_check' # @private # Weirdly named generators namespace (should be `RSpec`) for compatibility with # rails loading. module Rspec # @private module Generators # @private class Base < ::Rails::Generators::NamedBase include RSpec::Rails::FeatureCheck def self.source_root(path = nil) if path @_rspec_source_root = path else @_rspec_source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'rspec', generator_name, 'templates')) end end # This is specifically to parse and load `.rspec` file, # So we can use different directory. def self.configuration @configuration ||= begin configuration = RSpec.configuration options = RSpec::Core::ConfigurationOptions.new({}) options.configure(configuration) configuration end end def target_path(*paths) File.join(self.class.configuration.default_path, *paths) end end end end # @private module Rails module Generators # @private class GeneratedAttribute def input_type @input_type ||= if type == :text "textarea" else "input" end end end end end
Handle nil result from parser
# encoding: UTF-8 require 'active_support/core_ext/object' require 'crfpp' require 'free_cite/crfparser' class Citation def self.parse(str) return unless str.present? hash = self.parser.parse_string(str).symbolize_keys hash if self.valid_reference?(hash) end def self.parser @parser ||= CRFParser.new end def self.valid_reference?(hash) hash[:title].present? && hash[:raw_string] != hash[:title] && hash[:year].present? end end
# encoding: UTF-8 require 'active_support/core_ext/object' require 'crfpp' require 'free_cite/crfparser' class Citation def self.parse(str) return unless str.present? hash = (self.parser.parse_string(str) || {}).symbolize_keys hash if self.valid_reference?(hash) end def self.parser @parser ||= CRFParser.new end def self.valid_reference?(hash) hash[:title].present? && hash[:raw_string] != hash[:title] && hash[:year].present? end end
Rename rake task to reflect action better.
require 'rake/tasklib' module Chicago # Rake tasks for a Chicago project. class RakeTasks < Rake::TaskLib def initialize(db) @migration_dir = "migrations" @db = db @test_dir = "test" define end def define desc "Report code statistics (KLOCs, etc) from the application" task :stats do verbose = true stats_dirs = [['Code', './lib'], ['Test', "./#{@test_dir}"]].select { |name, dir| File.directory?(dir) } CodeStatistics.new(*stats_dirs).to_s end namespace :db do desc "Write Null dimension records" task :prepare do # TODO: replace this with proper logging. warn "Loading NULL records." Schema::Dimension.definitions.each {|dimension| dimension.create_null_records(@db) } end desc "Writes a migration file to change the database based on defined Facts & Dimensions" task :write_migrations do Schema::MigrationFileWriter.new(@db, @migration_dir).write_migration_file end end end end end
require 'rake/tasklib' module Chicago # Rake tasks for a Chicago project. class RakeTasks < Rake::TaskLib def initialize(db) @migration_dir = "migrations" @db = db @test_dir = "test" define end def define desc "Report code statistics (KLOCs, etc) from the application" task :stats do verbose = true stats_dirs = [['Code', './lib'], ['Test', "./#{@test_dir}"]].select { |name, dir| File.directory?(dir) } CodeStatistics.new(*stats_dirs).to_s end namespace :db do desc "Write Null dimension records" task :create_null_records do # TODO: replace this with proper logging. warn "Loading NULL records." Schema::Dimension.definitions.each {|dimension| dimension.create_null_records(@db) } end desc "Writes a migration file to change the database based on defined Facts & Dimensions" task :write_migrations do Schema::MigrationFileWriter.new(@db, @migration_dir).write_migration_file end end end end end
Change to page with signout link
Given(/^I am a signed in admin$/) do admin = create(:case_worker, :admin) visit new_user_session_path sign_in(admin, 'password') end Given(/^a case worker exists$/) do @case_worker = create(:case_worker) end Given(/^submitted claims exist$/) do @claims = create_list(:submitted_claim, 5) end When(/^I visit the case worker allocation page$/) do visit allocate_case_workers_admin_case_worker_path(@case_worker) end When(/^I allocate claims$/) do select @claims.first.case_number, from: 'case_worker_claim_ids' select @claims.second.case_number, from: 'case_worker_claim_ids' click_on 'Update Case worker' end Then(/^the case worker should have claims allocated to them$/) do expect(@case_worker.claims).to match_array([@claims.first, @claims.second]) end Then(/^the claims should be visible on the case worker's dashboard$/) do click_on 'Sign out' visit new_user_session_path sign_in(@case_worker, 'password') claim_dom_ids = @case_worker.claims.map { |claim| "#claim_#{claim.id}" } claim_dom_ids.each do |dom_id| expect(page).to have_selector(dom_id) end end
Given(/^I am a signed in admin$/) do admin = create(:case_worker, :admin) visit new_user_session_path sign_in(admin, 'password') end Given(/^a case worker exists$/) do @case_worker = create(:case_worker) end Given(/^submitted claims exist$/) do @claims = create_list(:submitted_claim, 5) end When(/^I visit the case worker allocation page$/) do visit allocate_case_workers_admin_case_worker_path(@case_worker) end When(/^I allocate claims$/) do select @claims.first.case_number, from: 'case_worker_claim_ids' select @claims.second.case_number, from: 'case_worker_claim_ids' click_on 'Update Case worker' end Then(/^the case worker should have claims allocated to them$/) do expect(@case_worker.claims).to match_array([@claims.first, @claims.second]) end Then(/^the claims should be visible on the case worker's dashboard$/) do visit case_workers_root_path click_on 'Sign out' visit new_user_session_path sign_in(@case_worker, 'password') claim_dom_ids = @case_worker.claims.map { |claim| "#claim_#{claim.id}" } claim_dom_ids.each do |dom_id| expect(page).to have_selector(dom_id) end end
Fix persistence generator for Rails 3 use
require 'rails/generators/migration' require 'rails/generators/active_record' class PersistenceGenerator < Rails::Generators::Base include Rails::Generators::Migration desc "Generates a migration for the AMEE Organisation models" def self.source_root @source_root ||= File.dirname(__FILE__) + '/templates' end def self.next_migration_number(path) ActiveRecord::Generators::Base.next_migration_number(path) end def generate_migration migration_template 'db/migrate/001_create_persistence_tables.rb', 'db/migrate/create_persistence_tables' migration_template 'db/migrate/002_add_unit_columns.rb', 'db/migrate/add_unit_columns' migration_template 'db/migrate/003_add_value_types.rb', 'db/migrate/add_value_types' end def manifest record do |m| ######################################## # persistence level configuration file # ######################################## # Get method from command line - default is metadata method = args[0] || 'metadata' # Make sure there is a config directory m.directory File.join("config") # Create persistence.yml file m.template File.join("config","persistence.yml.erb"), File.join("config","persistence.yml"), :assigns => {:method => method} end end end
require 'rails/generators/migration' require 'rails/generators/active_record' class PersistenceGenerator < Rails::Generators::Base # Get method from command line - default is metadata argument :method, :type => :string, :desc => "The storage method to use; everything, metadata, or outputs", :default => 'metadata' include Rails::Generators::Migration desc "Generates a migration for the AMEE Organisation models" def self.source_root @source_root ||= File.dirname(__FILE__) + '/templates' end def self.next_migration_number(path) ActiveRecord::Generators::Base.next_migration_number(path) end def generate_migration migration_template 'db/migrate/001_create_persistence_tables.rb', 'db/migrate/create_persistence_tables' migration_template 'db/migrate/002_add_unit_columns.rb', 'db/migrate/add_unit_columns' migration_template 'db/migrate/003_add_value_types.rb', 'db/migrate/add_value_types' end def manifest ######################################## # persistence level configuration file # ######################################## # Create persistence.yml file template File.join("config","persistence.yml.erb"), File.join("config","persistence.yml"), :assigns => {:method => self.method} end end
Check slide number before setting
module CommandDeck class Runner attr_accessor :deck def initialize(args) @current = args.fetch(:start, 1) p @current @deck = CommandDeck::Deck.new(slide_dir: args[:slide_dir], screen_width: args.fetch(:screen_width, 80), screen_height: args.fetch(:screen_height, 24)) end def read_char begin old_state = `stty -g` system "stty raw -echo" c = $stdin.getc.chr rescue => ex p ex ensure system "stty #{old_state}" end c end def start display_slide(@current) loop do case read_char when "q" break when "n" @current = @current + 1 display_slide(@current) when "p" @current = @current - 1 display_slide(@current) else next end end end def display_slide(number) system "clear" puts deck.slide_with_number(number).content end end end
module CommandDeck class Runner attr_accessor :deck def initialize(args) @current = args.fetch(:start, 1) p @current @deck = CommandDeck::Deck.new(slide_dir: args[:slide_dir], screen_width: args.fetch(:screen_width, 80), screen_height: args.fetch(:screen_height, 24)) end def read_char begin old_state = `stty -g` system "stty raw -echo" c = $stdin.getc.chr rescue => ex p ex ensure system "stty #{old_state}" end c end def start display_slide(@current) loop do case read_char when "q" break when "n" @current = @current + 1 unless deck.count <= @current display_slide(@current) when "p" @current = @current - 1 unless @current <= 1 display_slide(@current) else next end end end def display_slide(number) system "clear" puts deck.slide_with_number(number).content end end end
Add migration for new contact_people fields
class UpdateContactPeople < ActiveRecord::Migration def change add_column :contact_people, :first_name, :string add_column :contact_people, :last_name, :string add_column :contact_people, :operational_name, :string add_column :contact_people, :academic_title, :string add_column :contact_people, :gender, :string add_column :contact_people, :role, :string add_column :contact_people, :responsibility, :string ContactPeople.find_each do |contact_person| contact_person.update_column :last_name, contact_person.name end end end
Add TODO note about recently added functionality.
require "active_support/core_ext" require 'nark/middleware' require 'nark/exceptions' require 'nark/plugin' require 'nark/report_broker' # # This middleware is the basis of all tracking via rack middleware. # # It allows you to easily create your own tracker and simply plugin it into Nark allowing you to gain # valuable information on the service you are currently running. # module Nark include Nark::ReportBroker include Nark::Plugin # # All Rack::Tracker class variables are settable via this configuration method. # # This means that configuration settings are dynamically added dependant on # what variables you expose via your plugins to Rack::Tracker. # # TODO: Refactor so only specific class variables, possibly only setters, are exposed via our plugins. # class << self def configure yield self true end def app app Rack::Builder.new do use Nark::Middleware Nark.reporters.each do |reporter| use reporter end run app end end end end
require "active_support/core_ext" require 'nark/middleware' require 'nark/exceptions' require 'nark/plugin' require 'nark/report_broker' # # This middleware is the basis of all tracking via rack middleware. # # It allows you to easily create your own tracker and simply plugin it into Nark allowing you to gain # valuable information on the service you are currently running. # module Nark include Nark::ReportBroker include Nark::Plugin # # All Rack::Tracker class variables are settable via this configuration method. # # This means that configuration settings are dynamically added dependant on # what variables you expose via your plugins to Rack::Tracker. # # TODO: Refactor so only specific class variables, possibly only setters, are exposed via our plugins. # class << self def configure yield self true end def app app Rack::Builder.new do use Nark::Middleware # TODO: Determine whether this belongs here or not. Feels like part of the middlewares job. Nark.reporters.each do |reporter| use reporter end run app end end end end
Add 'minitest/pride' to encourage testing.
require 'simplecov' require 'pry' require 'minitest/autorun' require 'minitest/hell' SimpleCov.start do command_name 'MiniTest::Spec' add_filter '/test/' end unless ENV['no_simplecov'] require 'playa' require 'mocha/setup' GC.disable # commented out by default (makes tests slower) # require 'minitest/reporters' # Minitest::Reporters.use!( # Minitest::Reporters::DefaultReporter.new({ color: true, slow_count: 5 }), # Minitest::Reporters::SpecReporter.new # )
require 'simplecov' require 'pry' require 'minitest/autorun' require 'minitest/hell' require 'minitest/pride' SimpleCov.start do command_name 'MiniTest::Spec' add_filter '/test/' end unless ENV['no_simplecov'] require 'playa' require 'mocha/setup' GC.disable # commented out by default (makes tests slower) # require 'minitest/reporters' # Minitest::Reporters.use!( # Minitest::Reporters::DefaultReporter.new({ color: true, slow_count: 5 }), # Minitest::Reporters::SpecReporter.new # )
Refactor test to match temp dir on regex
describe WinRM::FileManager, :integration => true do let(:service) { winrm_connection } let(:src_file) { __FILE__ } let(:dest_file) { File.join(subject.temp_dir, 'winrm_filemanager_test') } subject { WinRM::FileManager.new(service) } context 'temp_dir' do it 'should return the remote guests temp dir' do expect(subject.temp_dir).to eq('C:\Users\vagrant\AppData\Local\Temp') end end context 'upload' do it 'should upload the specified file' do subject.upload(src_file, dest_file) expect(subject.exists?(dest_file)).to be true end end end
describe WinRM::FileManager, :integration => true do let(:service) { winrm_connection } let(:src_file) { __FILE__ } let(:dest_file) { File.join(subject.temp_dir, 'winrm_filemanager_test') } subject { WinRM::FileManager.new(service) } context 'temp_dir' do it 'should return the remote guests temp dir' do expect(subject.temp_dir).to match(/C:\\Users\\\w+\\AppData\\Local\\Temp/) end end context 'upload' do it 'should upload the specified file' do subject.upload(src_file, dest_file) expect(subject.exists?(dest_file)).to be true end end end
Move api call to Heroe model
require 'digest/md5' class HeroesController < ApplicationController def index render "heroes" end def all # Marvel API only returns a maximum of 100 results per call # There are 1485 characters # Some results are organizations such as H.Y.D.R.A # Some comics are collections of individual issues url = 'https://gateway.marvel.com:443/v1/public/characters?limit=100' + '&ts=' + timestamp + '&apikey=' + ENV["MARVEL_PUBLIC"] + '&hash=' + marvel_hash # debugger uri = URI(url) response = Net::HTTP.get(uri) render json: JSON.parse(response) end private def timestamp Time.now.to_i.to_s end def marvel_hash hash = Digest::MD5.hexdigest( timestamp + ENV['MARVEL_PRIVATE'] + ENV['MARVEL_PUBLIC'] ) end end
require 'digest/md5' class HeroesController < ApplicationController def index render "heroes" end def all # Marvel API only returns a maximum of 100 results per call # There are 1485 characters # Will need to offset by 100 every call, 15 times to populate database # Some results are organizations such as H.Y.D.R.A # Some comics are collections of individual issues # url = "https://gateway.marvel.com:443/v1/public/characters?limit=100&offset=10&ts=#{timestamp}&apikey=#{ENV['MARVEL_PUBLIC']}&hash=#{marvel_hash}" # debugger # uri = URI(url) # response = Net::HTTP.get(uri) # @response = JSON.parse(response) # render json: JSON.parse(response) # test # <% @response['data']['results'].each do |hero| %> # <%= hero['name'] %> # <% end %> # render "heroes" Heroe.save_hero_data end end
Refactor to sting interpolation Pair: @rachelthecodesmith @CharlesIC
module ConfigEndpoints PATH = '/config'.freeze PATH_PREFIX = Pathname(PATH) IDP_LIST_SUFFIX = 'idps/idp-list/%s/%s'.freeze IDP_LIST_SIGN_IN_SUFFIX = 'idps/idp-list-for-sign-in/%s'.freeze DISPLAY_DATA_SUFFIX = 'transactions/%s/display-data'.freeze TRANSACTIONS_SUFFIX = 'transactions/enabled'.freeze def idp_list_for_loa_endpoint(transaction_id, loa) PATH_PREFIX.join(IDP_LIST_SUFFIX % [CGI.escape(transaction_id), CGI.escape(loa)]).to_s end def idp_list_for_sign_in_endpoint(transaction_id) PATH_PREFIX.join(IDP_LIST_SIGN_IN_SUFFIX % [CGI.escape(transaction_id)]).to_s end def transactions_endpoint PATH_PREFIX.join(TRANSACTIONS_SUFFIX).to_s end def transaction_display_data_endpoint(transaction_entity_id) PATH_PREFIX.join(DISPLAY_DATA_SUFFIX % CGI.escape(transaction_entity_id)).to_s end end
module ConfigEndpoints PATH = '/config'.freeze PATH_PREFIX = Pathname(PATH) IDP_LIST_SUFFIX = 'idps/idp-list/%<transaction_name>s/%<loa>s'.freeze IDP_LIST_SIGN_IN_SUFFIX = 'idps/idp-list-for-sign-in/%<transaction_name>s'.freeze DISPLAY_DATA_SUFFIX = 'transactions/%<transaction_entity_id>s/display-data'.freeze TRANSACTIONS_SUFFIX = 'transactions/enabled'.freeze def idp_list_for_loa_endpoint(transaction_id, loa) # PATH_PREFIX.join(IDP_LIST_SUFFIX % [CGI.escape(transaction_id), CGI.escape(loa)]).to_s PATH_PREFIX.join(IDP_LIST_SUFFIX % { transaction_name: CGI.escape(transaction_id), loa: CGI.escape(loa) }).to_s end def idp_list_for_sign_in_endpoint(transaction_id) # PATH_PREFIX.join(IDP_LIST_SIGN_IN_SUFFIX % [CGI.escape(transaction_id)]).to_s PATH_PREFIX.join(IDP_LIST_SIGN_IN_SUFFIX % { transaction_name: CGI.escape(transaction_id) }).to_s end def transactions_endpoint PATH_PREFIX.join(TRANSACTIONS_SUFFIX).to_s end def transaction_display_data_endpoint(transaction_entity_id) PATH_PREFIX.join(DISPLAY_DATA_SUFFIX % { transaction_entity_id: CGI.escape(transaction_entity_id) }).to_s end end
Fix crash when error response is not a valid JSON
module Fog module Scaleway module Errors def self.decode_error(error) body = begin Fog::JSON.decode(error.response.body) rescue Fog::JSON::DecodeError end return if body.nil? type = body['type'] message = body['message'] fields = body['fields'] return if type.nil? || message.nil? unless fields.nil? message << "\n" message << format_fields(fields) end { type: type, message: message } end def self.format_fields(fields) fields.map { |field, msgs| format_field(field, msgs) }.join("\n") end def self.format_field(field, msgs) msgs = msgs.map { |msg| "\t\t- #{msg}" } "\t#{field}:\n#{msgs.join("\n")}" end end end end
module Fog module Scaleway module Errors def self.decode_error(error) body = begin Fog::JSON.decode(error.response.body) rescue Fog::JSON::DecodeError nil end return if body.nil? type = body['type'] message = body['message'] fields = body['fields'] return if type.nil? || message.nil? unless fields.nil? message << "\n" message << format_fields(fields) end { type: type, message: message } end def self.format_fields(fields) fields.map { |field, msgs| format_field(field, msgs) }.join("\n") end def self.format_field(field, msgs) msgs = msgs.map { |msg| "\t\t- #{msg}" } "\t#{field}:\n#{msgs.join("\n")}" end end end end
Change route to share application
#module CatarseStripe #class Engine < ::Rails::Engine #isolate_namespace CatarseStripe #end #end module ActionDispatch::Routing class Mapper def mount_catarse_stripe_at(catarse_stripe) namespace :payment do get '/stripe/:id/review' => 'catarse_stripe/payment/stripe#review', :as => 'review_stripe' post '/stripe/notifications' => 'catarse_stripe/payment/stripe#ipn', :as => 'ipn_stripe' match '/stripe/:id/notifications' => 'catarse_stripe/payment/stripe#notifications', :as => 'notifications_stripe' match '/stripe/:id/pay' => 'catarse_stripe/payment/stripe#pay', :as => 'pay_stripe' match '/stripe/:id/success' => 'catarse_stripe/payment/stripe#success', :as => 'success_stripe' match '/stripe/:id/cancel' => 'catarse_stripe/payment/stripe#cancel', :as => 'cancel_stripe' match '/stripe/:id/charge' => 'catarse_stripe/payment/stripe#charge', :as => 'charge_stripe' end end end end
#module CatarseStripe #class Engine < ::Rails::Engine #isolate_namespace CatarseStripe #end #end module ActionDispatch::Routing class Mapper def mount_catarse_stripe_at(catarse_stripe) scope :payment do get '/stripe/:id/review' => 'catarse_stripe/payment/stripe#review', :as => 'review_stripe' post '/stripe/notifications' => 'catarse_stripe/payment/stripe#ipn', :as => 'ipn_stripe' match '/stripe/:id/notifications' => 'catarse_stripe/payment/stripe#notifications', :as => 'notifications_stripe' match '/stripe/:id/pay' => 'catarse_stripe/payment/stripe#pay', :as => 'pay_stripe' match '/stripe/:id/success' => 'catarse_stripe/payment/stripe#success', :as => 'success_stripe' match '/stripe/:id/cancel' => 'catarse_stripe/payment/stripe#cancel', :as => 'cancel_stripe' match '/stripe/:id/charge' => 'catarse_stripe/payment/stripe#charge', :as => 'charge_stripe' end end end end
Add fix for Rails 4
module MultiTest def self.disable_autorun if defined?(Test::Unit::Runner) Test::Unit::Runner.module_eval("@@stop_auto_run = true") end end end
module MultiTest def self.disable_autorun if defined?(Test::Unit::Runner) Test::Unit::Runner.module_eval("@@stop_auto_run = true") end if defined?(Minitest) if defined?(Minitest::Unit) Minitest::Unit.class_eval do def run(*) end end end end end end
Include `Which` within Util autoloads
module Vagrant module Util autoload :Busy, 'vagrant/util/busy' autoload :CommandDeprecation, 'vagrant/util/command_deprecation' autoload :Counter, 'vagrant/util/counter' autoload :CredentialScrubber, 'vagrant/util/credential_scrubber' autoload :DeepMerge, 'vagrant/util/deep_merge' autoload :Env, 'vagrant/util/env' autoload :HashWithIndifferentAccess, 'vagrant/util/hash_with_indifferent_access' autoload :GuestInspection, 'vagrant/util/guest_inspection' autoload :Platform, 'vagrant/util/platform' autoload :Retryable, 'vagrant/util/retryable' autoload :SafeExec, 'vagrant/util/safe_exec' autoload :SilenceWarnings, 'vagrant/util/silence_warnings' autoload :StackedProcRunner, 'vagrant/util/stacked_proc_runner' autoload :StringBlockEditor, 'vagrant/util/string_block_editor' autoload :Subprocess, 'vagrant/util/subprocess' autoload :TemplateRenderer, 'vagrant/util/template_renderer' end end
module Vagrant module Util autoload :Busy, 'vagrant/util/busy' autoload :CommandDeprecation, 'vagrant/util/command_deprecation' autoload :Counter, 'vagrant/util/counter' autoload :CredentialScrubber, 'vagrant/util/credential_scrubber' autoload :DeepMerge, 'vagrant/util/deep_merge' autoload :Env, 'vagrant/util/env' autoload :HashWithIndifferentAccess, 'vagrant/util/hash_with_indifferent_access' autoload :GuestInspection, 'vagrant/util/guest_inspection' autoload :Platform, 'vagrant/util/platform' autoload :Retryable, 'vagrant/util/retryable' autoload :SafeExec, 'vagrant/util/safe_exec' autoload :SilenceWarnings, 'vagrant/util/silence_warnings' autoload :StackedProcRunner, 'vagrant/util/stacked_proc_runner' autoload :StringBlockEditor, 'vagrant/util/string_block_editor' autoload :Subprocess, 'vagrant/util/subprocess' autoload :TemplateRenderer, 'vagrant/util/template_renderer' autoload :Which, 'vagrant/util/which' end end