diff
stringlengths
65
26.7k
message
stringlengths
7
9.92k
diff --git a/test/prawn/emoji/image_spec.rb b/test/prawn/emoji/image_spec.rb index abc1234..def5678 100644 --- a/test/prawn/emoji/image_spec.rb +++ b/test/prawn/emoji/image_spec.rb @@ -1,12 +1,13 @@ require 'test_helper' describe Prawn::Emoji::Image do - describe '#path' do - def image_path_for(emoji) - Prawn::Emoji::Image.new(emoji).path + let(:emojis) { %w( 😀 © ) } + + it 'possible to find the image file' do + emojis.each do |emoji| + emoji_image = Prawn::Emoji::Image.new(emoji) + + assert File.exist?(emoji_image.path), "#{emoji} not found" end - - it { image_path_for('😀').must_equal Prawn::Emoji.root.join('emoji', 'images', '1F600.png').to_s } - it { image_path_for('©').must_equal Prawn::Emoji.root.join('emoji', 'images', '00A9.png').to_s } end end
Test for existence of emoji image file
diff --git a/app/uploaders/esr_file_uploader.rb b/app/uploaders/esr_file_uploader.rb index abc1234..def5678 100644 --- a/app/uploaders/esr_file_uploader.rb +++ b/app/uploaders/esr_file_uploader.rb @@ -7,6 +7,6 @@ # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir - "system/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" + root.join(model.class.to_s.underscore, mounted_as.to_s, model.id.to_s) end end
Use configured root instead of hardcoded "system/uploads" for esr file uploader.
diff --git a/app/validators/schema_validator.rb b/app/validators/schema_validator.rb index abc1234..def5678 100644 --- a/app/validators/schema_validator.rb +++ b/app/validators/schema_validator.rb @@ -29,7 +29,7 @@ def schema @schema || JSON.load(File.read(schema_filepath)) rescue Errno::ENOENT => error - msg = "#{payload} is missing schema_name #{schema_name} or type #{type}" + msg = "Unable to find schema for schema_name #{schema_name} and type #{type}" Airbrake.notify_or_ignore(error, parameters: { explanation: msg }) {} end
Improve error message when schema not found
diff --git a/apps/api/controllers/data/fetch.rb b/apps/api/controllers/data/fetch.rb index abc1234..def5678 100644 --- a/apps/api/controllers/data/fetch.rb +++ b/apps/api/controllers/data/fetch.rb @@ -16,11 +16,5 @@ url = GetUrlForBlob.call(@blob) redirect_to url end - - # http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-authentication-HTTPPOST.html - # http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjectPreSignedURLRubySDK.html#UploadObjectPreSignedURLRubySDKV2 - # https://leonid.shevtsov.me/post/demystifying-s3-browser-upload/ - # https://github.com/codeartists/codeartists-com/blob/master/How-to-upload-files-to-Amazon-S3-from-client-side-web-app.md - # http://docs.aws.amazon.com/sdk-for-ruby/v2/developer-guide/stubbing.html end end
Remove commented AWS S3 references
diff --git a/disc.gemspec b/disc.gemspec index abc1234..def5678 100644 --- a/disc.gemspec +++ b/disc.gemspec @@ -14,6 +14,6 @@ s.executables.push('disc') s.add_dependency('disque', '~> 0.0.6') - s.add_dependency('msgpack', '>= 0.5.6', '=< 0.6.2') + s.add_dependency('msgpack', '>= 0.5.6', '< 0.6.3') s.add_dependency('clap', '~> 1.0') end
Fix requirement pattern of mspgack dependency.
diff --git a/JTSSloppySwiping.podspec b/JTSSloppySwiping.podspec index abc1234..def5678 100644 --- a/JTSSloppySwiping.podspec +++ b/JTSSloppySwiping.podspec @@ -1,17 +1,17 @@ Pod::Spec.new do |s| s.name = "JTSSloppySwiping" - s.version = "1.2.1" + s.version = "1.2.2" s.summary = "A drop-in UINavigationControllerDelegate that enables sloppy swiping." s.description = "A drop-in UINavigationControllerDelegate that enables sloppy swiping. I'm adding additional words here to satisy CocoaPods' pedantry." s.homepage = "https://github.com/jaredsinclair/JTSSloppySwiping" s.license = 'MIT' s.author = { "Jared Sinclair" => "desk@jaredsinclair.com" } - s.source = { :git => "https://github.com/jaredsinclair/JTSSloppySwiping", :tag => s.version.to_s } + s.source = { :git => "https://github.com/jaredsinclair/JTSSloppySwiping.git", :tag => s.version.to_s } s.platform = :ios, '8.0' s.requires_arc = true s.frameworks = 'Foundation' - s.source_files = 'Source/*.swift' + s.source_files = 'JTSSloppySwiping/*.swift' end
Fix podspec errors, bump to 1.2.2.
diff --git a/app/services/demand_progress_gateway.rb b/app/services/demand_progress_gateway.rb index abc1234..def5678 100644 --- a/app/services/demand_progress_gateway.rb +++ b/app/services/demand_progress_gateway.rb @@ -1,5 +1,5 @@ class DemandProgressGateway < ActiveRecord::Base self.abstract_class = true - establish_connection "demand_progress_" + ::Rails.env.to_s + establish_connection "demand_progress_"[::Rails.env] end
Revert "Changed connection string in DP Gateway to string" This reverts commit 13301fa6caebf6aa6a0e3c88607639b1c3fc9278.
diff --git a/lib/cocoapods/search/pod.rb b/lib/cocoapods/search/pod.rb index abc1234..def5678 100644 --- a/lib/cocoapods/search/pod.rb +++ b/lib/cocoapods/search/pod.rb @@ -7,11 +7,7 @@ end def score - if github? - @star_count + @fork_count * 5 - else - 0 - end + github? ? (@star_count + @fork_count * 5) : 0 end def to_a
Refactor 1liner as readability is not lost
diff --git a/lib/hivemind/code_viewer.rb b/lib/hivemind/code_viewer.rb index abc1234..def5678 100644 --- a/lib/hivemind/code_viewer.rb +++ b/lib/hivemind/code_viewer.rb @@ -0,0 +1,41 @@+ 'universal_ast' + +module Hivemind + class CodeViewer + def initialize(tree) + @tree = tree + end + + def view_as(query) + hierarchy = QueryAnalyzer.parse(query) + rebuild_tree(hierarchy) + end + + def rebuild_tree(hierarchy) + if hierarchy[0].type == @code_view.hierarchy[0].type + # only sorting maybe + # and sorting still not supported + @tree + else + # method > code + new_tree = UniversalAST::Image.new([]) + top = {} + if hierarchy[0].type == :method + @tree.statements.each do |statement| + statement.methods.each do |method| + top[method.method_name.value] ||= {} + top[method.method_name.value][statement.class_name.value] = [args, method.body] + end + end + else + @tree.statements.each do |statement| + statement.body.each do |method| + top[method.class_name.value] ||= {} + top[method.class_name.value][statement.method_name.value] = [args, method.body] + end + end + end + end + end + end +end
Add a prototype of a code viewer
diff --git a/cookbooks/bcpc_kafka/recipes/zookeeper_server.rb b/cookbooks/bcpc_kafka/recipes/zookeeper_server.rb index abc1234..def5678 100644 --- a/cookbooks/bcpc_kafka/recipes/zookeeper_server.rb +++ b/cookbooks/bcpc_kafka/recipes/zookeeper_server.rb @@ -5,7 +5,9 @@ include_recipe 'bcpc_kafka::default' -node.default[:bcpc][:hadoop][:kerberos][:enable] = false +# For the time being, this will have to be force_override. +node.force_override[:bcpc][:hadoop][:kerberos][:enable] = false + include_recipe 'bcpc-hadoop::zookeeper_server' include_recipe 'bcpc::diamond'
Raise kafka_bcpc kerberos override precedence level to force_override
diff --git a/cookbooks/travis_build_environment/recipes/hk.rb b/cookbooks/travis_build_environment/recipes/hk.rb index abc1234..def5678 100644 --- a/cookbooks/travis_build_environment/recipes/hk.rb +++ b/cookbooks/travis_build_environment/recipes/hk.rb @@ -20,9 +20,10 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. -ark 'hk' do - version '20140604' - url 'https://hk.heroku.com/hk.gz' - has_binaries %w(hk) - strip_components 0 +local_hk_gz = "#{Chef::Config[:file_cache_path]}/hk.gz" + +remote_file local_hk_gz do + source 'https://hk.heroku.com/hk.gz' end + +execute "zcat < #{local_hk_gz} > /usr/local/bin/hk && chmod +x /usr/local/bin/hk"
Switch from ark to remote_file && execute since ark doesn't understand `.gz`
diff --git a/db/migrate/20210315163900_update_associations.rb b/db/migrate/20210315163900_update_associations.rb index abc1234..def5678 100644 --- a/db/migrate/20210315163900_update_associations.rb +++ b/db/migrate/20210315163900_update_associations.rb @@ -6,8 +6,8 @@ def up # Updates any adjustments missing an order association - Spree::Adjustment.where(order_id: nil, adjustable_type: "Spree::Order").find_each do |adjustment| - adjustment.update_column(:order_id, adjustment.adjustable_id) - end + Spree::Adjustment. + where(order_id: nil, adjustable_type: "Spree::Order"). + update_all("order_id = adjustable_id") end end
Improve update efficiency in migration
diff --git a/models/class_type.rb b/models/class_type.rb index abc1234..def5678 100644 --- a/models/class_type.rb +++ b/models/class_type.rb @@ -1,8 +1,9 @@ class ClassType TYPES_BY_ROLE = { - 'Creation' => ['Builder', 'Factory', 'Pool', 'Prototype'], - 'Interface' => ['Adapter', 'Interface'] + 'Business Object' => [''], + 'Creation' => ['Builder', 'Factory', 'Pool', 'Prototype'], + 'Interface' => ['Adapter', 'Interface'] } def self.roles
Add plain business object as role
diff --git a/activesupport/lib/active_support/memoizable.rb b/activesupport/lib/active_support/memoizable.rb index abc1234..def5678 100644 --- a/activesupport/lib/active_support/memoizable.rb +++ b/activesupport/lib/active_support/memoizable.rb @@ -29,14 +29,24 @@ raise "Already memoized #{symbol}" if method_defined?(:#{original_method}) alias #{original_method} #{symbol} - def #{symbol}(*args) - #{memoized_ivar} ||= {} - reload = args.pop if args.last == true || args.last == :reload + if instance_method(:#{symbol}).arity == 0 + def #{symbol}(reload = false) + if !reload && defined? #{memoized_ivar} + #{memoized_ivar} + else + #{memoized_ivar} = #{original_method}.freeze + end + end + else + def #{symbol}(*args) + #{memoized_ivar} ||= {} + reload = args.pop if args.last == true || args.last == :reload - if !reload && #{memoized_ivar} && #{memoized_ivar}.has_key?(args) - #{memoized_ivar}[args] - else - #{memoized_ivar}[args] = #{original_method}(*args).freeze + if !reload && #{memoized_ivar} && #{memoized_ivar}.has_key?(args) + #{memoized_ivar}[args] + else + #{memoized_ivar}[args] = #{original_method}(*args).freeze + end end end EOS
Optimize memoized method if there are no arguments
diff --git a/app/controllers/api/v1/locations_controller.rb b/app/controllers/api/v1/locations_controller.rb index abc1234..def5678 100644 --- a/app/controllers/api/v1/locations_controller.rb +++ b/app/controllers/api/v1/locations_controller.rb @@ -17,7 +17,7 @@ def show location = Location.includes( contacts: :phones, - services: [:categories, :regular_schedules, :holiday_schedules] + services: [:contacts, :categories, :regular_schedules, :holiday_schedules] ).find(params[:id]) render json: location, status: 200 expires_in ENV['EXPIRES_IN'].to_i.minutes, public: true
Fix N+1 query with Service Contacts.
diff --git a/app/controllers/gobierto_cms/pages_controller.rb b/app/controllers/gobierto_cms/pages_controller.rb index abc1234..def5678 100644 --- a/app/controllers/gobierto_cms/pages_controller.rb +++ b/app/controllers/gobierto_cms/pages_controller.rb @@ -12,7 +12,7 @@ def find_page_by_id_and_redirect if params[:id].present? && params[:id] =~ /\A\d+\z/ page = current_site.pages.active.find(params[:id]) - redirect_to gobierto_cms_page_path(page) and return false + redirect_to gobierto_cms_page_path(page.slug) and return false end end
Fix page finder by ID
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index abc1234..def5678 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -13,7 +13,7 @@ require 'veritas' require 'spec' -require 'spec/autorun' +require 'spec/autorun' if RUBY_VERSION < '1.9' include Veritas
Add conditional logic for loading autorun only for 1.8
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index abc1234..def5678 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -7,7 +7,6 @@ require 'rubygems' require 'bundler/setup' -require 'money_extensions' if ENV['COVERAGE'] require 'simplecov' @@ -16,6 +15,8 @@ SimpleCov.start end +require 'money_extensions' + RSpec.configure do |config| config.treat_symbols_as_metadata_keys_with_true_values = true config.run_all_when_everything_filtered = true
Fix coverage task as it needs to load prior to library
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index abc1234..def5678 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -36,7 +36,9 @@ class MiniTest::Spec before do - Vendorificator::Environment.any_instance.stubs(:git).returns(stub) + _git = stub + _git.stubs(:capturing).returns(stub) + Vendorificator::Environment.any_instance.stubs(:git).returns(_git) end def conf
Make stubbed MiniGit expect .capturing
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index abc1234..def5678 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -8,7 +8,7 @@ plugin_path = File.expand_path('.') config.start_vim do - vim = Vimrunner.start + vim = Vimrunner.start_gvim vim.add_plugin(plugin_path, 'plugin/splitjoin.vim') vim end
Use GUI vim for tests
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index abc1234..def5678 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -23,7 +23,7 @@ headers = c.headers (1..c.fields.size-1).each do |n| unless c.field(n).nil? - verbs[c.field(0)][headers[n]] = c.field(n).sub("* ","").sub(" / ",", ") + verbs[c.field(0)][headers[n]] = c.field(n).gsub("* ","").gsub(" / ",", ") end end unless verbs[c.field(0)]["qualifier"].nil?
Correct verb data reading methods to gsub ' / ' to ', ' rather than just subbing it. This should fix some incorrectly failing tests for the past test.
diff --git a/roles/ic.rb b/roles/ic.rb index abc1234..def5678 100644 --- a/roles/ic.rb +++ b/roles/ic.rb @@ -30,7 +30,7 @@ } }, :web => { - :backends => %w[rails1 rails2 rails3], + :backends => %w[rails4 rails5], :fileserver => "ironbelly", :readonly_database_host => "karm.ic.openstreetmap.org" }
Make IC frontends use bytemark backends
diff --git a/spec/todoml_spec.rb b/spec/todoml_spec.rb index abc1234..def5678 100644 --- a/spec/todoml_spec.rb +++ b/spec/todoml_spec.rb @@ -31,8 +31,9 @@ it "should retreve tasks" do @data['CURRENT'].count.should eq 1 task = @data['CURRENT'].first - task[0].should eq "User can read learn you some erlang" - task[1].should eq 3 + task = Todoml::Task.new({name: task[0], point: task[1]}) + task.name.should eq "User can read learn you some erlang" + task.point.should eq 3 end end end
Refactor task to use Task model
diff --git a/app/models/concerns/gobierto_common/sluggable.rb b/app/models/concerns/gobierto_common/sluggable.rb index abc1234..def5678 100644 --- a/app/models/concerns/gobierto_common/sluggable.rb +++ b/app/models/concerns/gobierto_common/sluggable.rb @@ -21,11 +21,12 @@ new_slug = base_slug if uniqueness_validators.present? - count = 2 uniqueness_validators.each do |validator| - while self.class.exists?(scope_attributes(validator.options[:scope]).merge(slug: new_slug)) - new_slug = "#{ base_slug }-#{ count }" - count += 1 + if (related_slugs = self.class.where("slug ~* ?", "#{ new_slug }-\\d+$").where(scope_attributes(validator.options[:scope]))).exists? + max_count = related_slugs.pluck(:slug).map { |slug| slug.scan(/\d+$/).first.to_i }.max + new_slug = "#{ base_slug }-#{ max_count + 1 }" + elsif self.class.exists?(scope_attributes(validator.options[:scope]).merge(slug: new_slug)) + new_slug = "#{ base_slug }-2" end end end
Refactor slug counter calculation to avoid increasing queries
diff --git a/ScalarArithmetic.podspec b/ScalarArithmetic.podspec index abc1234..def5678 100644 --- a/ScalarArithmetic.podspec +++ b/ScalarArithmetic.podspec @@ -1,5 +1,5 @@ Pod::Spec.new do |s| - name = "ScalarOperatable" + name = "ScalarArithmetic" url = "https://github.com/seivan/#{name}" git_url = "#{url}.git" s.name = name @@ -26,7 +26,7 @@ s.source = { :git => git_url, :tag => version} - s.platform = :ios, "8.0" + s.platform = :ios, "7.0" s.source_files = source_files
Fix name and set platform version to support 7.0
diff --git a/spec/count_words_spec.rb b/spec/count_words_spec.rb index abc1234..def5678 100644 --- a/spec/count_words_spec.rb +++ b/spec/count_words_spec.rb @@ -6,7 +6,6 @@ VCR.use_cassette('collect all the words') do repo = Lexhub::Repo.new('joemsak', 'lexhub') - repo.words.keys.count.should == 53 repo.words['initial'].should == { :count => 1 } end end
Remove specific that changes over time
diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index abc1234..def5678 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -26,6 +26,15 @@ build(:user, email: nil).should_not be_valid end - it "is invalid with a duplicate email address" + it "is invalid with a duplicate email address" do + User.create(firstname: 'Hector', + lastname: 'Felix', + email: 'test@gmail.com') + user = User.create(firstname: 'Angela', + lastname: 'Felix', + email: 'test@gmail.com') + expect(user).to have(1).errors_on(:email) + end + it "returns an user's full name as a string" end
Add test 'invalid with duplicate email addres.
diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index abc1234..def5678 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -12,7 +12,7 @@ expect(new_user.uid).to eq("12345678910") expect(new_user.first_name).to eq("Jesse") - expect(new_user.oauth_expires_at).to eq(auth[:credentials][:expires_at]) + expect(new_user.token).to eq("abcdefg12345") end describe 'associations' do
Update test to look for different user attributes
diff --git a/spec/toy/plugins_spec.rb b/spec/toy/plugins_spec.rb index abc1234..def5678 100644 --- a/spec/toy/plugins_spec.rb +++ b/spec/toy/plugins_spec.rb @@ -31,9 +31,9 @@ end it "adds plugins to classes declared after plugin was called" do - create_constant('Move') - Move.foo.should == 'foo' - Move.new.bar.should == 'bar' + klass = Class.new { include Toy::Store } + klass.foo.should == 'foo' + klass.new.bar.should == 'bar' end end -end+end
Switch to plain class instead of constant stuff for plugin spec.
diff --git a/app/controllers/spree/products_controller_decorator.rb b/app/controllers/spree/products_controller_decorator.rb index abc1234..def5678 100644 --- a/app/controllers/spree/products_controller_decorator.rb +++ b/app/controllers/spree/products_controller_decorator.rb @@ -5,7 +5,7 @@ def can_show_product @product ||= Spree::Product.find_by_permalink!(params[:id]) if @product.stores.empty? || !@product.stores.include?(current_store) - render :file => "#{::Rails.root}/public/404", :status => 404, :formats => [:html] + raise ActiveRecord::RecordNotFound end end
Raise an ActiveRecord::RecordNotFound exception in ProductsController By rendering the 404 template, it renders within the layout and looks ugly. Raising an AR::RecordNotFound exception here will render the 404 page normally.
diff --git a/config/initializers/stackdriver.rb b/config/initializers/stackdriver.rb index abc1234..def5678 100644 --- a/config/initializers/stackdriver.rb +++ b/config/initializers/stackdriver.rb @@ -5,6 +5,7 @@ # is private and you can't override the defaults? sampler.send(:initialize, path_blacklist: ["/_ah/health", "/healthz", "/healthcheck"].freeze, qps: 0.01) config.sampler = sampler + config.notifications << 'cache_read.active_support' end Google::Cloud::ErrorReporting.configure do |config|
Enable tracing of memcache reads
diff --git a/spec/acceptance/support/sphinx_controller.rb b/spec/acceptance/support/sphinx_controller.rb index abc1234..def5678 100644 --- a/spec/acceptance/support/sphinx_controller.rb +++ b/spec/acceptance/support/sphinx_controller.rb @@ -33,11 +33,12 @@ rescue Riddle::CommandFailedError => error puts <<-TXT -The Sphinx #{type} command failed: +The Sphinx start command failed: Command: #{error.command_result.command} Status: #{error.command_result.status} Output: #{error.command_result.output} TXT + raise error end def stop
Fix error handling - no type variable, still raise error.
diff --git a/lib/data_mapper/validation/rule/primitive_type.rb b/lib/data_mapper/validation/rule/primitive_type.rb index abc1234..def5678 100644 --- a/lib/data_mapper/validation/rule/primitive_type.rb +++ b/lib/data_mapper/validation/rule/primitive_type.rb @@ -12,6 +12,8 @@ property = get_resource_property(resource, attribute_name) value = resource.validation_property_value(attribute_name) + # FIXME: Deprecation message said Property#valid? was replaced + # with Property#value_dumped? but IMHO value_loaded? would be correct here? value.nil? || property.value_dumped?(value) end
Add FIXME at value_dumped? vs value_loaded?
diff --git a/lib/mumuki/laboratory/mailers/message_delivery.rb b/lib/mumuki/laboratory/mailers/message_delivery.rb index abc1234..def5678 100644 --- a/lib/mumuki/laboratory/mailers/message_delivery.rb +++ b/lib/mumuki/laboratory/mailers/message_delivery.rb @@ -10,6 +10,6 @@ private def in_rake_task? - defined? Rake.application + Rake.respond_to? :application end end
Fix rake task not being detected properly
diff --git a/lib/petra/proxies/active_record_relation_proxy.rb b/lib/petra/proxies/active_record_relation_proxy.rb index abc1234..def5678 100644 --- a/lib/petra/proxies/active_record_relation_proxy.rb +++ b/lib/petra/proxies/active_record_relation_proxy.rb @@ -3,6 +3,8 @@ class ActiveRecordRelationProxy < Petra::Proxies::ObjectProxy CLASS_NAMES = %w(ActiveRecord::Relation).freeze + include Enumerable + include Petra::Proxies::EnumerableProxy::InstanceMethods # # Method which is called e.g. by Model/Relation.all.
Fix for broken enumerable methods in ActiveRecordRelationProxy
diff --git a/app/controllers/contacts_controller.rb b/app/controllers/contacts_controller.rb index abc1234..def5678 100644 --- a/app/controllers/contacts_controller.rb +++ b/app/controllers/contacts_controller.rb @@ -14,7 +14,6 @@ expose(:contacts) { department. contacts. - ungrouped. for_listing. decorate }
Include all contacts in the listing We're removing the grouping.
diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index abc1234..def5678 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -5,9 +5,12 @@ end def create - user = User.find_by_email(params[:email]) + email = Digest::SHA1.hexdigest params[:email].to_s + pass = Digest::SHA1.hexdigest params[:password] + + user = User.find_by_email(email) # If the user exists AND the password entered is correct. - if user && user.authenticate(params[:password]) + if user && user.authenticate(pass) # Save the user id inside the browser cookie. This is how we keep the user # logged in when they navigate around our website. session[:user_id] = user.id
Use SHA1 for login page
diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index abc1234..def5678 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -1,36 +1,36 @@ class SessionsController < ApplicationController + def create + if Artist.find_by(email: params[:session][:email]).present? + @user = Artist.find_by(email: params[:session][:email]) + if @user && @user.authenticate(params[:session][:password]) + session[:artist_id] = @user.id + redirect_to artist_path(@user) + else + # render json: "{error: 'Invalid email/password combination'}" + redirect_to root_path + end - def create - if Artist.find_by(email: params[:session][:email]).present? - user = Artist.find_by(email: params[:session][:email]) - if user && user.authenticate(params[:session][:password]) - session[:artist_id] = user.id - redirect_to artist_path(user) - else - redirect_to '/login' - end - - elsif Organization.find_by(email: params[:session][:email]).present? - user = Organization.find_by(email: params[:session][:email]) - if user && user.authenticate(params[:session][:password]) - session[:organization_id] = user.id - redirect_to organization_path(user) - else - redirect_to '/login' - end - else - flash.now[:danger] = 'Invalid email/password combination' - redirect_to '/login' - end + elsif Organization.find_by(email: params[:session][:email]).present? + @user = Organization.find_by(email: params[:session][:email]) + if @user && @user.authenticate(params[:session][:password]) + session[:organization_id] = @user.id + redirect_to organization_path(@user) + else + # render json: "{error: 'Invalid email/password combination'}" + redirect_to root_path + end + else + # render json: "{error: 'Invalid email/password combination'}" + redirect_to root_path + end end def destroy if session[:artist_id] - session[:artist_id] = nil + session[:artist_id] = nil else session[:organization_id] = nil end - redirect_to root_path + redirect_to root_path end - end
Add silent fail on failed login
diff --git a/webapp/spec/models/participations_risk_factor_spec.rb b/webapp/spec/models/participations_risk_factor_spec.rb index abc1234..def5678 100644 --- a/webapp/spec/models/participations_risk_factor_spec.rb +++ b/webapp/spec/models/participations_risk_factor_spec.rb @@ -29,6 +29,9 @@ it "should validate expected delivery date" do @risk_factor.should validate_date(:pregnancy_due_date) + @risk_factor.pregnancy_due_date = @event.created_at - 1.day + @risk_factor.save + @risk_factor.errors.on(:pregnancy_due_date).should =~ /must be on or after/ end end
Revert "Removes validation on expected delivery date" This reverts commit f3f12925cfa1418ac7348abcc9049655c3b7599d.
diff --git a/example/rails/config/initializers/rack-escrow.rb b/example/rails/config/initializers/rack-escrow.rb index abc1234..def5678 100644 --- a/example/rails/config/initializers/rack-escrow.rb +++ b/example/rails/config/initializers/rack-escrow.rb @@ -1,6 +1,7 @@ Rails.application.config.middleware.use( Rack::Escrow::Middleware, - Rails.application) + Rails.application, + $redis) # ================================ # When using with Devise / Warden, @@ -10,5 +11,6 @@ # Rails.application.config.middleware.insert_before( # Warden::Manager, # Rack::Escrow::Middleware, -# Rails.application) +# Rails.application, +# $redis)
Add $redis argument to example initialization
diff --git a/config/initializers/s3_direct_upload.rb b/config/initializers/s3_direct_upload.rb index abc1234..def5678 100644 --- a/config/initializers/s3_direct_upload.rb +++ b/config/initializers/s3_direct_upload.rb @@ -3,7 +3,7 @@ c.access_key_id = ENV['S3_KEY'] c.secret_access_key = ENV['S3_SECRET'] c.bucket = ENV['S3_BUCKET'] - c.region = "s3-eu-west-1" + c.region = ENV['S3_REGION'] end # Used for debugging
Use S3 region from env file
diff --git a/lib/bluecap/server.rb b/lib/bluecap/server.rb index abc1234..def5678 100644 --- a/lib/bluecap/server.rb +++ b/lib/bluecap/server.rb @@ -32,7 +32,6 @@ klass = Bluecap::Server.handlers.fetch(message.recipient, Bluecap::NullHandler) handler = klass.new(message.contents) handler.handle - handler.response end # Process a message received from a client, sending a response if
Fix bug, handler no longer has response method
diff --git a/lib/chiketto/event.rb b/lib/chiketto/event.rb index abc1234..def5678 100644 --- a/lib/chiketto/event.rb +++ b/lib/chiketto/event.rb @@ -46,7 +46,7 @@ private def self.find_attendees(id, params) - attendees = get "events/#{id}/attendees", params + get "events/#{id}/attendees", params end end end
Refactor method to remove unused variable
diff --git a/lib/current_scopes.rb b/lib/current_scopes.rb index abc1234..def5678 100644 --- a/lib/current_scopes.rb +++ b/lib/current_scopes.rb @@ -6,8 +6,7 @@ def current_course return unless current_user - @__current_course ||= current_user.courses.find_by(id: session[:course_id]) if session[:course_id] - @__current_course ||= current_user.default_course + @__current_course ||= CourseRouter.current_course_for(current_user, session[:course_id]) end def current_user_is_staff?
Use the CourseRouter to retrieve the current course
diff --git a/lib/holidays/rails.rb b/lib/holidays/rails.rb index abc1234..def5678 100644 --- a/lib/holidays/rails.rb +++ b/lib/holidays/rails.rb @@ -1,12 +1,16 @@ module Holidays class Holiday module Rails + extend ActiveSupport::Concern + + module ClassMethods + def model_name + ActiveModel::Name.new(Holidays::Holiday) + end + end + def to_key [parameterize(name)] - end - - def self.model_name - ActiveModel::Name.new(Holidays::Holiday) end def param_key
Use ActiveSupport::Concern for the Rails extensions
diff --git a/lib/pagerduty/base.rb b/lib/pagerduty/base.rb index abc1234..def5678 100644 --- a/lib/pagerduty/base.rb +++ b/lib/pagerduty/base.rb @@ -16,16 +16,11 @@ uri = URI.parse("https://#{@subdomain}.pagerduty.com/api/v1/#{path}") http = Net::HTTP.new(uri.host, uri.port) - - # This is probably stupid - query_string = "" - params.each do |key, val| - next unless val != nil - query_string << '&' unless key == params.keys.first - query_string << "#{URI.encode(key.to_s)}=#{URI.encode(params[key])}" + output = [] + params.each_pair do |key,val| + output << "#{URI.encode(key.to_s)}=#{URI.encode(val)}" end - uri.query = query_string - + uri.query = "?#{output.join("&")}" req = Net::HTTP::Get.new(uri.request_uri) res = http.get(uri.to_s, {
Fix when all of the parameters are not used
diff --git a/lib/rowling/client.rb b/lib/rowling/client.rb index abc1234..def5678 100644 --- a/lib/rowling/client.rb +++ b/lib/rowling/client.rb @@ -1,13 +1,12 @@- module Rowling class Client include HTTParty attr_accessor *Configuration::CONFIGURATION_KEYS - def initialize(options={}) + def initialize(args={}) Configuration::CONFIGURATION_KEYS.each do |key| - send("#{key}=", options[key]) + send("#{key}=", args[key]) end end @@ -15,25 +14,49 @@ template = Addressable::Template.new("http://api.usatoday.com/open/bestsellers/books{/segments*}{?query*}") end - def get_classes(options={}) - options[:api_key] = self.api_key - url = base_template.expand({ - segments: "classes", - query: options}) - class_response = HTTParty.get(url) + def get_classes(args={}) + class_response = make_request({segments: "classes"}) class_response["Classes"] end - def get_book(options={}) - options[:api_key] = self.api_key - isbn = options.delete(:isbn) + def get_book(args={}) + isbn = args.delete(:isbn) segments = ["titles"] segments << isbn if isbn - url = base_template.expand({ - segments: segments, - query: options}) - book_response = HTTParty.get(url) - Rowling::Book.new(book_response) + errors = [] + begin + book_response = make_request({segments: segments, query: args}) + rescue StandardError => e + if book_response.code == 503 && args[:isbn] + errors << "Book with ISBN #{args[:isbn]} not found, or you've made too many requests." + elsif book_response.code != 200 + errors << e.message + end + end + if errors.empty? + Rowling::Book.new(book_response) + else + puts errors.join("\n") + end + end + + def make_request(args={}) + if self.api_key + query = { api_key: self.api_key } + query.merge!(args[:options]) if args[:options] + url = base_template.expand({ + segments: args[:segments], + query: query}) + response = HTTParty.get(url) + if response.code != 200 + raise StandardError, "Request Failed. Code #{response.code}." + response + else + response + end + else + raise StandardError, "You must set an API key before making a request." + end end end end
Refactor and start doing some error handling
diff --git a/lib/chamber/rails/railtie.rb b/lib/chamber/rails/railtie.rb index abc1234..def5678 100644 --- a/lib/chamber/rails/railtie.rb +++ b/lib/chamber/rails/railtie.rb @@ -0,0 +1,13 @@+module Chamber +module Rails +class Railtie < ::Rails::Railtie + initializer 'chamber.load', before: :load_environment_config do + Chamber.load(:basepath => Rails.root.join('config')) + end + + rake_tasks do + load 'chamber/tasks/heroku.rake' + end +end +end +end
Add a Railtie which loads Chamber with the proper Rails config path and load the rake task
diff --git a/lib/capybara_webkit_builder.rb b/lib/capybara_webkit_builder.rb index abc1234..def5678 100644 --- a/lib/capybara_webkit_builder.rb +++ b/lib/capybara_webkit_builder.rb @@ -1,4 +1,5 @@ require "fileutils" +require "rbconfig" module CapybaraWebkitBuilder extend self @@ -11,7 +12,7 @@ def makefile qmake_binaries = ['qmake', 'qmake-qt4'] qmake = qmake_binaries.detect { |qmake| system("which #{qmake}") } - case RUBY_PLATFORM + case RbConfig::CONFIG['host_os'] when /linux/ system("#{qmake} -spec linux-g++") when /freebsd/
Choose platform more reliably. (Works with Jruby.)
diff --git a/lib/dolphy/configurations.rb b/lib/dolphy/configurations.rb index abc1234..def5678 100644 --- a/lib/dolphy/configurations.rb +++ b/lib/dolphy/configurations.rb @@ -9,5 +9,9 @@ def [](element) configurations[element] end + + def []=(key, value) + configurations[key] = value + end end end
Add ability to set the hash as well.
diff --git a/benchmarks/turkish_word_recognition.rb b/benchmarks/turkish_word_recognition.rb index abc1234..def5678 100644 --- a/benchmarks/turkish_word_recognition.rb +++ b/benchmarks/turkish_word_recognition.rb @@ -0,0 +1,12 @@+require 'benchmark' +require 'turkish_stemmer' + +Benchmark.bmbm(7) do |x| + x.report('regex') do + 10000.times { "aaaaaaaaaa" =~ /^[#{TurkishStemmer::ALPHABET}]+$/ } + end + + x.report('loop') do + 10000.times { "aaaaaaaaaa".chars.to_a.all? { |c| TurkishStemmer::ALPHABET.include?(c) } } + end +end
Add benchmark about turkish word recongition
diff --git a/lib/klam/primitives/lists.rb b/lib/klam/primitives/lists.rb index abc1234..def5678 100644 --- a/lib/klam/primitives/lists.rb +++ b/lib/klam/primitives/lists.rb @@ -11,7 +11,7 @@ # 1. Its performance is better # 2. It can be read directly by the Ruby reader EMPTY_LIST = nil - CONS_TAG = ":[CONS]" + CONS_TAG = :"[CONS]" def cons(head, tail) [head, tail, CONS_TAG]
Use a symbol for the type tag
diff --git a/lib/peek_a_view/tools/yslow.rb b/lib/peek_a_view/tools/yslow.rb index abc1234..def5678 100644 --- a/lib/peek_a_view/tools/yslow.rb +++ b/lib/peek_a_view/tools/yslow.rb @@ -6,11 +6,11 @@ class YSlow < Checker def check(uri) - system "phantomjs '#{yslow_script}' -f tap '#{uri}'" + system "phantomjs '#{yslow_script}' -f plain '#{uri}'" end def report(uri) - system "phantomjs '#{yslow_script}' -f tap '#{uri}' > '#{report_file(uri)}'" + system "phantomjs '#{yslow_script}' -f junit '#{uri}' > '#{report_file(uri)}'" end private @@ -24,7 +24,7 @@ end def report_file(uri) - report_path(uri, '.tap') + report_path(uri, '.xml') end end end
Write reports in junit format.
diff --git a/app/controllers/shoppe/customers_controller.rb b/app/controllers/shoppe/customers_controller.rb index abc1234..def5678 100644 --- a/app/controllers/shoppe/customers_controller.rb +++ b/app/controllers/shoppe/customers_controller.rb @@ -47,7 +47,7 @@ private def safe_params - params[:customer].permit(:first_name, :last_name, :company, :email, :phone, :mobile) + params[:customer].permit(:first_name, :last_name, :company, :email, :phone, :mobile, :business_details) end end end
Add :business_details to permit parameters
diff --git a/post-install.rb b/post-install.rb index abc1234..def5678 100644 --- a/post-install.rb +++ b/post-install.rb @@ -3,14 +3,20 @@ require 'ftools' require 'find' -$docdir = nil +if defined?(ToplevelInstaller) && self.class == ToplevelInstaller + $docdir = nil -# Where to install the documentation -def docdir - return $docdir if $docdir - dir = get_config('doc-dir')+File::SEPARATOR - dir.sub!(/\A$prefix/, get_config('prefix')) - $docdir = dir + # Where to install the documentation + def docdir + return $docdir if $docdir + dir = get_config('doc-dir')+'/' + dir.sub!(/\A$prefix/, get_config('prefix')) + $docdir = dir + end +else + def docdir + return ARGV[0] + end end puts "\npost-install.rb: installing documentation..."
Add code to allow command-line execution for debugging
diff --git a/Casks/thunderbird-beta.rb b/Casks/thunderbird-beta.rb index abc1234..def5678 100644 --- a/Casks/thunderbird-beta.rb +++ b/Casks/thunderbird-beta.rb @@ -2,9 +2,10 @@ version '38.0b4' sha256 '07e8d88b0a1c37b9770f24b35e513fd27eefb7d34dca20236499692573739503' - url "https://download-installer.cdn.mozilla.net/pub/thunderbird/releases/#{version}/mac/en-US/Thunderbird%20#{version}.dmg" + url "https://download.mozilla.org/?product=thunderbird-#{version}&os=osx&lang=en-US" homepage 'https://www.mozilla.org/en-US/thunderbird/all-beta.html' license :mpl + tags :vendor => 'Mozilla' app 'Thunderbird.app' end
Add tag stanza to Thunderbird-beta Update URL
diff --git a/Casks/thunderbird-beta.rb b/Casks/thunderbird-beta.rb index abc1234..def5678 100644 --- a/Casks/thunderbird-beta.rb +++ b/Casks/thunderbird-beta.rb @@ -1,8 +1,8 @@ class ThunderbirdBeta < Cask - version '32.0b1' - sha256 '0f66e9cb452293e248d92c9a156c0b81c50e81ba1107922ab6f8b555934e83d3' + version '33.0b1' + sha256 '96db91d29cf5ec4e01e1c877eb804c9894e699e57c0d6d55219b1f53cbdb0dab' - url 'https://download-installer.cdn.mozilla.net/pub/thunderbird/releases/32.0b1/mac/en-US/Thunderbird%2032.0b1.dmg' + url 'https://download-installer.cdn.mozilla.net/pub/thunderbird/releases/33.0b1/mac/en-US/Thunderbird%2033.0b1.dmg' homepage 'https://www.mozilla.org/en-US/thunderbird/all-beta.html' app 'Thunderbird.app'
Update Thunderbird Beta to 33.0b1
diff --git a/db/migrate/20160805145635_remove_local_interactions.rb b/db/migrate/20160805145635_remove_local_interactions.rb index abc1234..def5678 100644 --- a/db/migrate/20160805145635_remove_local_interactions.rb +++ b/db/migrate/20160805145635_remove_local_interactions.rb @@ -0,0 +1,9 @@+class RemoveLocalInteractions < Mongoid::Migration + def self.up + LocalAuthority.all.each { |la| la.unset(:local_interactions) } + end + + def self.down + # No down, this is destructive + end +end
Remove local_interactions from the db Now that we don't import local interactions and have removed them from govuk_content_models we can also remove them from the database with a migration.
diff --git a/lib/tasks/db_test_prepare.rake b/lib/tasks/db_test_prepare.rake index abc1234..def5678 100644 --- a/lib/tasks/db_test_prepare.rake +++ b/lib/tasks/db_test_prepare.rake @@ -1,7 +1,7 @@ namespace :db do namespace :test do - def common_stuff + def load_common_data Rake::Task['db:backup:load_probe_configurations'].invoke Rake::Task['db:backup:load_ri_grade_span_expectations'].invoke Rake::Task['app:jnlp:generate_maven_jnlp_resources'].invoke('false') @@ -10,7 +10,7 @@ desc 'after completing db:test:prepare load probe configurations' task :prepare do ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test']) - common_stuff + load_common_data end @@ -21,7 +21,7 @@ Rake::Task['db:create'].invoke Rake::Task['db:schema:load'].invoke - common_stuff + load_common_data require File.expand_path('../../../spec/spec_helper.rb', __FILE__) APP_CONFIG[:password_for_default_users] = 'password'
Change function name to load_common_data. - Change function name to load_common_data.
diff --git a/lib/tasks/metadata_tagger.rake b/lib/tasks/metadata_tagger.rake index abc1234..def5678 100644 --- a/lib/tasks/metadata_tagger.rake +++ b/lib/tasks/metadata_tagger.rake @@ -1,7 +1,7 @@ require 'rummager' desc "Apply metadata from the json file" -task :tag_json_metadata do - file_path = File.join(settings.root, '../../config/metadata.json') +task :tag_metadata do + file_path = File.join(settings.root, '../../config/metadata.csv') Indexer::MetadataTagger.amend_indexes_for_file(file_path) end
Update the rake task to use csv suffix
diff --git a/lib/tweetwine/option_parser.rb b/lib/tweetwine/option_parser.rb index abc1234..def5678 100644 --- a/lib/tweetwine/option_parser.rb +++ b/lib/tweetwine/option_parser.rb @@ -12,9 +12,10 @@ end def parse(args = ARGV) + @parser.order! args + result = @options.dup @options.clear - @parser.order! args - @options.dup + result rescue ::OptionParser::ParseError => e raise CommandLineError, e.message end
Fix memory leak after parsing options
diff --git a/lib/virtualbox/ext/platform.rb b/lib/virtualbox/ext/platform.rb index abc1234..def5678 100644 --- a/lib/virtualbox/ext/platform.rb +++ b/lib/virtualbox/ext/platform.rb @@ -20,7 +20,7 @@ end def platform - Config::CONFIG["host_os"].downcase + RbConfig::CONFIG["host_os"].downcase end end end
Fix Config deprecation to RbConfig
diff --git a/flowvel2d.rb b/flowvel2d.rb index abc1234..def5678 100644 --- a/flowvel2d.rb +++ b/flowvel2d.rb @@ -8,6 +8,8 @@ depends_on :fortran def install + inreplace "Makefile", /gfortran/, "\${FC}" + system "make" bin.install "2dflowvel" end
Replace gfortran with FC environment var.
diff --git a/documents/lib/social_stream/views/toolbar/documents.rb b/documents/lib/social_stream/views/toolbar/documents.rb index abc1234..def5678 100644 --- a/documents/lib/social_stream/views/toolbar/documents.rb +++ b/documents/lib/social_stream/views/toolbar/documents.rb @@ -15,7 +15,7 @@ when :profile items << { :key => :documents, - :name => link_to(image_tag("btn/btn_resource.png",:class =>"menu_icon")+t("document.title.other"), + :html => link_to(image_tag("btn/btn_resource.png",:class =>"menu_icon")+t("document.title.other"), [options[:subject], Document.new], :id => "toolbar_menu-documents") }
Fix files toolbar menu entry
diff --git a/models/team.rb b/models/team.rb index abc1234..def5678 100644 --- a/models/team.rb +++ b/models/team.rb @@ -11,9 +11,8 @@ has_many :records def self.number(team_number) - raise ArgumentError, "Must supply a team number!" unless team_number.is_a?(Integer) - - return self.where(number: team_number).first + # Team.find_by number: team_number + find_by number: team_number end validates :number, :location, :name, presence: true
Use find_by instead of where We are getting one element, so we might as well use a function that retrieves one element. This is comparable to using `find` instead of `select.first`. Sorry for being a jerk.
diff --git a/ci_environment/riak/recipes/default.rb b/ci_environment/riak/recipes/default.rb index abc1234..def5678 100644 --- a/ci_environment/riak/recipes/default.rb +++ b/ci_environment/riak/recipes/default.rb @@ -6,7 +6,7 @@ end apt_repository 'basho-riak' do - uri 'https://packagecloud.io/basho/riak/' + uri 'https://packagecloud.io/basho/riak/ubuntu/' distribution node["lsb"]["codename"] components ["main"] key 'https://packagecloud.io/gpg.key'
Revert "Fix Riak repository URL" This reverts commit ef33d3b432d4dda78374906ebcbcf3d6da465af6.
diff --git a/devise_g5_authenticatable.gemspec b/devise_g5_authenticatable.gemspec index abc1234..def5678 100644 --- a/devise_g5_authenticatable.gemspec +++ b/devise_g5_authenticatable.gemspec @@ -18,7 +18,7 @@ spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] - spec.add_dependency 'devise', '~> 3.0' + spec.add_dependency 'devise', '~> 3.5' spec.add_dependency 'g5_authentication_client', '~> 0.2' spec.add_dependency 'omniauth-g5', '~> 0.1' end
Upgrade dependency on devise to ~> 3.5
diff --git a/spec/features/show_game_pairings_spec.rb b/spec/features/show_game_pairings_spec.rb index abc1234..def5678 100644 --- a/spec/features/show_game_pairings_spec.rb +++ b/spec/features/show_game_pairings_spec.rb @@ -0,0 +1,17 @@+require "rails_helper" + +RSpec.describe "show tournament round pairings" do + context "Any vistor to the website" do + let(:tournament) { create :tournament } + let(:round) { create :round, tournament: tournament } + let(:games) { create_list } + fit "can navigate to a page showing the games for a tournament" do + round_link = "Round #{round.number}" + visit tournament_path(tournament) + click_on(round_link) + expect(page).to have_selector + end + + end + +end
Add show game pairings feature test
diff --git a/spec/helpers/admin/orders_helper_spec.rb b/spec/helpers/admin/orders_helper_spec.rb index abc1234..def5678 100644 --- a/spec/helpers/admin/orders_helper_spec.rb +++ b/spec/helpers/admin/orders_helper_spec.rb @@ -7,13 +7,13 @@ let(:order) { create(:order) } it "selects eligible adjustments" do - adjustment = create(:adjustment, adjustable: order, amount: 1) + adjustment = create(:adjustment, order: order, adjustable: order, amount: 1) expect(helper.order_adjustments_for_display(order)).to eq [adjustment] end it "filters shipping method adjustments" do - create(:adjustment, adjustable: order, amount: 1, originator_type: "Spree::ShippingMethod") + create(:adjustment, order: order, adjustable: order, amount: 1, originator_type: "Spree::ShippingMethod") expect(helper.order_adjustments_for_display(order)).to eq [] end
Improve OrdersHelper spec and delete dead code The removed test here was checking for adjustments that have an amount of zero and are eligible. If the amount is zero, it will already be marked as ineligible.
diff --git a/spec/lib/mailchimp_error_handler_spec.rb b/spec/lib/mailchimp_error_handler_spec.rb index abc1234..def5678 100644 --- a/spec/lib/mailchimp_error_handler_spec.rb +++ b/spec/lib/mailchimp_error_handler_spec.rb @@ -0,0 +1,70 @@+require 'spec_helper' + +describe MailchimpErrorHandler, type: :module do + let(:retry_attempt) { 2 } + + SpreeMarketing::CONFIG = { Rails.env => { campaign_defaults: { from_email: 'a@test.com' }} } + + class TestJob < ActiveJob::Base + include MailchimpErrorHandler + + def perform + raise Gibbon::MailChimpError + end + end + + subject(:job) { TestJob.new } + + describe 'constants' do + it 'RETRY_LIMIT equals to the limit for retrying failed job' do + expect(MailchimpErrorHandler::RETRY_LIMIT).to eq 5 + end + end + + describe '#retry_attempt' do + it 'when unassigned returns default value' do + expect(job.retry_attempt).to eq(1) + end + + it 'when assigned returns assigned value' do + job.instance_variable_set(:@retry_attempt, retry_attempt) + expect(job.retry_attempt).to eq retry_attempt + end + end + + describe '#should_retry?' do + it 'equals to true when should retry job' do + expect(job.should_retry?(job.retry_attempt)).to eq(true) + end + it 'equals to false when should not retry job' do + job.instance_variable_set(:@retry_attempt, MailchimpErrorHandler::RETRY_LIMIT + 1) + expect(job.should_retry?(job.retry_attempt)).to eq(false) + end + end + + describe '#serialize' do + it 'adds retry_attempt key to serialized arguments' do + expect(job.serialize.keys).to include('retry_attempt') + end + end + + describe '#deserialize' do + it 'defines retry_attempt attribute on job' do + job.instance_variable_set(:@retry_attempt, retry_attempt) + job.deserialize(job.serialize) + expect(job.retry_attempt).to eq retry_attempt + end + end + + describe '#notify_admin' do + it 'Spree::Marketing::MailchimpErrorNotifier to receive notify_failure' do + expect { job.notify_admin(Gibbon::MailChimpError.new) }.to change { ActionMailer::Base.deliveries.count }.by 1 + end + end + + describe '#rescue_with_handler' do + it 'notifies admin after more than RETRY_LIMIT failed attempts' do + expect { job.class.perform_now }.to change { ActionMailer::Base.deliveries.count }.by 1 + end + end +end
Add rspecs for mailchimp error handler
diff --git a/spec/unit/cookbook/gem_installer_spec.rb b/spec/unit/cookbook/gem_installer_spec.rb index abc1234..def5678 100644 --- a/spec/unit/cookbook/gem_installer_spec.rb +++ b/spec/unit/cookbook/gem_installer_spec.rb @@ -0,0 +1,70 @@+require "spec_helper" +require "bundler/dsl" + +describe Chef::Cookbook::GemInstaller do + let(:cookbook_collection) do + { + test: double( + :cookbook, + metadata: double( + :metadata, + gems: [["httpclient"], ["nokogiri"]] + ) + ), + test2: double( + :cookbook, + metadata: double( + :metadata, + gems: [["httpclient", ">= 2.0"]] + ) + ), + test3: double( + :cookbook, + metadata: double( + :metadata, + gems: [["httpclient", ">= 1.0"]] + ) + ), + } + end + + let(:gem_installer) do + described_class.new(cookbook_collection, Chef::EventDispatch::Dispatcher.new) + end + + let(:gemfile) do + StringIO.new + end + + let(:shell_out) do + double(:shell_out, stdout: "") + end + + let(:bundler_dsl) do + b = Bundler::Dsl.new + b.instance_eval(gemfile.string) + b + end + + before(:each) do + # Prepare mocks: using a StringIO instead of a File + expect(Dir).to receive(:mktmpdir).and_yield("") + expect(File).to receive(:open).and_yield(gemfile) + expect(gemfile).to receive(:path).and_return("") + expect(IO).to receive(:read).and_return("") + expect(gem_installer).to receive(:shell_out!).and_return(shell_out) + + end + + it "generates a valid Gemfile" do + expect { gem_installer.install }.to_not raise_error + + expect { bundler_dsl }.to_not raise_error + end + + it "generate a Gemfile with all constraints" do + expect { gem_installer.install }.to_not raise_error + + expect(bundler_dsl.dependencies.find { |d| d.name == "httpclient" }.requirements_list.length).to eql(2) + end +end
Add unit test for gem installer Change-Id: Ibf4a53b9f687882f84932433cc3d45e084e3a29e Signed-off-by: Maxime Brugidou <64f9cd4d18ae4d76ae69a984bce9896c188d1768@criteo.com>
diff --git a/tests/hp/requests/network/security_group_tests.rb b/tests/hp/requests/network/security_group_tests.rb index abc1234..def5678 100644 --- a/tests/hp/requests/network/security_group_tests.rb +++ b/tests/hp/requests/network/security_group_tests.rb @@ -0,0 +1,48 @@+Shindo.tests('HP::Network | networking security group requests', ['hp', 'networking', 'securitygroup']) do + + @security_group_format = { + 'id' => String, + 'name' => String, + 'description' => String, + 'tenant_id' => String, + 'security_group_rules' => [Hash] + } + + tests('success') do + + @sec_group_id = nil + + tests("#create_security_group('fog_security_group', 'tests group')").formats(@security_group_format) do + attributes = {:name => 'fog_security_group', :description => 'tests group'} + data = HP[:network].create_security_group(attributes).body['security_group'] + @sec_group_id = data['id'] + data + end + + tests("#get_security_group('#{@sec_group_id}')").formats(@security_group_format) do + HP[:network].get_security_group(@sec_group_id).body['security_group'] + end + + tests("#list_security_groups").formats('security_groups' => [@security_group_format]) do + HP[:network].list_security_groups.body + end + + tests("#delete_security_group('#{@sec_group_id}')").succeeds do + HP[:network].delete_security_group(@sec_group_id) + end + + end + + tests('failure') do + + tests("#get_security_group(0)").raises(Fog::HP::Network::NotFound) do + HP[:network].get_security_group(0) + end + + tests("#delete_security_group(0)").raises(Fog::HP::Network::NotFound) do + HP[:network].delete_security_group(0) + end + + end + +end
[hp|network] Add tests for request methods for networking security groups.
diff --git a/oembed.gemspec b/oembed.gemspec index abc1234..def5678 100644 --- a/oembed.gemspec +++ b/oembed.gemspec @@ -15,7 +15,8 @@ gem.require_paths = ["lib"] gem.version = Oembed::VERSION + gem.add_development_dependency 'fakeweb' + gem.add_development_dependency 'rake' gem.add_development_dependency 'rspec' gem.add_development_dependency 'simplecov' - gem.add_development_dependency 'fakeweb' end
Add Rake to development dependecies
diff --git a/spec/lib/tumblfetch/cli_spec.rb b/spec/lib/tumblfetch/cli_spec.rb index abc1234..def5678 100644 --- a/spec/lib/tumblfetch/cli_spec.rb +++ b/spec/lib/tumblfetch/cli_spec.rb @@ -9,10 +9,11 @@ end describe Tumblfetch::CLI, '#init' do + let(:output) { capture(:stdout) { subject.init } } + context 'when ~/.tumblr is nonexistent' do it 'should print execute `tumblr`' do File.stub(:exist?).and_return(false) - output = capture(:stdout) { subject.init } expect(output).to include Tumblfetch::CLI::EXECUTE_TUMBLR_MSG end end @@ -20,12 +21,11 @@ context 'when ~/.tumblr exist' do context 'when .tumblfetch is nonexistent' do it 'should generate a .tumblfetch' do - output = capture(:stdout) { subject.init } + subject.init File.exist?('./.tumblfetch').should be_true end it 'should print success message' do - output = capture(:stdout) { subject.init } expect(output).to include Tumblfetch::CLI::SETTINGS_GENERATED_MSG end end @@ -33,7 +33,6 @@ context 'when .tumblfetch already exist' do it 'should print warning message' do File.open('./.tumblfetch', 'w').close - output = capture(:stdout) { subject.init } expect(output).to include Tumblfetch::CLI::SETTINGS_EXIST_MSG end end
Use let for remove repetition
diff --git a/test/controllers/articles_controller_test.rb b/test/controllers/articles_controller_test.rb index abc1234..def5678 100644 --- a/test/controllers/articles_controller_test.rb +++ b/test/controllers/articles_controller_test.rb @@ -18,30 +18,30 @@ test "should create article" do assert_difference('Article.count') do - post :create, article: { body: @article.body, title: @article.title } + post :create, params: { article: { body: @article.body, title: @article.title } } end assert_redirected_to article_path(assigns(:article)) end test "should show article" do - get :show, id: @article + get :show, params: { id: @article } assert_response :success end test "should get edit" do - get :edit, id: @article + get :edit, params: { id: @article } assert_response :success end test "should update article" do - patch :update, id: @article, article: { body: @article.body, title: @article.title } + patch :update, params: { id: @article, article: { body: @article.body, title: @article.title } } assert_redirected_to article_path(assigns(:article)) end test "should destroy article" do assert_difference('Article.count', -1) do - delete :destroy, id: @article + delete :destroy, params: { id: @article } end assert_redirected_to articles_path
Add params to controller tests
diff --git a/Casks/geany.rb b/Casks/geany.rb index abc1234..def5678 100644 --- a/Casks/geany.rb +++ b/Casks/geany.rb @@ -1,6 +1,6 @@ cask 'geany' do - version '1.26' - sha256 'baa663b085f9f187fc1884f274a3528b816bf5b9686072d6920e148c7c9461b8' + version '1.27' + sha256 'ce629ba35aebbd71e054c3cd32984abc41f368f0d578864a2c1b3662f9b00ecc' url "http://download.geany.org/geany-#{version}_osx.dmg" name 'Geany'
Update Geany to version 1.27
diff --git a/Casks/java6.rb b/Casks/java6.rb index abc1234..def5678 100644 --- a/Casks/java6.rb +++ b/Casks/java6.rb @@ -1,14 +1,12 @@ cask :v1 => 'java6' do version '1.6.0_65' - sha256 '97bc9b3c47af1f303710c8b15f2bcaedd6b40963c711a18da8eac1e49690a8a0' + sha256 '1b7b88c7c7ca3a1c50eacee1977dee974a50157ff7c88d0e73902bd98fc58a86' - url 'http://support.apple.com/downloads/DL1572/en_US/JavaForOSX2014-001.dmg' - homepage 'http://support.apple.com/kb/DL1572' + url 'https://support.apple.com/downloads/DL1572/en_US/javaforosx.dmg' + homepage 'https://support.apple.com/kb/DL1572' license :unknown pkg 'JavaForOSX.pkg' uninstall :pkgutil => 'com.apple.pkg.JavaForMacOSX107' - - depends_on :macos => '<= :yosemite' end
Use the new package for java 6 that works on el capitan with rootless mode enabled.
diff --git a/app/workers/extract_extension_basic_metadata_worker.rb b/app/workers/extract_extension_basic_metadata_worker.rb index abc1234..def5678 100644 --- a/app/workers/extract_extension_basic_metadata_worker.rb +++ b/app/workers/extract_extension_basic_metadata_worker.rb @@ -5,7 +5,7 @@ @extension = Extension.find(extension_id) repo = octokit.repo(@extension.github_repo) - @extension.update_attributes( + Extension.where(id: @extension.id).update_all( extension_followers_count: repo[:stargazers_count], issues_url: "https://github.com/#{@extension.github_repo}/issues" )
Use update_all to get around readonly counter cache
diff --git a/lib/omniauth/strategies/discord.rb b/lib/omniauth/strategies/discord.rb index abc1234..def5678 100644 --- a/lib/omniauth/strategies/discord.rb +++ b/lib/omniauth/strategies/discord.rb @@ -13,7 +13,7 @@ :token_url => 'oauth2/token' } - option :authorize_options, [:scope] + option :authorize_options, [:scope, :permissions] uid { raw_info['id'] }
Add the extra authorize option
diff --git a/features/step_definitions/file_steps.rb b/features/step_definitions/file_steps.rb index abc1234..def5678 100644 --- a/features/step_definitions/file_steps.rb +++ b/features/step_definitions/file_steps.rb @@ -1,7 +1,3 @@-Given /^a file called '(.*)'$/ do |virtual_path, content| - create_file expand(virtual_path), expand(content) -end - Given /^an executable file named "(.*)" with:$/ do |file_path, content| steps %Q{ Given a file named "#{file_path}" with:
Delete a legacy step for files
diff --git a/test/test_application.rb b/test/test_application.rb index abc1234..def5678 100644 --- a/test/test_application.rb +++ b/test/test_application.rb @@ -1,6 +1,15 @@ require_relative "test_helper" +class TestController < Rulers::Controller + def index + "Hello" + end +end + class TestApp < Rulers::Application + def get_controller_and_action(env) + [TestController, "index"] + end end class RulersAppTest < Test::Unit::TestCase @@ -11,7 +20,7 @@ end def test_request - get "/" + get "/example/route" assert last_response.ok? body = last_response.body @@ -19,7 +28,7 @@ end def test_content - get "/" + get "/example/route" assert last_response.content_type =='text/html' end
Update tests for Chap 4 Exercise 1
diff --git a/lib/weka/classifiers/evaluation.rb b/lib/weka/classifiers/evaluation.rb index abc1234..def5678 100644 --- a/lib/weka/classifiers/evaluation.rb +++ b/lib/weka/classifiers/evaluation.rb @@ -1,4 +1,5 @@ require 'weka/class_builder' +require 'weka/concerns' module Weka module Classifiers @@ -6,6 +7,7 @@ class Evaluation include ClassBuilder + include Weka::Concerns::Persistent # Use both nomenclatures f_measure and fmeasure for consistency # due to jruby's auto method generation of 'fMeasure' to 'f_measure' and
Fix warning: singleton on non-persistent Java type
diff --git a/lib/ws_light/set/watermelon_set.rb b/lib/ws_light/set/watermelon_set.rb index abc1234..def5678 100644 --- a/lib/ws_light/set/watermelon_set.rb +++ b/lib/ws_light/set/watermelon_set.rb @@ -4,7 +4,7 @@ module Set # Creates a watermelon set, some green, some white, lots of red with a few red dots class WatermelonSet < ColorSet - def frame + def create_frame set = [] length_red = (0.72 * @length).to_i @@ -27,10 +27,14 @@ end end - set + type == :double ? set + set.reverse : set end - def pixel(number, _frame = 0) + def frame + @set ||= create_frame + end + + def pixel(number) frame[number] end end
[BUGFIX] Extend melon to second led strip
diff --git a/doorkeeper_assertion_flow.gemspec b/doorkeeper_assertion_flow.gemspec index abc1234..def5678 100644 --- a/doorkeeper_assertion_flow.gemspec +++ b/doorkeeper_assertion_flow.gemspec @@ -16,7 +16,7 @@ spec.require_paths = ['lib'] spec.add_dependency 'railties', '>= 4.0' - spec.add_dependency 'doorkeeper', '>= 2.0' + spec.add_dependency 'doorkeeper', '~> 2' spec.add_development_dependency 'bundler', '~> 1.6' spec.add_development_dependency 'rake', '~> 10.3'
Update doorkeeper version specifier to use 2.x
diff --git a/hubtime.gemspec b/hubtime.gemspec index abc1234..def5678 100644 --- a/hubtime.gemspec +++ b/hubtime.gemspec @@ -24,5 +24,4 @@ s.add_dependency("octokit", "~> 1.20") s.add_dependency("terminal-table", "~> 1.4") s.add_dependency("erubis", "~> 2.7") - s.add_dependency("hashie", "~> 1.2") end
Remove explicit dependency on hashie Octokit already depends on it.
diff --git a/app/models/spree/page.rb b/app/models/spree/page.rb index abc1234..def5678 100644 --- a/app/models/spree/page.rb +++ b/app/models/spree/page.rb @@ -1,5 +1,6 @@ module Spree class Page < ActiveRecord::Base + attr_accessible :title, :meta_keywords, :meta_description, :body, :permalink, :published validates :title, :presence => true validates :permalink, :uniqueness => true
Add attr_accessible to be compatible with rails 3.2.6+
diff --git a/roles/grifon.rb b/roles/grifon.rb index abc1234..def5678 100644 --- a/roles/grifon.rb +++ b/roles/grifon.rb @@ -15,6 +15,20 @@ :allow => ["2a00:5884::8"] }, :networking => { + :firewall => { + :inet6 => [ + { + :action => "ACCEPT", + :source => "net:[2a00:5884::7]", + :dest => "fw", + :proto => "tcp", + :dest_ports => "munin", + :source_ports => "1024:", + :rate_limit => "-", + :connection_limit => "-" + } + ] + }, :nameservers => ["2a00:5884::7", "8.8.8.8", "8.8.4.4"], :roles => { :external => {
Enable munin monitoring for Grifon machines
diff --git a/hippie.gemspec b/hippie.gemspec index abc1234..def5678 100644 --- a/hippie.gemspec +++ b/hippie.gemspec @@ -18,6 +18,4 @@ 'tests/hippie_test.rb', 'hippie.gemspec' ] - - s.add_development_dependency 'minitest', '>= 2.5', '< 5.0' end
Remove minitest as a development dependency
diff --git a/src/fieri/app/controllers/fieri/jobs_controller.rb b/src/fieri/app/controllers/fieri/jobs_controller.rb index abc1234..def5678 100644 --- a/src/fieri/app/controllers/fieri/jobs_controller.rb +++ b/src/fieri/app/controllers/fieri/jobs_controller.rb @@ -15,6 +15,7 @@ [:cookbook_name, :cookbook_version, :cookbook_artifact_url].each do |param| params.require(param) end + params end end end
Return the params, eh, instead of an array of the required params. The each block was returning the array of symbols, not the modified params object with required keys checked.
diff --git a/lib/core_ext/active_support_cache_store_ext.rb b/lib/core_ext/active_support_cache_store_ext.rb index abc1234..def5678 100644 --- a/lib/core_ext/active_support_cache_store_ext.rb +++ b/lib/core_ext/active_support_cache_store_ext.rb @@ -1,21 +1,27 @@-module ActiveSupport::Cache - class Store - def expire(options = {}) - tags = options[:tags] - cache_version = read("$cache_version").to_i - - write("$cache_version", cache_version + 1) +# This module extends cache class with some additional methods. +module ActiveSupport + module Cache + module StoreExt + def expire(options = {}) + tags = options[:tags] + cache_version = read("$cache_version").to_i + + write("$cache_version", cache_version + 1) + end + + def expire_tag_version + # $tag_version is bumped when the type of a tag is changed in Tags, if + # a new tag is created, or if a tag's post_count becomes nonzero. + incr("$tag_version") + end + + def incr(key) + val = read(key) + write(key, val.to_i + 1) + end end - - def expire_tag_version - # $tag_version is bumped when the type of a tag is changed in Tags, if - # a new tag is created, or if a tag's post_count becomes nonzero. - incr("$tag_version") - end - - def incr(key) - val = read(key) - write(key, val.to_i + 1) - end + Store.send :include, StoreExt + # DalliStore doesn't inherit Store, therefore it directly injected + DalliStore.send :include, StoreExt if defined? DalliStore end end
Fix for cache store since dalli doesn't extend Store anymore.
diff --git a/lib/optical/filters/at_least_one_end_unique.rb b/lib/optical/filters/at_least_one_end_unique.rb index abc1234..def5678 100644 --- a/lib/optical/filters/at_least_one_end_unique.rb +++ b/lib/optical/filters/at_least_one_end_unique.rb @@ -5,10 +5,11 @@ class Optical::Filters::AtLeastOneEndUnique < Optical::Filters::NullFilter def filter_to(output_bam) if ! @lib.is_paired? - raise ArgumentError.new("This filter only works for paired end data") + # A single end with at least one end unique, is really just only unique, duh + OnlyUnique.new(@lib,@name,@conf).filter_to(output_bam) + else + filter_through_awk_script([File.join(File.dirname(__FILE__),"paired_end_filters.awk"),"at_least_one_unique"], + output_bam,@conf.min_map_quality_score,true) end - - filter_through_awk_script([File.join(File.dirname(__FILE__),"paired_end_filters.awk"),"at_least_one_unique"], - output_bam,@conf.min_map_quality_score,true) end end
Allow AtLeastOneUnique filter for SE For single end, just treat it as only unique, now we can mix PE & SE in the same analysis config
diff --git a/lib/paperclip/storage/dropbox/url_generator.rb b/lib/paperclip/storage/dropbox/url_generator.rb index abc1234..def5678 100644 --- a/lib/paperclip/storage/dropbox/url_generator.rb +++ b/lib/paperclip/storage/dropbox/url_generator.rb @@ -24,7 +24,7 @@ private def user_id - @attachment_options[:dropbox_credentials][:user_id] + @attachment.dropbox_credentials[:user_id] end end
Fix dropbox credentials not working with Pathname Fixes #54
diff --git a/lib/stack_master/aws_driver/cloud_formation.rb b/lib/stack_master/aws_driver/cloud_formation.rb index abc1234..def5678 100644 --- a/lib/stack_master/aws_driver/cloud_formation.rb +++ b/lib/stack_master/aws_driver/cloud_formation.rb @@ -3,11 +3,15 @@ class CloudFormation extend Forwardable - attr_reader :region + def region + @region ||= ENV['AWS_REGION'] || Aws.config[:region] || Aws.shared_config.region + end - def set_region(region) - @region = region - @cf = nil + def set_region(value) + if region != value + @region = value + @cf = nil + end end def_delegators :cf, :create_change_set, @@ -33,7 +37,7 @@ private def cf - @cf ||= Aws::CloudFormation::Client.new(region: @region) + @cf ||= Aws::CloudFormation::Client.new(region: region) end def retry_with_backoff
Support auto-detecting the current region
diff --git a/jbadmin.gemspec b/jbadmin.gemspec index abc1234..def5678 100644 --- a/jbadmin.gemspec +++ b/jbadmin.gemspec @@ -16,7 +16,7 @@ s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"] - s.add_dependency "rails", ">= 5.0.2" + s.add_dependency "rails", ">= 5.1.0" s.add_dependency "sass-rails", ">= 5.0.4" s.add_dependency "jquery-rails", ">= 4.3.1" s.add_dependency "haml", ">= 4.0.7"
Upgrade gemspec dependency to use Rails 5.1
diff --git a/examples/version_mix_consensus.rb b/examples/version_mix_consensus.rb index abc1234..def5678 100644 --- a/examples/version_mix_consensus.rb +++ b/examples/version_mix_consensus.rb @@ -0,0 +1,42 @@+old_image = ENV["OLD_IMAGE"] +new_image = ENV["NEW_IMAGE"] + +raise "missing ENV['OLD_IMAGE']" unless old_image +raise "missing ENV['NEW_IMAGE']" unless new_image + +peers = [:oldnode1, :oldnode2, :newnode1, :newnode2] + +process :oldnode1, peers, 4, docker_core_image: old_image, docker_pull: true +process :oldnode2, peers, 4, docker_core_image: old_image, docker_pull: true +process :newnode1, peers, 4, docker_core_image: new_image, docker_pull: true +process :newnode2, peers, 4, docker_core_image: new_image, docker_pull: true + +account :alice +account :bob + +on :oldnode2 do + create_account :alice, :master + create_account :bob, :master + while not ((account_created :bob) and (account_created :alice)) + $stderr.puts "Awaiting account-creation" + close_ledger + end + $stderr.puts "oldnode2 bob balance: #{(balance :bob)}" + $stderr.puts "oldnode2 alice balance: #{(balance :alice)}" + payment :master, :bob, [:native, 1000_000000] + close_ledger +end + +on :newnode1 do + $stderr.puts "newnode1 bob balance: #{(balance :bob)}" + $stderr.puts "newnode1 alice balance: #{(balance :alice)}" + raise if (balance :bob) != 11000_000000 + payment :master, :alice, [:native, 1000_000000] + close_ledger +end + +on :oldnode1 do + $stderr.puts "oldnode1 bob balance: #{(balance :bob)}" + $stderr.puts "oldnode1 alice balance: #{(balance :alice)}" + raise if (balance :alice) != 11000_000000 +end
Add sketch of multi-version consensus tests.
diff --git a/espn_page_grab.rb b/espn_page_grab.rb index abc1234..def5678 100644 --- a/espn_page_grab.rb +++ b/espn_page_grab.rb @@ -0,0 +1,53 @@+#!/usr/bin/env ruby + +require 'rubygems' +require 'nokogiri' +require 'open-uri' +require 'fileutils' + +BASE_URL = 'http://espn.go.com/nfl/statistics/player/_/stat/' +BASE_DIR = {:passing => 'passing/sort/passingYards/year/2013/seasontype/2/qualified/false/count/', + :rushing => 'rushing/sort/rushingYards/year/2013/seasontype/2/qualified/false/count/', + :receiving => 'receiving/sort/receivingYards/year/2013/seasontype/2/qualified/false/count/', + } + +def scrape(position) + puts "You asked for the #{position} stats\nHere they come." + arr = [] + counts = (1..900).step(40) { |i| arr.push(i) } + + page = Nokogiri::HTML(open(BASE_URL + BASE_DIR[position.to_sym] + '1')) + ## Debugging + puts "Found '#{page.title}'" + #### Writes the first file #### + File.open("espn_html_pages/#{position}1.html", 'w'){|f| f.write(page.to_html)} + puts "First #{position} file saved successfully" + + #### Find the number of results(players) for the given stat request #### + results_div = page.css('#my-players-table div.totalResults').first.content + number_results_arr = results_div.split(' ') + number_results = number_results_arr[0].to_i + + #### Finding the correct number of pages to find #### + if number_results % 40 == 0 + num_pages = number_results/40 + else + num_pages = (number_results/40) + 1 + end + + puts "#{num_pages - 1} more pages need to be collected" + + if num_pages > 1 + #### Grabs each page of stats for passing #### + arr[(1..(num_pages-1))].each do |x| + page = Nokogiri::HTML(open(BASE_URL + BASE_DIR[position.to_sym] + "#{x}")) + #### Writes page to an HTML file on disk #### + File.open("espn_html_pages/#{position}#{x}.html", 'w'){|f| f.write(page.to_html)} + puts "File #{position}#{x} saved successfully" + end + end + puts "Reached the end of the 'scrape #{position}' method" + +end + +scrape('passing')
Add new scraping code. Rename for better understanding of its function
diff --git a/lib/attribute_normalizer.rb b/lib/attribute_normalizer.rb index abc1234..def5678 100644 --- a/lib/attribute_normalizer.rb +++ b/lib/attribute_normalizer.rb @@ -35,9 +35,10 @@ end - alias :normalize_attribute :normalize_attributes + end - end + alias :normalize_attribute :normalize_attributes + end end
Move the line to its correct position for alias.
diff --git a/lib/bacon/colored_output.rb b/lib/bacon/colored_output.rb index abc1234..def5678 100644 --- a/lib/bacon/colored_output.rb +++ b/lib/bacon/colored_output.rb @@ -1,15 +1,11 @@ module Bacon module ColoredOutput - include SpecDoxOutput - - def handle_requirement(description) - print spaces - + def handle_requirement(*args) error = yield print error.empty? ? color("\e[32m") : color("\e[1;31m") - print " - #{description}" - puts error.empty? ? color("\e[0m") : " [#{error}]#{color("\e[0m")}" + super + print color("\e[0m") end def color(escape_seq)
Make colored output universal (for any output style)
diff --git a/lib/forex/traders/jm/ncb.rb b/lib/forex/traders/jm/ncb.rb index abc1234..def5678 100644 --- a/lib/forex/traders/jm/ncb.rb +++ b/lib/forex/traders/jm/ncb.rb @@ -1,7 +1,7 @@ Forex::Trader.define "NCB" do |t| t.base_currency = "JMD" t.name = "National Commercial Bank" - t.endpoint = "http://www.jncb.com/rates/foreignexchangerates" + t.endpoint = "http://www.jncb.com/rates" t.twitter_handle = "@ncbja" t.rates_parser = ->(doc) do # doc is a nokogiri document @@ -13,7 +13,7 @@ buy_draft: 3, } - table = doc.css(".rates table").first + table = doc.css(".fxratestable").first Forex::TabularRates.new(table, options).parse_rates end
Update NCB rates endpoint and table class
diff --git a/layer-ruby.gemspec b/layer-ruby.gemspec index abc1234..def5678 100644 --- a/layer-ruby.gemspec +++ b/layer-ruby.gemspec @@ -14,14 +14,6 @@ spec.homepage = "TODO: Put your gem's website or public repo URL here." spec.license = "MIT" - # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or - # delete this section to allow pushing this gem to any host. - if spec.respond_to?(:metadata) - spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'" - else - raise "RubyGems 2.0 or newer is required to protect against public gem pushes." - end - spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
Allow pushing to any host