Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix lame reg engine workaround
Gem::Specification.new do |s| s.name = "registration_engine" s.version = "0.0.1" s.authors = [ "Scott Willson" ] s.email = [ "scott.willson@gmail.com" ] s.homepage = "http://rocketsurgeryllc.com" s.summary = "Event registration" s.description = "Empty placeholder gem" s.add_dependency "activemerchant" end
Use new syntax for setting SimpleCov formatters.
require "simplecov" require "coveralls" SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter ] SimpleCov.start { add_filter "/spec/" } require "lita-karma" require "lita/rspec" Lita.version_3_compatibility_mode = false
require "simplecov" require "coveralls" SimpleCov.formatters = [ SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter ] SimpleCov.start { add_filter "/spec/" } require "lita-karma" require "lita/rspec" Lita.version_3_compatibility_mode = false
Read cookbook version from gem version
name 'chef-sugar' maintainer 'Seth Vargo' maintainer_email 'sethvargo@gmail.com' license 'Apache 2.0' description 'Installs chef-sugar. Please see the chef-sugar ' \ 'Ruby gem for more information.' long_description <<-EOH Chef Sugar is a Gem & Chef Recipe that includes series of helpful syntactic sugars on top of the Chef core and other resources to make a cleaner, more lean recipe DSL, enforce DRY principles, and make writing Chef recipes an awesome and fun experience! For the most up-to-date information and documentation, please visit the [Chef Sugar project page on GitHub](https://github.com/sethvargo/chef-sugar). EOH version '2.3.2'
name 'chef-sugar' maintainer 'Seth Vargo' maintainer_email 'sethvargo@gmail.com' license 'Apache 2.0' description 'Installs chef-sugar. Please see the chef-sugar ' \ 'Ruby gem for more information.' long_description <<-EOH Chef Sugar is a Gem & Chef Recipe that includes series of helpful syntactic sugars on top of the Chef core and other resources to make a cleaner, more lean recipe DSL, enforce DRY principles, and make writing Chef recipes an awesome and fun experience! For the most up-to-date information and documentation, please visit the [Chef Sugar project page on GitHub](https://github.com/sethvargo/chef-sugar). EOH require_relative 'lib/chef/sugar/version' version Chef::Sugar::VERSION
Add a test for the Reru::IO::Reader's stop method
require 'spec_helper' describe Reru::IO::Reader do it "spits what it reads down the stream" do StringIO.open("hello world\nhere we go!") do |input| reader = Reru::IO::Reader.new(input) xs = [] reader.perform { |x| xs << x } Reru.run xs.should == ["hello world\n", "here we go!"] end end end
require 'spec_helper' describe Reru::IO::Reader do it "spits what it reads down the stream" do StringIO.open("hello world\nhere we go!") do |input| reader = Reru::IO::Reader.new(input) xs = [] reader.perform { |x| xs << x } Reru.run xs.should == ["hello world\n", "here we go!"] end end it "stops reading if told so" do StringIO.open("hello world\nhere we go!") do |input| reader = Reru::IO::Reader.new(input) xs = [] reader.perform { |x| xs << x reader.stop } Reru.run xs.should == ["hello world\n"] end end end
Add methods to find box(es) from its children.
# coding: utf-8 # vim: set expandtab tabstop=2 shiftwidth=2 softtabstop=2 autoindent: module BMFF::Box::Container attr_accessor :children def container? true end def parse_children @children = [] until eob? @children << BMFF::Box.get_box(io, self) end end end
# coding: utf-8 # vim: set expandtab tabstop=2 shiftwidth=2 softtabstop=2 autoindent: module BMFF::Box::Container attr_accessor :children def container? true end def parse_children @children = [] until eob? @children << BMFF::Box.get_box(io, self) end end # Find a box which has a specific type from this children. def find(boxtype) (@children || []).each do |child| case boxtype when String return child if child.type == boxtype when Class return child if child.instance_of?(boxtype) end end nil end # Find boxes which have a specific type from this children. def find_all(boxtype) found_boxes = [] (@children || []).each do |child| case boxtype when String found_boxes << child if child.type == boxtype when Class found_boxes << child if child.instance_of?(boxtype) end end found_boxes end # Find boxes which have a specific type from this offspring. def select_offspring(boxtype) selected_boxes = [] (@children || []).each do |child| case boxtype when String selected_boxes << child if child.type == boxtype when Class selected_boxes << child if child.instance_of?(boxtype) end if child.container? selected_boxes.concat(child.select_offspring(boxtype)) end end selected_boxes end end
Add karmacracy to main module
require 'link_shrink/version' require 'link_shrink/options' require 'link_shrink/util' require 'link_shrink/request' require 'link_shrink/json_parser' require 'link_shrink/shrinkers/base' require 'link_shrink/shrinkers/google' require 'link_shrink/shrinkers/tinyurl' require 'link_shrink/shrinkers/isgd' require 'link_shrink/shrinkers/owly' require 'link_shrink/config' # @author Jonah Ruiz <jonah@pixelhipsters.com> # Creates a short URLs module LinkShrink extend self include LinkShrink::Request # Returns a short URL # example: shrink_url('http://www.wtf.com') # # @param url [String] long URL to be shortened # @return [String] generated short URL def shrink_url(url) process_request(url) end # Yield's to Config for options # # @param <config> [String] api interface to use # @param <api_key> [String] api key to use def configure yield LinkShrink::Config if block_given? end end
require 'link_shrink/version' require 'link_shrink/options' require 'link_shrink/util' require 'link_shrink/request' require 'link_shrink/json_parser' require 'link_shrink/shrinkers/base' require 'link_shrink/shrinkers/google' require 'link_shrink/shrinkers/tinyurl' require 'link_shrink/shrinkers/isgd' require 'link_shrink/shrinkers/owly' require 'link_shrink/shrinkers/karmacracy' require 'link_shrink/config' # @author Jonah Ruiz <jonah@pixelhipsters.com> # Creates a short URLs module LinkShrink extend self include LinkShrink::Request # Returns a short URL # example: shrink_url('http://www.wtf.com') # # @param url [String] long URL to be shortened # @return [String] generated short URL def shrink_url(url) process_request(url) end # Yield's to Config for options # # @param <config> [String] api interface to use # @param <api_key> [String] api key to use def configure yield LinkShrink::Config if block_given? end end
Remove `cd` as it cause issues in Debian
require 'fileutils' namespace :npm do desc "Install npm packages" task :install do package_file = ::Rails.configuration.npm.package_file browserify_options = ::Rails.configuration.npm.browserify_options output_path = ::Rails.root.join(::Rails.configuration.npm.output_path) output_file = "npm-dependencies.js" output_file_path = output_path.join(output_file) Npm::Rails::TaskHelpers.create_file(output_path, output_file) unless File.exist?(output_file_path) Npm::Rails::PackageBundler.bundle(::Rails.root, package_file, ::Rails.env) do |packages, bundle_file_path| sh "cd #{ ::Rails.root }" sh "npm install --loglevel error #{ packages }" browserify = Npm::Rails::TaskHelpers.find_browserify(::Rails.root.join("node_modules")) browserify_command = "#{ browserify } #{ browserify_options } #{ bundle_file_path } > #{ output_file_path }" if Rails.env.production? browserify_command = "NODE_ENV=production #{ browserify_command }" end sh browserify_command end end end if ::Rails.configuration.npm.run_before_assets_precompile task "assets:precompile" => ["npm:install"] end
require 'fileutils' namespace :npm do desc "Install npm packages" task :install do package_file = ::Rails.configuration.npm.package_file browserify_options = ::Rails.configuration.npm.browserify_options output_path = ::Rails.root.join(::Rails.configuration.npm.output_path) output_file = "npm-dependencies.js" output_file_path = output_path.join(output_file) Npm::Rails::TaskHelpers.create_file(output_path, output_file) unless File.exist?(output_file_path) Npm::Rails::PackageBundler.bundle(::Rails.root, package_file, ::Rails.env) do |packages, bundle_file_path| sh "npm install --prefix #{ ::Rails.root } --loglevel error #{ packages }" browserify = Npm::Rails::TaskHelpers.find_browserify(::Rails.root.join("node_modules")) browserify_command = "#{ browserify } #{ browserify_options } #{ bundle_file_path } > #{ output_file_path }" if Rails.env.production? browserify_command = "NODE_ENV=production #{ browserify_command }" end sh browserify_command end end end if ::Rails.configuration.npm.run_before_assets_precompile task "assets:precompile" => ["npm:install"] end
Support for HTTP auth CouchDB reporter.
require "json" require "time" class Time def to_json(*args) #:nodoc: iso8601(3).to_json(*args) end end module Stampede module Reporters class CouchDB def initialize(url) @url = url @docs = [] @closing = false end def record(value) @docs << ::JSON.generate(value) EM.next_tick { flush } end def close @closing = true @close_callback = Proc.new flush end def flush return if @docs.empty? docs, @docs = %Q({"docs":[#{@docs.join(",")}]}), [] request = EM::HttpRequest.new(@url + "/_bulk_docs").post :body => docs, :head => { "content-type" => "application/json" } request.callback do @close_callback.call if @closing end request.errback do @close_callback.call if @closing end end end end end
require "json" require "time" require "em-http-request" require "addressable/uri" class Time def to_json(*args) #:nodoc: iso8601(3).to_json(*args) end end module Stampede module Reporters class CouchDB def initialize(url) @url = url @headers = { "content-type" => "application/json" } parsed = Addressable::URI.parse(url) @headers["authorization"] = [ Addressable::URI.unencode(parsed.normalized_user), Addressable::URI.unencode(parsed.normalized_password) ] if parsed.normalized_user @docs = [] @closing = false end def record(value) @docs << ::JSON.generate(value) EM.next_tick { flush } end def close @closing = true @close_callback = Proc.new flush end def flush return if @docs.empty? docs, @docs = %Q({"docs":[#{@docs.join(",")}]}), [] request = EM::HttpRequest.new(@url + "/_bulk_docs").post :body => docs, :head => @headers request.callback do @close_callback.call if @closing end request.errback do @close_callback.call if @closing end end end end end
Add timeout for short transaction
# frozen_string_literal: true require 'timeout' module RubyRabbitmqJanus module Rabbit # @author VAILLANT Jeremy <jeremy.vaillant@dazzl.tv> # # Class for manage connection with RabbitMQ class Connect # Initialize connection to server RabbitMQ def initialize @rabbit = Bunny.new rescue => exception raise Errors::Rabbit::Connect::Initialize, exception end # Create an transaction with rabbitmq and close after response is received def transaction_short response = transaction_long { yield } close response rescue => exception raise Errors::Rabbit::Connect::TransactionShort, exception end # Create an transaction with rabbitmq and not close def transaction_long Timeout.timeout(10) do start yield end rescue => exception raise Errors::Rabbit::Connect::TransactionLong, exception end # Opening a connection with RabbitMQ def start @rabbit.start rescue => exception raise Errors::Rabbit::Connect::Start, exception end # Close connection to server RabbitMQ def close @rabbit.close rescue => exception raise Errors::Rabbit::Connect::Close, exception end # Create an channel def channel @rabbit.create_channel rescue => exception raise Errors::Rabbit::Connect::Channel, exception end private def bunny_conf Tools::Config.instance.server_settings.merge(connection_timeout: 5) end end end end
# frozen_string_literal: true require 'timeout' module RubyRabbitmqJanus module Rabbit # @author VAILLANT Jeremy <jeremy.vaillant@dazzl.tv> # # Class for manage connection with RabbitMQ class Connect # Initialize connection to server RabbitMQ def initialize @rabbit = Bunny.new rescue => exception raise Errors::Rabbit::Connect::Initialize, exception end # Create an transaction with rabbitmq and close after response is received def transaction_short Timeout.timeout(10) do response = transaction_long { yield } close response end rescue => exception raise Errors::Rabbit::Connect::TransactionShort, exception end # Create an transaction with rabbitmq and not close def transaction_long Timeout.timeout(10) do start yield end rescue => exception raise Errors::Rabbit::Connect::TransactionLong, exception end # Opening a connection with RabbitMQ def start @rabbit.start rescue => exception raise Errors::Rabbit::Connect::Start, exception end # Close connection to server RabbitMQ def close @rabbit.close rescue => exception raise Errors::Rabbit::Connect::Close, exception end # Create an channel def channel @rabbit.create_channel rescue => exception raise Errors::Rabbit::Connect::Channel, exception end private def bunny_conf Tools::Config.instance.server_settings.merge(connection_timeout: 5) end end end end
Use sub() instead of split()
module VundleCli module Helpers module_function def file_validate(fpath, check_dir = false) fpath = File.expand_path(fpath) unless File.exist?(fpath) raise ArgumentError.new("#{fpath} does not exist") end fpath = File.readlink(fpath) if File.symlink?(fpath) if check_dir unless File.directory?(fpath) raise ArgumentError.new("#{fpath} is not a directory") end else unless File.file?(fpath) raise ArgumentError.new("#{fpath} is not a valid file") end end fpath end # Get the bundle's main name. # (the provided @bundle usually looks like baopham/trailertrash.vim, # so we trim it down to get "trailertrash.vim" only). def bundle_base_name(bundle) bundle_name = bundle if bundle.include?("/") bundle_name = bundle.split("/")[1] end bundle_name end # Get the trimed name of the bundle, # e.g. remove prefix, suffix "vim-", "-vim", ".vim". def bundle_trim_name(bundle_name) bundle_name.gsub(/(vim|-|\.)/, '') end def puts_separator puts "-----------------------------" end end end
module VundleCli module Helpers module_function def file_validate(fpath, check_dir = false) fpath = File.expand_path(fpath) unless File.exist?(fpath) raise ArgumentError.new("#{fpath} does not exist") end fpath = File.readlink(fpath) if File.symlink?(fpath) if check_dir unless File.directory?(fpath) raise ArgumentError.new("#{fpath} is not a directory") end else unless File.file?(fpath) raise ArgumentError.new("#{fpath} is not a valid file") end end fpath end # Get the bundle's main name. # (the provided @bundle usually looks like baopham/trailertrash.vim, # so we trim it down to get "trailertrash.vim" only). def bundle_base_name(bundle) bundle.sub(/\S*\//, '') end # Get the trimed name of the bundle, # e.g. remove prefix, suffix "vim-", "-vim", ".vim". def bundle_trim_name(bundle_name) bundle_name.gsub(/(vim|-|\.)/, '') end def puts_separator puts "-----------------------------" end end end
Define Engine only if Rails is available
require "vidibus/uuid" require "vidibus/validate_uuid" require "vidibus/uuid/mongoid" module Vidibus::Uuid class Engine < ::Rails::Engine; end end ActiveModel::Validations.send(:include, Vidibus::ValidateUuid)
require "vidibus/uuid" require "vidibus/validate_uuid" require "vidibus/uuid/mongoid" if defined?(Rails) module Vidibus::Uuid class Engine < ::Rails::Engine; end end end ActiveModel::Validations.send(:include, Vidibus::ValidateUuid)
Add Willamette Valley Classics Tour competition
# frozen_string_literal: true module Competitions module WillametteValleyClassicsTour class Overall < Competitions::Overall def self.parent_event_name "Willamette Valley Classics Tour" end def category_names [ "Category 3 Men", "Category 4/5 Men", "Junior Men", "Junior Women", "Masters Men 40-49 (Category 3/4/5)", "Masters Men 50+/60+ (Category 3/4/5)", "Masters Men 60+ (Category 3/4/5)", "Masters Women 40+ (Category 3/4/5)", "Pro/1/2", "Pro/1/2 40+", "Pro/1/2 50+", "Women 1/2/3", "Women 4/5" ] end def point_schedule [100, 80, 60, 50, 45, 40, 36, 32, 29, 26, 24, 22, 20, 18, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] end def upgrade_points_multiplier 0.25 end end end end
Change to use the 18 parser for jruby in 1.9 mode
# encoding: utf-8 module YARD #:nodoc: all # Test if JRuby head is being used JRUBY_19MODE = RUBY_VERSION >= '1.9' && RUBY_ENGINE == 'jruby' JRUBY_HEAD = JRUBY_19MODE && JRUBY_VERSION >= '1.7.4.dev' # Fix jruby-head to use the ruby 1.8 parser until their ripper port is working Parser::SourceParser.parser_type = :ruby18 if JRUBY_HEAD end # module YARD
# encoding: utf-8 module YARD #:nodoc: all # Test if JRuby head is being used JRUBY_19MODE = RUBY_VERSION >= '1.9' && RUBY_ENGINE == 'jruby' # Fix jruby-head to use the ruby 1.8 parser until their ripper port is working Parser::SourceParser.parser_type = :ruby18 if JRUBY_19MODE end # module YARD
Fix N+1 query for BlogsController
# # == BlogsController # class BlogsController < ApplicationController before_action :blog_module_enabled? before_action :set_blog, only: [:show] decorates_assigned :blog, :comment include Commentable # GET /blog # GET /blog.json def index @blogs = Blog.online.order(created_at: :desc) per_p = @setting.per_page == 0 ? @blogs.count : @setting.per_page @blogs = BlogDecorator.decorate_collection(@blogs.page(params[:page]).per(per_p)) seo_tag_index category end # GET /blog/1 # GET /blog/1.json def show redirect_to @blog, status: :moved_permanently if request.path_parameters[:id] != @blog.slug @blog_settings = BlogSetting.first seo_tag_show blog end private def set_blog @blog = Blog.online.includes(:pictures, referencement: [:translations]).friendly.find(params[:id]) end def blog_module_enabled? not_found unless @blog_module.enabled? end end
# # == BlogsController # class BlogsController < ApplicationController before_action :blog_module_enabled? before_action :set_blog, only: [:show] decorates_assigned :blog, :comment include Commentable # GET /blog # GET /blog.json def index @blogs = Blog.includes(:translations, :user).online.order(created_at: :desc) per_p = @setting.per_page == 0 ? @blogs.count : @setting.per_page @blogs = BlogDecorator.decorate_collection(@blogs.page(params[:page]).per(per_p)) seo_tag_index category end # GET /blog/1 # GET /blog/1.json def show redirect_to @blog, status: :moved_permanently if request.path_parameters[:id] != @blog.slug @blog_settings = BlogSetting.first seo_tag_show blog end private def set_blog @blog = Blog.online.includes(:pictures, referencement: [:translations]).friendly.find(params[:id]) end def blog_module_enabled? not_found unless @blog_module.enabled? end end
Update upstream percona to 2.1.0
name 'osl-mysql' issues_url 'https://github.com/osuosl-cookbooks/osl-mysql/issues' source_url 'https://github.com/osuosl-cookbooks/osl-mysql' maintainer 'Oregon State University' maintainer_email 'systems@osuosl.org' license 'Apache-2.0' chef_version '>= 15.0' description 'Installs/Configures osl-mysql' version '4.0.0' depends 'firewall' depends 'git' depends 'mariadb', '~> 4.1' depends 'mysql', '~> 8.5.1' depends 'osl-nrpe' depends 'osl-munin' depends 'osl-postfix' depends 'percona', '~> 2.0.0' supports 'centos', '~> 7.0' supports 'centos', '~> 8.0'
name 'osl-mysql' issues_url 'https://github.com/osuosl-cookbooks/osl-mysql/issues' source_url 'https://github.com/osuosl-cookbooks/osl-mysql' maintainer 'Oregon State University' maintainer_email 'systems@osuosl.org' license 'Apache-2.0' chef_version '>= 15.0' description 'Installs/Configures osl-mysql' version '4.0.0' depends 'firewall' depends 'git' depends 'mariadb', '~> 4.1' depends 'mysql', '~> 8.5.1' depends 'osl-nrpe' depends 'osl-munin' depends 'osl-postfix' depends 'percona', '~> 2.1.0' supports 'centos', '~> 7.0' supports 'centos', '~> 8.0'
Add YARD gem to development dependencies
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'dice_set/version' Gem::Specification.new do |spec| spec.name = 'dice_set' spec.version = DiceSet::VERSION spec.authors = ['Rafaël Gonzalez'] spec.email = ['github@rafaelgonzalez.me'] spec.summary = %q{A gem with dices, to get rolling with Ruby.} spec.description = %q{A gem with dices, to get rolling with Ruby.} spec.homepage = 'https://github.com/rafaelgonzalez/dice_set' 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 '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 'dice_set/version' Gem::Specification.new do |spec| spec.name = 'dice_set' spec.version = DiceSet::VERSION spec.authors = ['Rafaël Gonzalez'] spec.email = ['github@rafaelgonzalez.me'] spec.summary = %q{A gem with dices, to get rolling with Ruby.} spec.description = %q{A gem with dices, to get rolling with Ruby.} spec.homepage = 'https://github.com/rafaelgonzalez/dice_set' 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 'bundler', '~> 1.5' spec.add_development_dependency 'rake' spec.add_development_dependency 'rspec', '~> 3.0' spec.add_development_dependency 'yard', '~> 0.8.7' end
Add migration that adds kontakt to header
class InsertContactInHeader < ActiveRecord::Migration def change main_menu = Menu.where(name: "main").first link = { controller: "contact", action: "index", title: "Kontakt", preferred_order: 3 } MenuLink.create(link.merge(menu: main_menu)) end end
Package version is incremented from patch number 0.1.1 to 0.1.2
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'telemetry-logger' s.version = '0.1.1' s.summary = 'Logging to STDERR with coloring and levels of severity' s.description = ' ' s.authors = ['Obsidian Software, Inc'] s.email = 'opensource@obsidianexchange.com' s.homepage = 'https://github.com/obsidian-btc/error_data' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.2.3' s.add_runtime_dependency 'clock', '~> 0' s.add_runtime_dependency 'dependency', '~> 0' s.add_runtime_dependency 'rainbow', '~> 0' end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'telemetry-logger' s.version = '0.1.2' s.summary = 'Logging to STDERR with coloring and levels of severity' s.description = ' ' s.authors = ['Obsidian Software, Inc'] s.email = 'opensource@obsidianexchange.com' s.homepage = 'https://github.com/obsidian-btc/error_data' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.2.3' s.add_runtime_dependency 'clock', '~> 0' s.add_runtime_dependency 'dependency', '~> 0' s.add_runtime_dependency 'rainbow', '~> 0' end
Allow build agent to specify VM provider
require 'tailor/rake_task' require 'foodcritic' require 'daptiv-chef-ci/vagrant_task' task :lint => [:version, :tailor, :foodcritic] task :default => [:lint] task :version do IO.write('version.txt', (ENV['BUILD_NUMBER'] ? "0.1.#{ENV['BUILD_NUMBER']}" : '0.1.0')) end FoodCritic::Rake::LintTask.new do |t| t.options = { :cookbook_paths => '.', :search_gems => true } end Tailor::RakeTask.new Vagrant::RakeTask.new
require 'tailor/rake_task' require 'foodcritic' require 'daptiv-chef-ci/vagrant_task' @provider = (ENV['PROVIDER'] || :virtualbox).to_sym task :lint => [:version, :tailor, :foodcritic] task :default => [:lint] task :version do IO.write('version.txt', (ENV['BUILD_NUMBER'] ? "0.1.#{ENV['BUILD_NUMBER']}" : '0.1.0')) end FoodCritic::Rake::LintTask.new do |t| t.options = { :cookbook_paths => '.', :search_gems => true } end Tailor::RakeTask.new Vagrant::RakeTask.new :vagrant, 'Run Vagrant with the specifed provider' do |t| t.provider = @provider end
Change to require all matchers.
# encoding: utf-8 if RUBY_VERSION > '1.9' and (ENV['COVERAGE'] || ENV['TRAVIS']) require 'simplecov' require 'coveralls' SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter ] SimpleCov.start do command_name 'spec' add_filter 'spec' end end require 'rspec-benchmark' require 'rspec/benchmark/timing_matcher' require 'rspec/benchmark/iteration_matcher' RSpec.configure do |config| config.include(RSpec::Benchmark::TimingMatcher) config.include(RSpec::Benchmark::IterationMatcher) config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.filter_run :focus config.run_all_when_everything_filtered = true config.disable_monkey_patching! config.warnings = true if config.files_to_run.one? config.default_formatter = 'doc' end config.profile_examples = 10 config.order = :random Kernel.srand config.seed end
# encoding: utf-8 if RUBY_VERSION > '1.9' and (ENV['COVERAGE'] || ENV['TRAVIS']) require 'simplecov' require 'coveralls' SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter ] SimpleCov.start do command_name 'spec' add_filter 'spec' end end require 'rspec-benchmark' RSpec.configure do |config| config.include(RSpec::Benchmark::TimingMatcher) config.include(RSpec::Benchmark::IterationMatcher) config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.filter_run :focus config.run_all_when_everything_filtered = true config.disable_monkey_patching! config.warnings = true if config.files_to_run.one? config.default_formatter = 'doc' end config.profile_examples = 10 config.order = :random Kernel.srand config.seed end
Remove ID from admin subscribers index
require "administrate/base_dashboard" class SubscriberDashboard < Administrate::BaseDashboard # ATTRIBUTE_TYPES # a hash that describes the type of each of the model's fields. # # Each different type represents an Administrate::Field object, # which determines how the attribute is displayed # on pages throughout the dashboard. ATTRIBUTE_TYPES = { id: Field::Number, name: Field::String, email: Field::String, created_at: Field::DateTime, updated_at: Field::DateTime, } # COLLECTION_ATTRIBUTES # an array of attributes that will be displayed on the model's index page. # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. COLLECTION_ATTRIBUTES = [ :id, :name, :email, :created_at, ] # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. SHOW_PAGE_ATTRIBUTES = ATTRIBUTE_TYPES.keys # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. FORM_ATTRIBUTES = [ :name, :email, ] # Overwrite this method to customize how subscribers are displayed # across all pages of the admin dashboard. # # def display_resource(subscriber) # "Subscriber ##{subscriber.id}" # end end
require "administrate/base_dashboard" class SubscriberDashboard < Administrate::BaseDashboard # ATTRIBUTE_TYPES # a hash that describes the type of each of the model's fields. # # Each different type represents an Administrate::Field object, # which determines how the attribute is displayed # on pages throughout the dashboard. ATTRIBUTE_TYPES = { id: Field::Number, name: Field::String, email: Field::String, created_at: Field::DateTime, updated_at: Field::DateTime, } # COLLECTION_ATTRIBUTES # an array of attributes that will be displayed on the model's index page. # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. COLLECTION_ATTRIBUTES = [ :name, :email, :created_at ] # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. SHOW_PAGE_ATTRIBUTES = ATTRIBUTE_TYPES.keys # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. FORM_ATTRIBUTES = [ :name, :email, ] # Overwrite this method to customize how subscribers are displayed # across all pages of the admin dashboard. # # def display_resource(subscriber) # "Subscriber ##{subscriber.id}" # end end
Add tests for empty objects
# -*- coding: utf-8 -*- require "stringio" require "pp" require "lazy/pp/json" module Lazy::PP class JSONTest < Test::Unit::TestCase def setup @original_stdout = $stdout.dup @stdout = StringIO.new $stdout = @stdout end class EmptyTest < self def test_array assert_lazy_json("[]", "[]") end def test_hash assert_lazy_json("{}", "{}") end end def teardown $stdout = @original_stdout end private def assert_lazy_json(expected, actual_string) actual = Lazy::PP::JSON.new(actual_string) assert_equal(expected, pp(actual)) end end end
Move snmp require so that it's available for other files.
require 'copian/version' require 'copian/collector/abstract_collector' require 'copian/collector/addresses_collector' require 'copian/collector/bandwidth_collector' require 'copian/collector/description_collector' require 'copian/collector/ports_collector' require 'copian/collector/port_stats_collector' require 'copian/collector/generic' require 'copian/collector/cisco' require 'copian/collector/dell' require 'copian/collector/hp' require 'snmp' # :stopdoc: class SNMP::Manager attr_reader :host, :community, :version end # :startdoc: module Copian # :nodoc: module Collector # :nodoc: end end
require 'snmp' require 'copian/version' require 'copian/collector/abstract_collector' require 'copian/collector/addresses_collector' require 'copian/collector/bandwidth_collector' require 'copian/collector/description_collector' require 'copian/collector/ports_collector' require 'copian/collector/port_stats_collector' require 'copian/collector/generic' require 'copian/collector/cisco' require 'copian/collector/dell' require 'copian/collector/hp' # :stopdoc: class SNMP::Manager attr_reader :host, :community, :version end # :startdoc: module Copian # :nodoc: module Collector # :nodoc: end end
Update hashie dependency to version ~> 1.1.0
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "rash/version" Gem::Specification.new do |s| s.name = %q{rash} s.authors = ["tcocca"] s.description = %q{simple extension to Hashie::Mash for rubyified keys, all keys are converted to underscore to eliminate horrible camelCasing} s.email = %q{tom.cocca@gmail.com} s.homepage = %q{http://github.com/tcocca/rash} s.rdoc_options = ["--charset=UTF-8"] s.summary = %q{simple extension to Hashie::Mash for rubyified keys} s.version = Rash::VERSION s.add_dependency "hashie", '~> 1.0.0' s.add_development_dependency "rspec", "~> 2.5.0" s.require_paths = ['lib'] s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "rash/version" Gem::Specification.new do |s| s.name = %q{rash} s.authors = ["tcocca"] s.description = %q{simple extension to Hashie::Mash for rubyified keys, all keys are converted to underscore to eliminate horrible camelCasing} s.email = %q{tom.cocca@gmail.com} s.homepage = %q{http://github.com/tcocca/rash} s.rdoc_options = ["--charset=UTF-8"] s.summary = %q{simple extension to Hashie::Mash for rubyified keys} s.version = Rash::VERSION s.add_dependency 'hashie', '~> 1.1.0' s.add_development_dependency "rspec", "~> 2.5.0" s.require_paths = ['lib'] s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } end
Fix Watcher.close for inotify backend
require 'rb-inotify' require 'io/nonblock' module EMDirWatcher module Platform module Linux class Watcher def initialize path, inclusions, exclusions @notifier = INotify::Notifier.new @notifier.watch(path, :recursive, :attrib, :modify, :create, :delete, :delete_self, :moved_from, :moved_to, :move_self) do |event| yield event.absolute_name end @conn = EM.watch @notifier.to_io do |conn| class << conn attr_accessor :notifier def notify_readable @notifier.process end end conn.notifier = @notifier conn.notify_readable = true end end def ready_to_use?; true; end def stop @conn.stop @notifier.watcher.close end end end end end
require 'rb-inotify' require 'io/nonblock' module EMDirWatcher module Platform module Linux module Native extend FFI::Library ffi_lib "c" attach_function :close, [:int], :int end class Watcher def initialize path, inclusions, exclusions @notifier = INotify::Notifier.new @notifier.watch(path, :recursive, :attrib, :modify, :create, :delete, :delete_self, :moved_from, :moved_to, :move_self) do |event| yield event.absolute_name end @conn = EM.watch @notifier.to_io do |conn| class << conn attr_accessor :notifier def notify_readable @notifier.process end end conn.notifier = @notifier conn.notify_readable = true end end def ready_to_use?; true; end def stop Native.close @notifier.fd end end end end end
Rename the shell script since the converter is platform dependent.
require 'nokogiri' class WordConverter attr_reader :raw_html, :html def initialize(raw_html) puts raw_html @raw_html = raw_html end def to_html() return @html if defined? @html @html = self.class.extract_body(@raw_html) @html = self.class.cleanse_html(@html) end class << self def html_from_file(filename) html = `unoconv "#{filename}"` WordConverter.new(html).to_html end def extract_body(html) if doc = Nokogiri::HTML::Document.parse(html) if body = doc.xpath('/html/body') return doc.xpath("//html/body").children.to_html end end return html end def cleanse_html(html) MyHtmlSanitizer.clean(html) end end end
require 'nokogiri' class WordConverter attr_reader :raw_html, :html def initialize(raw_html) puts raw_html @raw_html = raw_html end def to_html() return @html if defined? @html @html = self.class.extract_body(@raw_html) @html = self.class.cleanse_html(@html) end class << self def html_from_file(filename) html = `/opt/bin/convert_docx_to_html "#{filename}"` WordConverter.new(html).to_html end def extract_body(html) if doc = Nokogiri::HTML::Document.parse(html) if body = doc.xpath('/html/body') return doc.xpath("//html/body").children.to_html end end return html end def cleanse_html(html) MyHtmlSanitizer.clean(html) end end end
Move describing of feature selections into a class method so that it can be also be used to describe an array of feature selections not yet associated with a basket item
class BasketItem < ActiveRecord::Base validates_numericality_of :quantity, :greater_than_or_equal_to => 1 belongs_to :product has_many :feature_selections, :order => :id, :dependent => :delete_all before_save :update_features def line_total quantity * product.price end # generates a text description of the features the customer has selected and # described for this item in the basket def update_features self.feature_descriptions = feature_selections.map {|fs| fs.description}.join('|') end end
class BasketItem < ActiveRecord::Base validates_numericality_of :quantity, :greater_than_or_equal_to => 1 belongs_to :product has_many :feature_selections, :order => :id, :dependent => :delete_all before_save :update_features def line_total quantity * product.price end def self.describe_feature_selections fs fs.map {|fs| fs.description}.join('|') end # generates a text description of the features the customer has selected and # described for this item in the basket def update_features self.feature_descriptions = BasketItem.describe_feature_selections(feature_selections) end end
Rename rspec_context var to context
module AssemblyLine class Constructor extend Forwardable def_delegators :rspec_context, :let, :before attr_reader :name, :code_block, :rspec_context, :options def initialize(name, code_block) @name = name @code_block = code_block end def assemble(context, options) @options = options @rspec_context = context instance_eval(&code_block) self end def invoke(*methods) if methods.any? invoke_in_setup *methods else invoke_in_setup name end end def depends_on(*constructors) if options[:depends_on] constructors = Array(options[:depends_on]) end constructors.each do |name| AssemblyLine.assemble(name, rspec_context) end end protected def invoke_in_setup(*methods) before(:all) do methods.each do |method_name| send(method_name) end end end end end
module AssemblyLine class Constructor extend Forwardable def_delegators :context, :let, :before attr_reader :name, :code_block, :context, :options def initialize(name, code_block) @name = name @code_block = code_block end def assemble(context, options) @options = options @context = context instance_eval(&code_block) self end def invoke(*methods) if methods.any? invoke_in_setup *methods else invoke_in_setup name end end def depends_on(*constructors) if options[:depends_on] constructors = Array(options[:depends_on]) end constructors.each do |name| AssemblyLine.assemble(name, context) end end protected def invoke_in_setup(*methods) before(:all) do methods.each do |method_name| send(method_name) end end end end end
Change aggregation flag check logic
module Jetpants class DB def aggregator? return @aggregator unless @aggregator.nil? version_info = query_return_array('SHOW VARIABLES LIKE "%version%"') @aggregator = !version_info[:version_comment].nil? && version_info[:version_comment].downcase.include?("mariadb") end end end
module Jetpants class DB def aggregator? return @aggregator unless @aggregator.nil? version_info = query_return_array('SHOW VARIABLES LIKE "version"') @aggregator = !version_info.nil? && !version_info.empty? && version_info.first[:Value].downcase.include?("mariadb") end end end
Add 'should require login' test
require 'test_helper' class ProductsControllerTest < ActionController::TestCase setup do @product = products(:one) @update = { title: 'Lorem Ipsum', description: 'Wibbles are fun!', image_url: 'Lorem.jpg', price: 19.95 } end test "should get index" do get :index assert_response :success assert_not_nil assigns(:products) end test "should get new" do get :new assert_response :success end test "should create product" do assert_difference('Product.count') do post :create, product: @update end assert_redirected_to product_path(assigns(:product)) end test "should show product" do get :show, id: @product assert_response :success end test "should get edit" do get :edit, id: @product assert_response :success end test "should update product" do patch :update, id: @product, product: @update assert_redirected_to product_path(assigns(:product)) end test "can't delete product in cart" do assert_difference('Product.count', 0) do delete :destroy, id: products(:ruby) end assert_redirected_to products_path end test "should destroy product" do assert_difference('Product.count', -1) do delete :destroy, id: @product end assert_redirected_to products_path end end
require 'test_helper' class ProductsControllerTest < ActionController::TestCase setup do @product = products(:one) @update = { title: 'Lorem Ipsum', description: 'Wibbles are fun!', image_url: 'Lorem.jpg', price: 19.95 } end test "should require login" do logout get :index assert_redirected_to login_path end test "should get index" do get :index assert_response :success assert_not_nil assigns(:products) end test "should get new" do get :new assert_response :success end test "should create product" do assert_difference('Product.count') do post :create, product: @update end assert_redirected_to product_path(assigns(:product)) end test "should show product" do get :show, id: @product assert_response :success end test "should get edit" do get :edit, id: @product assert_response :success end test "should update product" do patch :update, id: @product, product: @update assert_redirected_to product_path(assigns(:product)) end test "can't delete product in cart" do assert_difference('Product.count', 0) do delete :destroy, id: products(:ruby) end assert_redirected_to products_path end test "should destroy product" do assert_difference('Product.count', -1) do delete :destroy, id: @product end assert_redirected_to products_path end end
Add revert method for item revisions
class Podio::ItemDiff < ActivePodio::Base property :field_id, :integer property :type, :string property :external_id, :integer property :label, :string property :from, :array property :to, :array alias_method :id, :field_id class << self def find_by_item_and_revisions(item_id, revision_from_id, revision_to_id) list Podio.connection.get("/item/#{item_id}/revision/#{revision_from_id}/#{revision_to_id}").body end end end
class Podio::ItemDiff < ActivePodio::Base property :field_id, :integer property :type, :string property :external_id, :integer property :label, :string property :from, :array property :to, :array alias_method :id, :field_id class << self def find_by_item_and_revisions(item_id, revision_from_id, revision_to_id) list Podio.connection.get("/item/#{item_id}/revision/#{revision_from_id}/#{revision_to_id}").body end def revert(item_id, revision_id) Podio.connection.delete("/item/#{item_id}/revision/#{revision_id}").body end end end
Bump minimum required pry version to 0.13.0
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "pry-rails/version" Gem::Specification.new do |s| s.name = "pry-rails" s.version = PryRails::VERSION s.authors = ["Robin Wenglewski"] s.email = ["robin@wenglewski.de"] s.homepage = "https://github.com/rweng/pry-rails" s.summary = %q{Use Pry as your rails console} s.license = "MIT" s.required_ruby_version = ">= 1.9.1" # s.description = %q{TODO: Write a gem description} # s.rubyforge_project = "pry-rails" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_dependency "pry", ">= 0.10.4" s.add_development_dependency "appraisal" s.add_development_dependency "minitest" end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "pry-rails/version" Gem::Specification.new do |s| s.name = "pry-rails" s.version = PryRails::VERSION s.authors = ["Robin Wenglewski"] s.email = ["robin@wenglewski.de"] s.homepage = "https://github.com/rweng/pry-rails" s.summary = %q{Use Pry as your rails console} s.license = "MIT" s.required_ruby_version = ">= 1.9.1" # s.description = %q{TODO: Write a gem description} # s.rubyforge_project = "pry-rails" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_dependency "pry", ">= 0.13.0" s.add_development_dependency "appraisal" s.add_development_dependency "minitest" end
Add language defaults to Accounts and Organizations.
class AddLanguageToAccountsAndOrganizations < ActiveRecord::Migration def self.up add_column :accounts, :language, :string, :limit => 3 add_column :organizations, :language, :string, :limit => 3 end def self.down remove_column :accounts, :language remove_column :organizations, :language end end
class AddLanguageToAccountsAndOrganizations < ActiveRecord::Migration def self.up add_column :accounts, :language, :string, :limit => 3, :default => "eng" add_column :organizations, :language, :string, :limit => 3, :default => "eng" Account.update_all :language=>"eng" Organization.update_all :language=>"eng" end def self.down remove_column :accounts, :language remove_column :organizations, :language end end
Add class inherits Thor in the module
require "remindice/version" module Remindice # Your code goes here... end
require "remindice/version" require "thor" module Remindice class Commands < Thor end end
Fix lint issue with ToJson
module Mailosaur module Models class BaseModel def to_json hash = {} instance_variables.each do |var| key = var.to_s.delete('@').split('_').collect(&:capitalize).join key = key[0].downcase + key[1..-1] hash[key] = instance_variable_get var end hash.to_json end end end end
module Mailosaur module Models class BaseModel def to_json(*_args) hash = {} instance_variables.each do |var| key = var.to_s.delete('@').split('_').collect(&:capitalize).join key = key[0].downcase + key[1..-1] hash[key] = instance_variable_get var end hash.to_json end end end end
Add space around edge labels
require 'graphviz' require_relative 'edge' module Architect class Association < Edge attr_accessor :attributes, :graph TYPES = { "<>" => "odiamond", "+" => "odiamond", "++" => "diamond", "" => "none", ">" => "vee" } def initialize(node1, node2, markup="->") super node1, node2 @attributes = parse_markup(markup) end def parse_markup(markup) matches = /(.*)-(.*)/.match(markup) left = matches[1] right = matches[2] {arrowhead: get_arrow(right), arrowtail: get_arrow(left), headlabel: strip_arrow(right), taillabel: strip_arrow(left), dir: "both"} end def get_arrow(string) tokens = /([<>+]+)/.match(string) if tokens == nil return "none" else return TYPES[tokens[0]] end end def strip_arrow(string) return "" if string == nil TYPES.keys.each do |arrow| string = string.gsub(arrow, "") end return string end def graph(g) g.add_edges(@node1.graphnode, @node2.graphnode, @attributes) end end end
require 'graphviz' require_relative 'edge' module Architect class Association < Edge attr_accessor :attributes, :graph TYPES = { "<>" => "odiamond", "+" => "odiamond", "++" => "diamond", "" => "none", ">" => "vee" } def initialize(node1, node2, markup="->") super node1, node2 @attributes = parse_markup(markup) end def parse_markup(markup) matches = /(.*)-(.*)/.match(markup) left = matches[1] right = matches[2] {arrowhead: get_arrow(right), arrowtail: get_arrow(left), headlabel: " " + strip_arrow(right) + " ", taillabel: " " + strip_arrow(left) + " ", dir: "both"} end def get_arrow(string) tokens = /([<>+]+)/.match(string) if tokens == nil return "none" else return TYPES[tokens[0]] end end def strip_arrow(string) return "" if string == nil TYPES.keys.each do |arrow| string = string.gsub(arrow, "") end return string end def graph(g) g.add_edges(@node1.graphnode, @node2.graphnode, @attributes) end end end
Add Friendly ID to Course Model
class Course < ActiveRecord::Base attr_accessible :description, :logo, :title acts_as_list :scope => :club validates :title, :presence => { :message => "for course can't be blank" } validates :description, :presence => { :message => "for course can't be blank" } validates :club_id, :presence => true belongs_to :club has_many :lessons, :dependent => :destroy validates :title, :presence => { :message => "for course can't be blank" } validates :description, :presence => { :message => "for course can't be blank" } validates :club_id, :presence => true def user club.user end def assign_defaults self.title = Settings.courses[:default_title] self.description = Settings.courses[:default_description] self.logo = Settings.courses[:default_logo] end end
class Course < ActiveRecord::Base extend FriendlyId friendly_id :title, :use => [ :slugged, :history ] attr_accessible :description, :logo, :title acts_as_list :scope => :club validates :title, :presence => { :message => "for course can't be blank" } validates :description, :presence => { :message => "for course can't be blank" } validates :club_id, :presence => true belongs_to :club has_many :lessons, :dependent => :destroy validates :title, :presence => { :message => "for course can't be blank" } validates :description, :presence => { :message => "for course can't be blank" } validates :club_id, :presence => true def user club.user end def assign_defaults self.title = Settings.courses[:default_title] self.description = Settings.courses[:default_description] self.logo = Settings.courses[:default_logo] end private def should_generate_new_friendly_id? true end end
Add feature steps for editing user steps
Given(/^that I have a user called "(.*?)" surname "(.*?)" with username "(.*?)" and password "(.*?)"$/) do |firstname, surname, username, password| pending # express the regexp above with the code you wish you had end When(/^I update firstname to "(.*?)"$/) do |firstname| pending # express the regexp above with the code you wish you had end Then(/^I expect a search for firstname "(.*?)" to return nil$/) do |firstname| pending # express the regexp above with the code you wish you had end Then(/^If I search for firstname "(.*?)"$/) do |firstname| pending # express the regexp above with the code you wish you had end Then(/^I should get a user with firstname "(.*?)" surname "(.*?)" with username "(.*?)"$/) do |firstname, surname, username| pending # express the regexp above with the code you wish you had end
Rewrite master spec to use gold master testing.
require 'spec_helper' require 'open3' describe 'master task', task: true, test_construct: true do Given { @construct.file "Rakefile", <<END require 'quarto' Quarto.configure do |config| config.clear_stylesheets config.use :markdown config.metadata = false end END @construct.file "ch1.md", <<END <p>Before listing 0</p> ```ruby puts "hello, world" ``` <p>After listing 0</p> <img src="images/image1.png"/> END @construct.directory("images") do |d| d.file "image1.png", "IMAGE1" end @construct.file "ch2.md", <<END ```c int main(int argc, char** argv) { printf("Hello, world\n") } ``` END } When { run "rake master --trace --rules" } Then { pending "fix specs" expect(contents("build/master/master.xhtml")).to eq(<<END) <?xml version="1.0"?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:xi="http://www.w3.org/2001/XInclude" xml:base=".."> <head> <title>Untitled Book</title> <link rel="schema.DC" href="http://purl.org/dc/elements/1.1/"/> </head> <body> <p> Before listing 0 </p> <div class="highlight"><pre><span class="nb">puts</span> <span class="s2">"hello, world"</span> </pre></div> <p> After listing 0 </p> <p> <img src="images/image1.png"/> </p> <div class="highlight"><pre><span class="kt">int</span> <span class="nf">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span><span class="o">**</span> <span class="n">argv</span><span class="p">)</span> <span class="p">{</span> <span class="n">printf</span><span class="p">(</span><span class="s">"Hello, world</span> <span class="s">")</span> <span class="p">}</span> </pre></div> </body> </html> END } And { expect(contents("build/master/images/image1.png")).to eq("IMAGE1") } end
require 'spec_helper' require 'open3' describe "rake master", golden: true do specify "builds a master file and links in images" do populate_from("examples/images") run "rake master" expect("build/master/master.xhtml").to match_master expect("build/master/images/image1.png").to match_master end end
Add logged in to comment new controller
class CommentsController < ApplicationController def show @comment = Comment.find_by(id: params[:comment_id]) end def new @review = Review.find_by(id: params[:review_id]) @comment = Comment.new end def edit @review = Review.find_by(id: params[:review_id]) @comment = Comment.find_by(id: params[:comment_id]) if current_user != @comment.user redirect_to review_comments_path(@review, @comment) end end def create @review = Review.find_by(id: params[:review_id]) @comment = Comment.new(comment_params.merge(user: current_user, review: @review)) if @comment.save redirect_to @review else render 'new' end end def update @review = Review.find_by(id: params[:review_id]) @comment = Comment.find_by(id: params[:id]) if @comment.update(comment_params) redirect_to @review else render 'edit' end end def destroy @review = Review.find_by(id: params[:review_id]) @comment = Comment.find_by(id: params[:id]) if current_user != @comment.user @comment.destroy redirect_to review_comments_path else redirect_to @review end end private def comment_params params.require(:comment).permit(:body, :user_id, :review_id) end end
class CommentsController < ApplicationController def show @comment = Comment.find_by(id: params[:comment_id]) end def new @review = Review.find_by(id: params[:review_id]) @comment = Comment.new end def edit @review = Review.find_by(id: params[:review_id]) @comment = Comment.find_by(id: params[:comment_id]) if current_user != @comment.user redirect_to review_comments_path(@review, @comment) end end def create @review = Review.find_by(id: params[:review_id]) @comment = Comment.new(comment_params.merge(user: current_user, review: @review)) if logged_in? && @comment.save redirect_to @review else render 'new' end end def update @review = Review.find_by(id: params[:review_id]) @comment = Comment.find_by(id: params[:id]) if @comment.update(comment_params) redirect_to @review else render 'edit' end end def destroy @review = Review.find_by(id: params[:review_id]) @comment = Comment.find_by(id: params[:id]) if current_user != @comment.user @comment.destroy redirect_to review_comments_path else redirect_to @review end end private def comment_params params.require(:comment).permit(:body, :user_id, :review_id) end end
Add some tests for Logger::Colors
# GitCompound # module GitCompound describe Logger::Colors do before { GitCompound::Logger.colors = true } after { GitCompound::Logger.colors = false } context 'use #colorize() method' do it 'colorize output foreground' do expect('Test'.colorize(color: :black)).to include "\e[0;30;49mTest\e[0m" expect('Test'.colorize(color: :blue)).to include "\e[0;34;49mTest\e[0m" expect('Test'.colorize(color: :default)).to include "\e[0;39;49mTest\e[0m" end it 'colorize output background' do expect('Test'.colorize(bgcolor: :black)).to include "\e[0;39;40mTest\e[0m" expect('Test'.colorize(bgcolor: :blue)).to include "\e[0;39;44mTest\e[0m" expect('Test'.colorize(bgcolor: :default)).to include "\e[0;39;49mTest\e[0m" end it 'set output bold' do expect('Test'.colorize(mode: :bold)).to include "\e[1;39;49mTest\e[0m" end end context 'use instance methods (#on_{color}, #{color}, #bold)' do it 'colorize output foreground' do expect('Test'.black).to include "\e[0;30;49mTest\e[0m" expect('Test'.blue).to include "\e[0;34;49mTest\e[0m" end it 'colorize output background' do expect('Test'.on_black).to include "\e[0;39;40mTest\e[0m" expect('Test'.on_blue).to include "\e[0;39;44mTest\e[0m" end it 'set output bold' do expect('Test'.bold).to include "\e[1;39;49mTest\e[0m" end end end end
Add test to enforce that 'recursive' returns a Proc
require 'minitest/autorun' require 'ruby-function' describe "recursive" do it "creates a recursive function" do func = recursive { |this, i| if i < 1 i else this.call(i - 1) end } func.call(10).must_equal(0) end end
require 'minitest/autorun' require 'ruby-function' describe "recursive" do it "creates a recursive function" do func = recursive { |this, i| if i < 1 i else this.call(i - 1) end } func.call(10).must_equal(0) end it "returns an instance of Proc" do func = recursive { |this| this.call } func.kind_of?(Proc).must_equal true end end
Remove tests regarding old hypriot driver, we'r using upstream bin
require 'spec_helper' describe package('docker-machine') do it { should be_installed } end describe command('dpkg -l docker-machine') do its(:stdout) { should match /ii docker-machine/ } its(:stdout) { should match /0.7.0-18/ } its(:exit_status) { should eq 0 } end describe file('/usr/local/bin/docker-machine') do it { should be_file } it { should be_mode 755 } it { should be_owned_by 'root' } end describe command('docker-machine --version') do its(:stdout) { should match /0.7.0/m } its(:exit_status) { should eq 0 } end describe command('docker-machine create --help') do its(:stdout) { should match /Available drivers:.*hypriot/ } its(:stdout) { should match /--hypriot-ip-address/ } its(:stdout) { should match /--hypriot-ssh-key/ } its(:stdout) { should match /--hypriot-ssh-port/ } its(:stdout) { should match /--hypriot-ssh-user/ } # its(:stderr) { should match /^$/ } its(:exit_status) { should eq 0 } end
require 'spec_helper' describe package('docker-machine') do it { should be_installed } end describe command('dpkg -l docker-machine') do its(:stdout) { should match /ii docker-machine/ } its(:stdout) { should match /0.7.0-18/ } its(:exit_status) { should eq 0 } end describe file('/usr/local/bin/docker-machine') do it { should be_file } it { should be_mode 755 } it { should be_owned_by 'root' } end describe command('docker-machine --version') do its(:stdout) { should match /0.7.0/m } its(:exit_status) { should eq 0 } end
Remove extraneous "Usage:" prefix that's already output by mco.
class MCollective::Application::Puppetupdate < MCollective::Application description "Puppet repository updates Client" usage "Usage: mco puppetupdate update_all -T oyldn or mco puppetupdate [update <branch> [<sha1>]]" def post_option_parser(configuration) if ARGV.length >= 1 configuration[:command] = ARGV.shift unless configuration[:command] =~ /^update(_all)?$/ STDERR.puts "Don't understand command '#{configuration[:command]}', please use update <branch> [<sha1>] or update_all" exit 1 end configuration[:branch] = ARGV.shift if configuration[:command] == 'update' && configuration[:branch].nil? STDERR.puts "Don't understand update without a branch name" exit 1 end configuration[:revision] = ARGV.shift || '' else STDERR.puts "Please specify an action (update <branch>|update_all) on the command line" exit 1 end end def main return unless %w(update_all update).include? configuration[:command] mc = rpcclient("puppetupdate", :options => options) printrpc( mc.send(configuration[:command], :revision => configuration[:revision], :branch => configuration[:branch])) mc.disconnect printrpcstats end end
class MCollective::Application::Puppetupdate < MCollective::Application description "Puppet repository updates Client" usage "mco puppetupdate update_all -T oyldn or mco puppetupdate [update <branch> [<sha1>]]" def post_option_parser(configuration) if ARGV.length >= 1 configuration[:command] = ARGV.shift unless configuration[:command] =~ /^update(_all)?$/ STDERR.puts "Don't understand command '#{configuration[:command]}', please use update <branch> [<sha1>] or update_all" exit 1 end configuration[:branch] = ARGV.shift if configuration[:command] == 'update' && configuration[:branch].nil? STDERR.puts "Don't understand update without a branch name" exit 1 end configuration[:revision] = ARGV.shift || '' else STDERR.puts "Please specify an action (update <branch>|update_all) on the command line" exit 1 end end def main return unless %w(update_all update).include? configuration[:command] mc = rpcclient("puppetupdate", :options => options) printrpc( mc.send(configuration[:command], :revision => configuration[:revision], :branch => configuration[:branch])) mc.disconnect printrpcstats end end
Add rest of devs back to cc.rb notifications
Project.configure do |project| project.email_notifier.emails = ["scott@butlerpress.com"] # project.email_notifier.emails = ["scott@butlerpress.com", "al.pendergrass@gmail.com", "ryan@cyclocrazed.com"] project.build_command = "./script/cruise_build.rb #{project.name}" end
Project.configure do |project| project.email_notifier.emails = ["scott@butlerpress.com", "al.pendergrass@gmail.com", "ryan@cyclocrazed.com"] project.build_command = "./script/cruise_build.rb #{project.name}" end
Fix availability zone views when infra provider is not attached
module AvailabilityZoneHelper::TextualSummary # # Groups # def textual_group_relationships %i(ems_cloud instances) end def textual_group_tags %i(tags) end def textual_group_availability_zone_totals %i(block_storage_disk_capacity block_storage_disk_usage) end # # Items # def textual_ems_cloud textual_link(@record.ext_management_system) end def textual_instances label = ui_lookup(:tables => "vm_cloud") num = @record.number_of(:vms) h = {:label => label, :image => "vm", :value => num} if num > 0 && role_allows(:feature => "vm_show_list") h[:link] = url_for(:action => 'show', :id => @availability_zone, :display => 'instances') h[:title] = "Show all #{label}" end h end def textual_block_storage_disk_capacity return nil unless @record.respond_to?(:block_storage_disk_capacity) {:value => number_to_human_size(@record.block_storage_disk_capacity.gigabytes, :precision => 2)} end def textual_block_storage_disk_usage return nil unless @record.respond_to?(:block_storage_disk_usage) {:value => number_to_human_size(@record.block_storage_disk_usage.bytes, :precision => 2)} end end
module AvailabilityZoneHelper::TextualSummary # # Groups # def textual_group_relationships %i(ems_cloud instances) end def textual_group_tags %i(tags) end def textual_group_availability_zone_totals %i(block_storage_disk_capacity block_storage_disk_usage) end # # Items # def textual_ems_cloud textual_link(@record.ext_management_system) end def textual_instances label = ui_lookup(:tables => "vm_cloud") num = @record.number_of(:vms) h = {:label => label, :image => "vm", :value => num} if num > 0 && role_allows(:feature => "vm_show_list") h[:link] = url_for(:action => 'show', :id => @availability_zone, :display => 'instances') h[:title] = "Show all #{label}" end h end def textual_block_storage_disk_capacity return nil unless @record.respond_to?(:block_storage_disk_capacity) && !@record.ext_management_system.provider.nil? {:value => number_to_human_size(@record.block_storage_disk_capacity.gigabytes, :precision => 2)} end def textual_block_storage_disk_usage return nil unless @record.respond_to?(:block_storage_disk_usage) {:value => number_to_human_size(@record.block_storage_disk_usage.bytes, :precision => 2)} end end
Use autoload like everywhere else
module Dockly::BuildCache end require 'dockly/build_cache/base' require 'dockly/build_cache/docker' require 'dockly/build_cache/local' module Dockly::BuildCache class << self attr_writer :model def model @model ||= Dockly::BuildCache::Docker end end end
module Dockly::BuildCache end module Dockly::BuildCache autoload :Base, 'dockly/build_cache/base' autoload :Docker, 'dockly/build_cache/docker' autoload :Local, 'dockly/build_cache/local' class << self attr_writer :model def model @model ||= Dockly::BuildCache::Docker end end end
Make interface of avatar helper methods consistent.
module Admin::AvatarHelper def avatar_url(email, size) gravatar_id = Digest::MD5.hexdigest(email.downcase) "http://gravatar.com/avatar/#{gravatar_id}.png?s=#{size}" end def small_avatar_image(user) image_tag avatar_url(user.email, 25) end def large_avatar_image(user) image_tag avatar_url(user.email, 50) end end
module Admin::AvatarHelper def avatar_url(user, size) gravatar_id = Digest::MD5.hexdigest(user.email.downcase) "http://gravatar.com/avatar/#{gravatar_id}.png?s=#{size}" end def small_avatar_image(user) image_tag avatar_url(user, 25) end def large_avatar_image(user) image_tag avatar_url(user, 50) end end
Fix horrible initialization code in test
require 'test_helper' describe Kiitos::Kiito do before do @subject = Kiitos::Kiito.new @subject.title = 'Title' @subject.kiitos_category_id = 1 @subject.description = 'Description' @subject.image = 'image' end it 'is invalid without a title' do @subject.title = nil @subject.valid?.must_equal false end it 'is invalid without a category' do @subject.kiitos_category_id = nil @subject.valid?.must_equal false end it 'is invalid without an image name' do @subject.image = nil @subject.valid?.must_equal false end end
require 'test_helper' describe Kiitos::Kiito do before do @subject = Kiitos::Kiito.new( title: 'Title', kiitos_category_id: 1, description: 'Description', image: 'image' ) end it 'is invalid without a title' do @subject.title = nil @subject.valid?.must_equal false end it 'is invalid without a category' do @subject.kiitos_category_id = nil @subject.valid?.must_equal false end it 'is invalid without an image name' do @subject.image = nil @subject.valid?.must_equal false end end
Allow TAs to see assignment summaries page
class SummariesController < ApplicationController include SummariesHelper before_filter :authorize_only_for_admin def index @assignment = Assignment.find(params[:assignment_id]) @section_column = '' if Section.all.size > 0 @section_column = "{ id: 'section', content: '" + I18n.t(:'summaries_index.section') + "', sortable: true }," end @criteria = @assignment.get_criteria end def populate @assignment = Assignment.find(params[:assignment_id]) if @current_user.ta? render json: get_summaries_table_info(@assignment, @current_user.id) else render json: get_summaries_table_info(@assignment) end end end
class SummariesController < ApplicationController include SummariesHelper before_filter :authorize_for_ta_and_admin def index @assignment = Assignment.find(params[:assignment_id]) @section_column = '' if Section.all.size > 0 @section_column = "{ id: 'section', content: '" + I18n.t(:'summaries_index.section') + "', sortable: true }," end @criteria = @assignment.get_criteria end def populate @assignment = Assignment.find(params[:assignment_id]) if @current_user.ta? render json: get_summaries_table_info(@assignment, @current_user.id) else render json: get_summaries_table_info(@assignment) end end end
Call anonymous functions for child abilities as well
module Brewery class AuthCore::Ability @@extra_classes = [] include CanCan::Ability attr_accessor :object def self.add_extra_ability_class_name(class_name) @@extra_classes << class_name.constantize end def initialize(user, extra_parameters) self.object = user @@extra_classes.each do |extra_class| extra_class.new(user, self, extra_parameters) end anonymous and return if user.nil? if user.has_role? :superadmin can :access, :admin can :manage, AuthCore::User end if user.has_role? :admin_user can :access, :admin can :manage, AuthCore::User end can :update, user can :destroy, AuthCore::UserSession end private def anonymous can :manage, AuthCore::UserSession can :create, AuthCore::User end end end
module Brewery class AuthCore::Ability @@extra_classes = [] include CanCan::Ability attr_accessor :object, :extras def self.add_extra_ability_class_name(class_name) @@extra_classes << class_name.constantize end def initialize(user, extra_parameters) self.object = user self.extras = [] @@extra_classes.each do |extra_class| extras << extra_class.new(user, self, extra_parameters) end anonymous and return if user.nil? if user.has_role? :superadmin can :access, :admin can :manage, AuthCore::User end if user.has_role? :admin_user can :access, :admin can :manage, AuthCore::User end can :update, user can :destroy, AuthCore::UserSession end private def anonymous can :manage, AuthCore::UserSession can :create, AuthCore::User extras.each do |extra| extra.anonymous if extra.respond_to?(:anonymous) end end end end
Undo commit 0616e068 - needed for unit testing
require 'activerecord' require 'invoicing/class_info' # load first because other modules depend on this Dir.glob(File.join(File.dirname(__FILE__), 'invoicing/**/*.rb')).sort.each {|f| require f } # Mix all modules Invoicing::*::ActMethods into ActiveRecord::Base as class methods Invoicing.constants.map{|c| Invoicing.const_get(c) }.select{|m| m.is_a?(Module) && m.const_defined?('ActMethods') }.each{ |m| ActiveRecord::Base.send(:extend, m.const_get('ActMethods')) }
$:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) require 'activerecord' require 'invoicing/class_info' # load first because other modules depend on this Dir.glob(File.join(File.dirname(__FILE__), 'invoicing/**/*.rb')).sort.each {|f| require f } # Mix all modules Invoicing::*::ActMethods into ActiveRecord::Base as class methods Invoicing.constants.map{|c| Invoicing.const_get(c) }.select{|m| m.is_a?(Module) && m.const_defined?('ActMethods') }.each{ |m| ActiveRecord::Base.send(:extend, m.const_get('ActMethods')) }
Add friends endpoint stub (TODO)
class UserController < ApplicationController def show user = User.find(params[:id]).to_json render json: user end def create user_params = params.require(:user).permit(:name) user = User.create(user_params) if user render json: { head: :ok } else render json: { head: :bad_request, message: 'Unable to create user' } end end end
class UserController < ApplicationController def show user = User.find(params[:id]).to_json render json: user end def create user_params = params.require(:user).permit(:name) user = User.create(user_params) if user render json: { head: :ok } else render json: { head: :bad_request, message: 'Unable to create user' } end end def friends # TODO end end
Add a FluxCapacitor class so we can capacitate our flux
module GitTimeMachine class FluxCapacitor class NoFuelError < RuntimeError; end def initialize @plutonium = nil end def setup @plutonium = :weapons_grade end def capacitate! raise NoFuelError unless plutonium_present? @flux = :capacitated end def capacitated? flux == :capacitated end private attr_reader :flux attr_reader :plutonium def plutonium_present? !plutonium.nil? end end end
Update gemspec to fix deprecation warning.
$LOAD_PATH.push File.expand_path('../lib', __FILE__) require 'forgery/version' Gem::Specification.new do |spec| spec.name = 'forgery' spec.version = Forgery::VERSION spec.authors = ['Nathan Sutton', 'Brandon Arbini', 'Kamil Kieliszczyk'] spec.email = ['nate@zencoder.com', 'brandon@zencoder.com', 'kamil@kieliszczyk.net'] spec.homepage = 'http://github.com/sevenwire/forgery' spec.summary = 'Easy and customizable generation of forged data.' spec.description = 'Easy and customizable generation of forged data. Can be used as a gem or a rails plugin. Includes rails generators for creating your own forgeries.' spec.platform = Gem::Platform::RUBY spec.required_rubygems_version = '>= 1.3.6' spec.rubyforge_project = 'forgery' spec.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR) spec.test_files = `git ls-files spec`.split($INPUT_RECORD_SEPARATOR) spec.require_paths = %w[lib] spec.add_development_dependency 'bundler', '~> 1.16.0' end
# frozen_string_literal: true $LOAD_PATH.push File.expand_path('lib', __dir__) require 'forgery/version' Gem::Specification.new do |spec| spec.name = 'forgery' spec.version = Forgery::VERSION spec.authors = ['Nathan Sutton', 'Brandon Arbini', 'Kamil Kieliszczyk'] spec.email = ['nate@zencoder.com', 'brandon@zencoder.com', 'kamil@kieliszczyk.net'] spec.homepage = 'http://github.com/sevenwire/forgery' spec.summary = 'Easy and customizable generation of forged data.' spec.description = 'Easy and customizable generation of forged data. Can be used as a gem or a rails plugin. Includes rails generators for creating your own forgeries.' spec.platform = Gem::Platform::RUBY spec.required_rubygems_version = '>= 1.3.6' spec.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR) spec.test_files = `git ls-files spec`.split($INPUT_RECORD_SEPARATOR) spec.require_paths = %w[lib] spec.add_development_dependency 'bundler', '~> 1.16.0' end
Use $stdin instead of STDIN
require 'colored' module Conversable # rubocop:disable Rails/Output def alert(msg) puts msg.red end def notify(msg) puts msg.green end def ask?(msg) puts msg.yellow STDIN.gets.chomp! end # rubocop:enable Rails/Output def confirm?(msg) case ask?(msg) when 'Y', 'y', 'yes', 'YES' true else false end end end
require 'colored' module Conversable # rubocop:disable Rails/Output def alert(msg) puts msg.red end def notify(msg) puts msg.green end def ask?(msg) puts msg.yellow $stdin.gets.chomp! end # rubocop:enable Rails/Output def confirm?(msg) case ask?(msg) when 'Y', 'y', 'yes', 'YES' true else false end end end
Add a base external request spec
require 'spec_helper' RSpec.describe 'External request', feature: true do it 'queries organization repos on Github' do uri = URI('https://api.github.com/orgs/github/repos') response = JSON.load(Net::HTTP.get(uri)) expect(response.first['owner']['login']).to eq 'octocat' end end
Revert "removing duplicated code: this is already in ControllerHelpers::Auth"
class Spree::UserSessionsController < Devise::SessionsController helper 'spree/base' include Spree::Core::ControllerHelpers::Auth include Spree::Core::ControllerHelpers::Common include Spree::Core::ControllerHelpers::Order include Spree::Core::ControllerHelpers::Store def create authenticate_spree_user! if spree_user_signed_in? respond_to do |format| format.html { flash[:success] = Spree.t(:logged_in_succesfully) redirect_back_or_default(after_sign_in_path_for(spree_current_user)) } format.js { render :json => {:user => spree_current_user, :ship_address => spree_current_user.ship_address, :bill_address => spree_current_user.bill_address}.to_json } end else respond_to do |format| format.html { flash.now[:error] = t('devise.failure.invalid') render :new } format.js { render :json => { error: t('devise.failure.invalid') }, status: :unprocessable_entity } end end end private def accurate_title Spree.t(:login) end end
class Spree::UserSessionsController < Devise::SessionsController helper 'spree/base' include Spree::Core::ControllerHelpers::Auth include Spree::Core::ControllerHelpers::Common include Spree::Core::ControllerHelpers::Order include Spree::Core::ControllerHelpers::Store def create authenticate_spree_user! if spree_user_signed_in? respond_to do |format| format.html { flash[:success] = Spree.t(:logged_in_succesfully) redirect_back_or_default(after_sign_in_path_for(spree_current_user)) } format.js { render :json => {:user => spree_current_user, :ship_address => spree_current_user.ship_address, :bill_address => spree_current_user.bill_address}.to_json } end else respond_to do |format| format.html { flash.now[:error] = t('devise.failure.invalid') render :new } format.js { render :json => { error: t('devise.failure.invalid') }, status: :unprocessable_entity } end end end private def accurate_title Spree.t(:login) end def redirect_back_or_default(default) redirect_to(session["spree_user_return_to"] || default) session["spree_user_return_to"] = nil end end
Revert "Add NOT NULL constraint"
class CreateDaimonNewsAdminPosts < ActiveRecord::Migration def change create_table :daimon_news_admin_posts do |t| t.string :title t.text :body t.references :daimon_news_admin_site, index: true, foreign_key: true, null: false t.timestamps null: false end end end
class CreateDaimonNewsAdminPosts < ActiveRecord::Migration def change create_table :daimon_news_admin_posts do |t| t.string :title t.text :body t.references :daimon_news_admin_site, index: true, foreign_key: true t.timestamps null: false end end end
Fix typo in Slim documentation
# encoding: utf-8 require 'slim' module Nanoc::Filters # @since 3.2.0 class Slim < Nanoc::Filter # Runs the content through [Slim](http://slim-lang.com/) # This method takes no options. # # @param [String] content The content to filter # # @return [String] The filtered content def run(content, params={}) params = { :disable_capture => true, # Capture managed by nanoc :buffer => '_erbout', # Force slim to output to the buffer used by nanoc }.merge params # Create context context = ::Nanoc::Context.new(assigns) ::Slim::Template.new(params) { content }.render(context) { assigns[:content] } end end end
# encoding: utf-8 require 'slim' module Nanoc::Filters # @since 3.2.0 class Slim < Nanoc::Filter # Runs the content through [Slim](http://slim-lang.com/). # This method takes no options. # # @param [String] content The content to filter # # @return [String] The filtered content def run(content, params={}) params = { :disable_capture => true, # Capture managed by nanoc :buffer => '_erbout', # Force slim to output to the buffer used by nanoc }.merge params # Create context context = ::Nanoc::Context.new(assigns) ::Slim::Template.new(params) { content }.render(context) { assigns[:content] } end end end
Use single quotes for style, not performance
require "faraday" require "faraday_middleware" require "json" require "hashie/mash" require "addressable/uri" require 'environs' require "buffer/version" require "buffer/core" require "buffer/user" require "buffer/profile" require "buffer/update" require "buffer/link" require "buffer/error" require "buffer/encode" require "buffer/datastructure" require "buffer/info" require "buffer/client" require "buffer/setup" module Buffer end
require 'faraday' require 'faraday_middleware' require 'json' require 'hashie/mash' require 'addressable/uri' require 'environs' require 'buffer/version' require 'buffer/core' require 'buffer/user' require 'buffer/profile' require 'buffer/update' require 'buffer/link' require 'buffer/error' require 'buffer/encode' require 'buffer/datastructure' require 'buffer/info' require 'buffer/client' require 'buffer/setup' module Buffer end
Raise an error if we can't find an explicitly enabled plugin.
plugins = EnterprisePluginCollection.from_glob("/opt/*/chef-server-plugin.rb") plugins.each do |p| next if !p.parent_plugin.nil? p.enabled true if node['private_chef']['enabled-plugins'].include?(p.name) p.enabled false if node['private_chef']['disabled-plugins'].include?(p.name) end plugins.each do |plugin| next if !plugin.parent_plugin.nil? chef_run plugin.run_list do cookbook_path plugin.cookbook_path included_attrs ["private_chef"] end end
plugins = EnterprisePluginCollection.from_glob("/opt/*/chef-server-plugin.rb") plugins.each do |p| next if !p.parent_plugin.nil? p.enabled true if node['private_chef']['enabled-plugins'].include?(p.name) p.enabled false if node['private_chef']['disabled-plugins'].include?(p.name) end missing_plugins = node['private_chef']['enabled-plugins'] - (plugins.map {|p| p.name }) if !missing_plugins.empty? raise "could not find plugins: #{missing_plugins}" end plugins.each do |plugin| next if !plugin.parent_plugin.nil? chef_run plugin.run_list do cookbook_path plugin.cookbook_path included_attrs ["private_chef"] end end
Use validation with association name instead of foreign key
class Comment < ActiveRecord::Base attr_accessible :content belongs_to :commentable, polymorphic: true belongs_to :user validates_presence_of :user_id end
class Comment < ActiveRecord::Base attr_accessible :content belongs_to :commentable, polymorphic: true belongs_to :user validates_presence_of :user end
Add method in job to fetch total commit count for project
module GithubCommitsJob extend self def run Project.with_github_url.each do |project| update_user_commit_counts_for(project) end end private def update_user_commit_counts_for(project) contributors = get_contributor_stats(project.github_repo) contributors.map do |contributor| user = User.find_by_github_username(contributor.author.login) CommitCount.find_or_initialize_by(user: user, project: project).update(commit_count: contributor.total) if user end end def get_contributor_stats(repo) loop do contributors = Octokit.contributor_stats(repo) return contributors unless contributors.nil? Rails.logger.warn "Waiting for Github to calculate project statistics for #{repo}" sleep 3 end end end
require 'nokogiri' module GithubCommitsJob extend self def run Project.with_github_url.each do |project| update_total_commit_count_for(project) update_user_commit_counts_for(project) end end private def update_total_commit_count_for(project) doc = Nokogiri::HTML(open(project.github_url)) commit_count = doc.at_css('li.commits .num').text.strip.gsub(',', '').to_i project.update(commit_count: commit_count) end def update_user_commit_counts_for(project) contributors = get_contributor_stats(project.github_repo) contributors.map do |contributor| user = User.find_by_github_username(contributor.author.login) CommitCount.find_or_initialize_by(user: user, project: project).update(commit_count: contributor.total) if user end end def get_contributor_stats(repo) loop do contributors = Octokit.contributor_stats(repo) return contributors unless contributors.nil? Rails.logger.warn "Waiting for Github to calculate project statistics for #{repo}" sleep 3 end end end
Fix spelling error in student controller
class StudentMemberController < ApplicationController before_action :authenticate_student_member! def index # render plain: params.inspect # ensure that only student member who # is logged in can see his/her own # record. @thisID = current_student_member.id @allties = TieAlumniWithStudentMember.where({ :StudentMember_id => "#{current_student_member.id}" }) # @allties = TieAlumniWithStudentMember.where(" \"StudentMember_id\" = #{current_student_member.id}") @allalums = Array.new @allties.each do |this_tie| @allalums.push(Alumni.find(this_tie.alumni_id)) end end end
class StudentMemberController < ApplicationController before_action :authenticate_student_member! def index # render plain: params.inspect # ensure that only student member who # is logged in can see his/her own # record. @thisID = current_student_member.id @allties = TieAlumniWithStudentMember.where({ :StudentMember_id => "#{current_student_member.id}" }) # @allties = TieAlumniWithStudentMember.where(" \"StudentMember_id\" = #{current_student_member.id}") @allalums = Array.new @allties.each do |this_tie| @allalums.push(Alumni.find(this_tie.Alumni_id)) end end end
Add an example program. This example shows how to validate an entire string and accumulate information on all validation errors.
# encoding: utf-8 # # Show how to parse a full string with multiple UTF8 validation failures. # Accumulate error information, and report it. # require 'rubygems' unless RUBY_VERSION =~ /1\.9/ require 'utf8_validator' # # = Purpose # # A helper class for processing multiple validation errors in a single string. # class ValidationHelper # attr_reader :error_list # # Get a validator instance. # def initialize @validator = UTF8::Validator.new end # # Validate the whole string. # def scanstring(string) @error_list = "" work_string = string run_pos = 0 begin @validator.valid_encoding?(work_string, true) rescue UTF8::ValidationError => e # Extract offset of error, keep running offset up to date last_colon = e.message.rindex(':') last_lparen = e.message.rindex('(') epos = e.message[last_colon+1..last_lparen-1] sub_start = epos.to_i if run_pos == 0 run_pos += sub_start else run_pos += sub_start + 1 end # Start again at error offset + 1 work_string = work_string[sub_start+1..-1] # Build next error message next_emsg = e.message[0..last_colon] # Part A of current message # Add running offset position run_pos_str = sprintf "%d(0x%x)", run_pos, run_pos next_emsg += run_pos_str # @error_list += next_emsg @error_list += "\n" retry end end end # puts "Started" puts # helper = ValidationHelper.new # test_data = [ "a\xffbc\xfed", "abcdefghijk\xffbcdefghijk\xfecdefg", "anoerrorsz", "errorlast\x80", "a\xffbcd\xfeefgh\xfd123", ] # test_data.each do |string| puts "/" * 60 puts "#{string}" helper.scanstring(string) puts "#{helper.error_list}" end # puts puts "Complete"
Add logged in and current user helpers
module ApplicationHelper end
module ApplicationHelper def logged_in? !!session[:user_id] end def current_user @current_user || User.find(session[:user_id]) if logged_in? end end
Reduce the number of queries to find if member has seed of this crop
module CropsHelper def display_seed_availability(member, crop) total_quantity = 0 seeds = member.seeds.select { |seed| seed.crop.name == crop.name } seeds.each do |seed| total_quantity += seed.quantity if seed.quantity end return "You don't have any seeds of this crop." if seeds.none? if total_quantity != 0 "You have #{total_quantity} #{Seed.model_name.human(count: total_quantity)} of this crop." else "You have an unknown quantity of seeds of this crop." end end def crop_ebay_seeds_url(crop) "https://rover.ebay.com/rover/1/705-53470-19255-0/1?icep_ff3=9&pub=5575213277&toolid=10001&campid=5337940151&customid=&icep_uq=#{CGI.escape crop.name}&icep_sellerId=&icep_ex_kw=&icep_sortBy=12&icep_catId=181003&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229515&kwid=902099&mtid=824&kw=lg" # rubocop:disable Metrics/LineLength end end
module CropsHelper def display_seed_availability(member, crop) seeds = member.seeds.where(crop: crop) total_quantity = seeds.where.not(quantity: nil).sum(:quantity) return "You don't have any seeds of this crop." if seeds.none? if total_quantity != 0 "You have #{total_quantity} #{Seed.model_name.human(count: total_quantity)} of this crop." else "You have an unknown quantity of seeds of this crop." end end def crop_ebay_seeds_url(crop) "https://rover.ebay.com/rover/1/705-53470-19255-0/1?icep_ff3=9&pub=5575213277&toolid=10001&campid=5337940151&customid=&icep_uq=#{CGI.escape crop.name}&icep_sellerId=&icep_ex_kw=&icep_sortBy=12&icep_catId=181003&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229515&kwid=902099&mtid=824&kw=lg" # rubocop:disable Metrics/LineLength end end
Add nokogiri dependency, fill out TODO fields
Gem::Specification.new do |spec| spec.name = "lita-wolfram-alpha" spec.version = "0.1.0" spec.authors = ["Tristan Chong"] spec.email = ["tristanchong@gmail.com"] spec.description = "TODO: Add a description" spec.summary = "TODO: Add a summary" spec.homepage = "TODO: Add a homepage" spec.license = "TODO: Add a license" spec.metadata = { "lita_plugin_type" => "handler" } 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_runtime_dependency "lita", ">= 4.3" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "pry-byebug" spec.add_development_dependency "rake" spec.add_development_dependency "rack-test" spec.add_development_dependency "rspec", ">= 3.0.0" spec.add_development_dependency "simplecov" spec.add_development_dependency "coveralls" end
Gem::Specification.new do |spec| spec.name = "lita-wolfram-alpha" spec.version = "0.1.0" spec.authors = ["Tristan Chong"] spec.email = ["ong@tristaneuan.ch"] spec.description = "A Lita handler that performs Wolfram Alpha queries." spec.summary = "A Lita handler that performs Wolfram Alpha queries." spec.homepage = "https://github.com/tristaneuan/lita-wolfram-alpha" spec.license = "MIT" spec.metadata = { "lita_plugin_type" => "handler" } 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_runtime_dependency "lita", ">= 4.3" spec.add_runtime_dependency "nokogiri", ">= 1.6.6" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "pry-byebug" spec.add_development_dependency "rake" spec.add_development_dependency "rack-test" spec.add_development_dependency "rspec", ">= 3.0.0" spec.add_development_dependency "simplecov" spec.add_development_dependency "coveralls" end
Use a .com domain that belongs to us for localhost resolution.
Given /^the application is set up$/ do # Using lvh.me to give us automatic resolution to localhost # N.B. This means some Cucumber scenarios will fail if your machine # isn't connected to the internet. We shoud probably fix this. # # Port needs to be saved for Selenium tests (because our app code considers # the port as well as the hostname when figuring out how to handle a # request, and the Capybara app server doesn't run on port 80). # # When using the rack-test driver, don't use port numbers at all, # since it makes our test-session-resetting code (see features/support/capybara_domains.rb) # more complicated. port_segment = Capybara.current_driver == :selenium ? ":#{Capybara.server_port}" : '' Setting[:base_domain] = "lvh.me#{port_segment}" Setting[:signup_domain] = "create.lvh.me#{port_segment}" end When /^the domain is the signup domain$/ do step %Q{the domain is "#{Setting[:signup_domain].sub(/:\d+$/, '')}"} end
Given /^the application is set up$/ do # Using ocolocalhost.com to give us automatic resolution to localhost # N.B. This means some Cucumber scenarios will fail if your machine # isn't connected to the internet. We shoud probably fix this. # # Port needs to be saved for Selenium tests (because our app code considers # the port as well as the hostname when figuring out how to handle a # request, and the Capybara app server doesn't run on port 80). # # When using the rack-test driver, don't use port numbers at all, # since it makes our test-session-resetting code (see features/support/capybara_domains.rb) # more complicated. port_segment = Capybara.current_driver == :selenium ? ":#{Capybara.server_port}" : '' Setting[:base_domain] = "ocolocalhost.com#{port_segment}" Setting[:signup_domain] = "create.ocolocalhost.com#{port_segment}" end When /^the domain is the signup domain$/ do step %Q{the domain is "#{Setting[:signup_domain].sub(/:\d+$/, '')}"} end
Fix a failing migration when running on a v1.x DB.
class ConvertProposalsToStateMachine < ActiveRecord::Migration class Proposal < ActiveRecord::Base; end def self.up add_column :proposals, :state, :string Proposal.all.each do |proposal| if proposal.accepted == 1 proposal.state = "accepted" elsif proposal.open == 1 proposal.state = "open" else proposal.state = "rejected" end proposal.save! end remove_column :proposals, :open remove_column :proposals, :accepted end def self.down add_column :proposals, :accepted, :integer, :limit => 1, :default => 0 add_column :proposals, :open, :integer, :limit => 1, :default => 1 Proposal.all.each do |proposal| case proposal.state when "accepted" proposal.open = 0 proposal.accepted = 1 when "open" proposal.open = 1 proposal.accepted = 0 when "rejected" proposal.open = 0 proposal.accepted = 0 end proposal.save! end remove_column :proposals, :state end end
class ConvertProposalsToStateMachine < ActiveRecord::Migration class ::Proposal < ActiveRecord::Base; end # Old databases being migrated from v1.x may have old class names in the # 'type' column, which causes an error when running this migration. # Temporarily define this class to work around this error. class ::FoundOrganisationProposal < Proposal; end def self.up add_column :proposals, :state, :string Proposal.all.each do |proposal| if proposal.accepted == 1 proposal.state = "accepted" elsif proposal.open == 1 proposal.state = "open" else proposal.state = "rejected" end proposal.save!(:validate => false) end remove_column :proposals, :open remove_column :proposals, :accepted end def self.down add_column :proposals, :accepted, :integer, :limit => 1, :default => 0 add_column :proposals, :open, :integer, :limit => 1, :default => 1 Proposal.all.each do |proposal| case proposal.state when "accepted" proposal.open = 0 proposal.accepted = 1 when "open" proposal.open = 1 proposal.accepted = 0 when "rejected" proposal.open = 0 proposal.accepted = 0 end proposal.save! end remove_column :proposals, :state end end
Add specs for ConfigFile helper.
require 'spec_helper' describe ConfigFile do pending "Add some tests" end
require 'spec_helper' describe ConfigFile do describe '.read' do let(:config_path) { File.join('rspec_config.yaml') } before do ConfigFile.stub(:get_path).and_return(config_path) File.unlink(config_path) if File.exists?(config_path) end after do File.unlink(config_path) if File.exists?(config_path) end context 'when no config file exists' do it 'logs an error' do expected_error = "Config file unavailable -- no log file found in #{config_path}" Logger.should_receive(:log).with(expected_error) ConfigFile.read end end context 'when an empty config file exists' do it 'returns an empty hash' do File.open(config_path, 'w'){|file| file.write( YAML.dump(nil) ) } ConfigFile.read.should eql Hash.new end end context 'when a config file exists' do let(:config_vars) { {'foo' => 'bar'} } before do File.open(config_path, 'w'){|file| file.write( YAML.dump(config_vars) ) } end it 'returns the contents of the file, deserialized from YAML' do ConfigFile.read['foo'].should eql 'bar' end end context 'when a config file exists containing ERB' do it 'returns the ERB-processed file, deserialized from YAML' do File.open(config_path, 'w'){|file| file.write( "---\nfoo: <%= 'baz' %>\n" ) } ConfigFile.read['foo'].should eql 'baz' end end end end
Replace `create` with `build` in adjustment metadata model specs
require 'spec_helper' describe AdjustmentMetadata do it "is valid when build from factory" do adjustment = create(:adjustment) expect(adjustment).to be_valid end end
require 'spec_helper' describe AdjustmentMetadata do it "is valid when built from factory" do adjustment = build(:adjustment) expect(adjustment).to be_valid end end
Update list of required files.
Gem::Specification.new do |s| s.name = "shield" s.version = "2.1.0" s.summary = %{Generic authentication protocol for rack applications.} s.description = %Q{ Provides all the protocol you need in order to do authentication on your rack application. The implementation specifics can be found in http://github.com/cyx/shield-contrib } s.authors = ["Michel Martens", "Damian Janowski", "Cyril David"] s.email = ["michel@soveran.com", "djanowski@dimaion.com", "me@cyrildavid.com"] s.homepage = "http://github.com/cyx/shield" s.files = Dir[ "README*", "LICENSE", "Rakefile", "lib/**/*.rb", "test/**/*.rb" ] s.add_dependency "armor" s.add_development_dependency "cutest" s.add_development_dependency "rack-test" end
Gem::Specification.new do |s| s.name = "shield" s.version = "2.1.0" s.summary = %{Generic authentication protocol for rack applications.} s.description = %Q{ Provides all the protocol you need in order to do authentication on your rack application. The implementation specifics can be found in http://github.com/cyx/shield-contrib } s.authors = ["Michel Martens", "Damian Janowski", "Cyril David"] s.email = ["michel@soveran.com", "djanowski@dimaion.com", "me@cyrildavid.com"] s.homepage = "http://github.com/cyx/shield" s.files = Dir[ "README*", "LICENSE", "lib/**/*.rb", "test/**/*.rb", "*.gemspec" ] s.add_dependency "armor" s.add_development_dependency "cutest" s.add_development_dependency "rack-test" end
Use RSpec >= 1.1.12 so 1.2 can be used as well
require 'pathname' require 'rubygems' gem 'rspec', '~>1.1.12' require 'spec' ROOT = Pathname(__FILE__).dirname.parent.expand_path # use local dm-types if running from dm-more directly lib = ROOT.parent.join('dm-types', 'lib').expand_path $LOAD_PATH.unshift(lib) if lib.directory? require ROOT + 'lib/dm-is-remixable' def load_driver(name, default_uri) return false if ENV['ADAPTER'] != name.to_s begin DataMapper.setup(name, ENV["#{name.to_s.upcase}_SPEC_URI"] || default_uri) DataMapper::Repository.adapters[:default] = DataMapper::Repository.adapters[name] true rescue LoadError => e warn "Could not load do_#{name}: #{e}" false end end ENV['ADAPTER'] ||= 'sqlite3' HAS_SQLITE3 = load_driver(:sqlite3, 'sqlite3::memory:') HAS_MYSQL = load_driver(:mysql, 'mysql://localhost/dm_core_test') HAS_POSTGRES = load_driver(:postgres, 'postgres://postgres@localhost/dm_core_test')
require 'pathname' require 'rubygems' gem 'rspec', '>=1.1.12' require 'spec' ROOT = Pathname(__FILE__).dirname.parent.expand_path # use local dm-types if running from dm-more directly lib = ROOT.parent.join('dm-types', 'lib').expand_path $LOAD_PATH.unshift(lib) if lib.directory? require ROOT + 'lib/dm-is-remixable' def load_driver(name, default_uri) return false if ENV['ADAPTER'] != name.to_s begin DataMapper.setup(name, ENV["#{name.to_s.upcase}_SPEC_URI"] || default_uri) DataMapper::Repository.adapters[:default] = DataMapper::Repository.adapters[name] true rescue LoadError => e warn "Could not load do_#{name}: #{e}" false end end ENV['ADAPTER'] ||= 'sqlite3' HAS_SQLITE3 = load_driver(:sqlite3, 'sqlite3::memory:') HAS_MYSQL = load_driver(:mysql, 'mysql://localhost/dm_core_test') HAS_POSTGRES = load_driver(:postgres, 'postgres://postgres@localhost/dm_core_test')
Interpolate default from: in Notifier
class Notifier < ActionMailer::Base default from: 'noreply@opencasebook.org', sent_on: Proc.new { Time.now } def password_reset_instructions(user) @token = user.perishable_token @edit_password_reset_url = edit_password_reset_url(user.perishable_token) mail(to: user.email_address, subject: "H2O Password Reset Instructions") end def verification_request(user) @verification_url = verify_user_url(user, token: user.perishable_token) @user_name = user.display_name mail(to: user.email_address, subject: "H2O: Verify your email address") end def verification_notice(user) mail(to: user.email_address, subject: "Welcome to H2O. Your account has been verified") end end
class Notifier < ActionMailer::Base default from: ENV["EXCEPTION_EMAIL_SENDER"], sent_on: Proc.new { Time.now } def password_reset_instructions(user) @token = user.perishable_token @edit_password_reset_url = edit_password_reset_url(user.perishable_token) mail(to: user.email_address, subject: "H2O Password Reset Instructions") end def verification_request(user) @verification_url = verify_user_url(user, token: user.perishable_token) @user_name = user.display_name mail(to: user.email_address, subject: "H2O: Verify your email address") end def verification_notice(user) mail(to: user.email_address, subject: "Welcome to H2O. Your account has been verified") end end
Update React Native documentation (0.30)
module Docs class ReactNative < React self.name = 'React Native' self.slug = 'react_native' self.type = 'react' self.release = '0.29' self.base_url = 'https://facebook.github.io/react-native/docs/' self.root_path = 'getting-started.html' self.links = { home: 'https://facebook.github.io/react-native/', code: 'https://github.com/facebook/react-native' } html_filters.push 'react_native/clean_html' options[:root_title] = 'React Native Documentation' options[:only_patterns] = nil options[:skip_patterns] = [/\Asample\-/] options[:skip] = %w( videos.html transforms.html troubleshooting.html more-resources.html ) options[:fix_urls] = ->(url) { url.sub! 'docs/docs', 'docs' url } options[:attribution] = <<-HTML &copy; 2016 Facebook Inc.<br> Licensed under the Creative Commons Attribution 4.0 International Public License. HTML end end
module Docs class ReactNative < React self.name = 'React Native' self.slug = 'react_native' self.type = 'react' self.release = '0.30' self.base_url = 'https://facebook.github.io/react-native/docs/' self.root_path = 'getting-started.html' self.links = { home: 'https://facebook.github.io/react-native/', code: 'https://github.com/facebook/react-native' } html_filters.push 'react_native/clean_html' options[:root_title] = 'React Native Documentation' options[:only_patterns] = nil options[:skip_patterns] = [/\Asample\-/] options[:skip] = %w( videos.html transforms.html troubleshooting.html more-resources.html ) options[:fix_urls] = ->(url) { url.sub! 'docs/docs', 'docs' url } options[:attribution] = <<-HTML &copy; 2016 Facebook Inc.<br> Licensed under the Creative Commons Attribution 4.0 International Public License. HTML end end
Refactor lazy load method definitions
module ActiveZuora module LazyAttr # This is meant to be included onto an Invoice class. # Returns true/false on success. # Result hash is stored in #result. # If success, the id will be set in the object. # If failure, errors will be present on object. extend ActiveSupport::Concern included do include Base end def fetch_field(field_name) return nil unless self.id query_string = "select #{self.class.get_field!(field_name).zuora_name} from #{zuora_object_name} where Id = '#{self.id}'" response = self.class.connection.request(:query){ |soap| soap.body = { :query_string => query_string } } response[:query_response][:result][:records][field_name.to_sym] end private :fetch_field module ClassMethods def lazy_load(*field_names) (@lazy_loadded_fields ||= []).concat field_names.map(&:to_sym) instance_eval do @lazy_loadded_fields.each do |field_name| field_var = "@#{field_name}" define_method field_name do instance_variable_get(field_var) || instance_variable_set(field_var, fetch_field(field_name)) end end end end end end end
module ActiveZuora module LazyAttr # This is meant to be included onto an Invoice class. # Returns true/false on success. # Result hash is stored in #result. # If success, the id will be set in the object. # If failure, errors will be present on object. extend ActiveSupport::Concern included do include Base end def fetch_field(field_name) return nil unless self.id query_string = "select #{self.class.get_field!(field_name).zuora_name} from #{zuora_object_name} where Id = '#{self.id}'" response = self.class.connection.request(:query){ |soap| soap.body = { :query_string => query_string } } response[:query_response][:result][:records][field_name.to_sym] end private :fetch_field module ClassMethods def lazy_load(*field_names) Array(field_names).map(&:to_sym).each do |field_name| define_lazy_feild field_name end end def define_lazy_feild(field) instance_eval do define_method field do instance_variable_get("@#{field}") || instance_variable_set(field, fetch_field("@#{field}")) end end end end end end
Configure ActiveJob to use Sidekiq
require_relative './boot' require 'active_model/railtie' require 'active_job/railtie' require 'active_record/railtie' require 'action_controller/railtie' require 'action_mailer/railtie' require 'action_view/railtie' require 'sprockets/railtie' Bundler.require(*Rails.groups) module RecordOfGuidance class Application < Rails::Application config.active_record.raise_in_transactional_callbacks = true end end
require_relative './boot' require 'active_model/railtie' require 'active_job/railtie' require 'active_record/railtie' require 'action_controller/railtie' require 'action_mailer/railtie' require 'action_view/railtie' require 'sprockets/railtie' Bundler.require(*Rails.groups) module RecordOfGuidance class Application < Rails::Application config.active_job.queue_adapter = :sidekiq config.active_record.raise_in_transactional_callbacks = true end end
Add missing require for migration_helper
Sequel.migration do up do create_table(:config, charset: 'utf8') do primary_key :id String :name, null: false String :type, null: false String :value, type: PactBroker::MigrationHelper.large_text_type DateTime :created_at, null: false DateTime :updated_at, null: false index [:name], unique: true, unique_constraint_name: 'unq_config_name' end end end
require_relative 'migration_helper' Sequel.migration do up do create_table(:config, charset: 'utf8') do primary_key :id String :name, null: false String :type, null: false String :value, type: PactBroker::MigrationHelper.large_text_type DateTime :created_at, null: false DateTime :updated_at, null: false index [:name], unique: true, unique_constraint_name: 'unq_config_name' end end end
Include tracking url in shipping_method show template
object @shipment cache [I18n.locale, root_object] attributes *shipment_attributes node(:order_id) { |shipment| shipment.order.number } node(:stock_location_name) { |shipment| shipment.stock_location.name } child shipping_rates: :shipping_rates do extends 'spree/api/v1/shipping_rates/show' end child selected_shipping_rate: :selected_shipping_rate do extends 'spree/api/v1/shipping_rates/show' end child shipping_methods: :shipping_methods do attributes :id, :name child zones: :zones do attributes :id, :name, :description end child shipping_categories: :shipping_categories do attributes :id, :name end end child manifest: :manifest do child variant: :variant do extends 'spree/api/v1/variants/small' end node(:quantity, &:quantity) node(:states, &:states) end
object @shipment cache [I18n.locale, root_object] attributes *shipment_attributes node(:order_id) { |shipment| shipment.order.number } node(:stock_location_name) { |shipment| shipment.stock_location.name } child shipping_rates: :shipping_rates do extends 'spree/api/v1/shipping_rates/show' end child selected_shipping_rate: :selected_shipping_rate do extends 'spree/api/v1/shipping_rates/show' end child shipping_methods: :shipping_methods do attributes :id, :name, :tracking_url child zones: :zones do attributes :id, :name, :description end child shipping_categories: :shipping_categories do attributes :id, :name end end child manifest: :manifest do child variant: :variant do extends 'spree/api/v1/variants/small' end node(:quantity, &:quantity) node(:states, &:states) end
Update rubocop to version 0.91.0
# frozen_string_literal: true require_relative 'lib/filewatcher' require_relative 'lib/filewatcher/version' Gem::Specification.new do |s| s.name = 'filewatcher' s.version = Filewatcher::VERSION s.authors = ['Thomas Flemming', 'Alexander Popov'] s.email = ['thomas.flemming@gmail.com', 'alex.wayfer@gmail.com'] s.homepage = 'http://github.com/filewatcher/filewatcher' s.summary = 'Lightweight filewatcher.' s.description = 'Detect changes in file system. Works anywhere.' s.files = Dir[File.join('{lib,spec}', '**', '{*,.*}')] s.licenses = ['MIT'] s.required_ruby_version = '~> 2.4' s.add_development_dependency 'bundler', '~> 2.0' s.add_development_dependency 'rake', '~> 13.0' s.add_development_dependency 'rspec', '~> 3.8' s.add_development_dependency 'rubocop', '~> 0.90.0' s.add_development_dependency 'rubocop-performance', '~> 1.5' s.add_development_dependency 'rubocop-rspec', '~> 1.43' end
# frozen_string_literal: true require_relative 'lib/filewatcher' require_relative 'lib/filewatcher/version' Gem::Specification.new do |s| s.name = 'filewatcher' s.version = Filewatcher::VERSION s.authors = ['Thomas Flemming', 'Alexander Popov'] s.email = ['thomas.flemming@gmail.com', 'alex.wayfer@gmail.com'] s.homepage = 'http://github.com/filewatcher/filewatcher' s.summary = 'Lightweight filewatcher.' s.description = 'Detect changes in file system. Works anywhere.' s.files = Dir[File.join('{lib,spec}', '**', '{*,.*}')] s.licenses = ['MIT'] s.required_ruby_version = '~> 2.4' s.add_development_dependency 'bundler', '~> 2.0' s.add_development_dependency 'rake', '~> 13.0' s.add_development_dependency 'rspec', '~> 3.8' s.add_development_dependency 'rubocop', '~> 0.91.0' s.add_development_dependency 'rubocop-performance', '~> 1.5' s.add_development_dependency 'rubocop-rspec', '~> 1.43' end
Create constant for minimum number of players
require 'gosu' # Defines application wide constants. module Constants MAJOR_VERSION = "0" MINOR_VERSION = "0" PATCH = "0" VERSION = [MAJOR_VERSION, MINOR_VERSION, PATCH].join(".") IMAGE_PATH = 'assets/images/' SOUND_PATH = 'assets/sounds/' SOUND_EFFECTS_PATH = SOUND_PATH + 'effects/' # The name of the font to use for text FONT_NAME = Gosu::default_font_name # The text height of the buttons BT_TEXT_HEIGHT = 30 # The standard text height TEXT_HEIGHT = 30 # The maximum number of players. MAX_PLAYERS = 4 end
require 'gosu' # Defines application wide constants. module Constants MAJOR_VERSION = "0" MINOR_VERSION = "0" PATCH = "0" VERSION = [MAJOR_VERSION, MINOR_VERSION, PATCH].join(".") IMAGE_PATH = 'assets/images/' SOUND_PATH = 'assets/sounds/' SOUND_EFFECTS_PATH = SOUND_PATH + 'effects/' # The name of the font to use for text FONT_NAME = Gosu::default_font_name # The text height of the buttons BT_TEXT_HEIGHT = 30 # The standard text height TEXT_HEIGHT = 30 # The maximum number of players. MAX_PLAYERS = 4 # The minimum number of players. MIN_PLAYERS = 2 end
Add code comment about where the auth comes from
class IepStorer def initialize(file_name:, path_to_file:, file_date:, local_id:, client:, logger:) @file_name = file_name @path_to_file = path_to_file @file_date = file_date @local_id = local_id @client = client @logger = logger end def store @student = Student.find_by_local_id(@local_id) return @logger.info("student not in db!") unless @student return unless store_object_in_s3 store_object_in_database end def store_object_in_s3 @logger.info("storing iep for student to s3...") response = @client.put_object( bucket: ENV['AWS_S3_IEP_BUCKET'], key: @file_name, body: File.open(@path_to_file), server_side_encryption: 'AES256' ) return false unless response @logger.info(" successfully stored to s3!") @logger.info(" encrypted with: #{response[:server_side_encryption]}") return true end def store_object_in_database @logger.info("storing iep for student to db.") IepDocument.create!( file_date: @file_date, file_name: @file_name, student: @student ) end end
class IepStorer def initialize(file_name:, path_to_file:, file_date:, local_id:, client:, logger:) @file_name = file_name @path_to_file = path_to_file @file_date = file_date @local_id = local_id @client = client @logger = logger end def store @student = Student.find_by_local_id(@local_id) return @logger.info("student not in db!") unless @student return unless store_object_in_s3 store_object_in_database end def store_object_in_s3 # Client is supplied with the proper creds via # ENV['AWS_ACCESS_KEY_ID'] and ENV['AWS_SECRET_ACCESS_KEY'] @logger.info("storing iep for student to s3...") response = @client.put_object( bucket: ENV['AWS_S3_IEP_BUCKET'], key: @file_name, body: File.open(@path_to_file), server_side_encryption: 'AES256' ) return false unless response @logger.info(" successfully stored to s3!") @logger.info(" encrypted with: #{response[:server_side_encryption]}") return true end def store_object_in_database @logger.info("storing iep for student to db.") IepDocument.create!( file_date: @file_date, file_name: @file_name, student: @student ) end end
Reorder documents so featuring a doc is quicker
class Admin::EditionWorldLocationsController < Admin::BaseController before_filter :find_world_location before_filter :find_edition_world_location, except: :index before_filter :limit_edition_world_location_access!, except: :index def index @featured_editions = @world_location.featured_edition_world_locations @editions = @world_location.published_edition_world_locations end def edit @edition_world_location.featured = true @edition_world_location.build_image end def update attributes = params[:edition_world_location] if attributes[:featured] == "false" attributes[:image] = nil attributes[:alt_text] = nil end if @edition_world_location.update_attributes(attributes) redirect_to admin_world_location_featurings_path(@edition_world_location.world_location) else @edition_world_location.build_image unless @edition_world_location.image.present? render :edit end end private def find_world_location @world_location = WorldLocation.find(params[:world_location_id]) end def find_edition_world_location @edition_world_location = @world_location.edition_world_locations.find(params[:id]) end def limit_edition_world_location_access! unless @edition_world_location.edition.accessible_by?(current_user) render "admin/editions/forbidden", status: 403 end end end
class Admin::EditionWorldLocationsController < Admin::BaseController before_filter :find_world_location before_filter :find_edition_world_location, except: :index before_filter :limit_edition_world_location_access!, except: :index def index @featured_editions = @world_location.featured_edition_world_locations @editions = @world_location.published_edition_world_locations.order("editions.public_timestamp DESC") end def edit @edition_world_location.featured = true @edition_world_location.build_image end def update attributes = params[:edition_world_location] if attributes[:featured] == "false" attributes[:image] = nil attributes[:alt_text] = nil end if @edition_world_location.update_attributes(attributes) redirect_to admin_world_location_featurings_path(@edition_world_location.world_location) else @edition_world_location.build_image unless @edition_world_location.image.present? render :edit end end private def find_world_location @world_location = WorldLocation.find(params[:world_location_id]) end def find_edition_world_location @edition_world_location = @world_location.edition_world_locations.find(params[:id]) end def limit_edition_world_location_access! unless @edition_world_location.edition.accessible_by?(current_user) render "admin/editions/forbidden", status: 403 end end end
Stop setting activerecord time to local
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module CalendarSync class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. config.time_zone = 'Pacific Time (US & Canada)' config.active_record.default_timezone = :local # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true end end
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module CalendarSync class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. config.time_zone = 'Pacific Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true end end
Change to allow any bundler version
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'tty/spinner/version' Gem::Specification.new do |spec| spec.name = 'tty-spinner' spec.version = TTY::Spinner::VERSION spec.authors = ['Piotr Murach'] spec.email = ['pmurach@gmail.com'] spec.summary = %q{A terminal spinner for tasks that have non-deterministic time frame.} spec.description = %q{A terminal spinner for tasks that have non-deterministic time frame.} spec.homepage = "https://piotrmurach.github.io/tty" spec.license = 'MIT' spec.files = Dir['{lib,spec,examples}/**/*.rb'] spec.files += Dir['{bin,tasks}/*', 'tty-spinner.gemspec'] spec.files += Dir['README.md', 'CHANGELOG.md', 'LICENSE.txt', 'Rakefile'] spec.require_paths = ['lib'] spec.required_ruby_version = '>= 2.0.0' spec.add_runtime_dependency 'tty-cursor', '~> 0.6.0' spec.add_development_dependency 'bundler', '>= 1.5.0', '< 2.0' spec.add_development_dependency 'rspec', '~> 3.1' spec.add_development_dependency 'rake' end
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'tty/spinner/version' Gem::Specification.new do |spec| spec.name = 'tty-spinner' spec.version = TTY::Spinner::VERSION spec.authors = ['Piotr Murach'] spec.email = ['pmurach@gmail.com'] spec.summary = %q{A terminal spinner for tasks that have non-deterministic time frame.} spec.description = %q{A terminal spinner for tasks that have non-deterministic time frame.} spec.homepage = "https://piotrmurach.github.io/tty" spec.license = 'MIT' spec.files = Dir['{lib,spec,examples}/**/*.rb'] spec.files += Dir['{bin,tasks}/*', 'tty-spinner.gemspec'] spec.files += Dir['README.md', 'CHANGELOG.md', 'LICENSE.txt', 'Rakefile'] spec.require_paths = ['lib'] spec.required_ruby_version = '>= 2.0.0' spec.add_runtime_dependency 'tty-cursor', '~> 0.6.0' spec.add_development_dependency 'bundler' spec.add_development_dependency 'rspec', '~> 3.1' spec.add_development_dependency 'rake' end
Remove default type value for orders table
class RemoveDefaultTypeForOrders < ActiveRecord::Migration[5.0] def up change_column_default(:paypal_orders, :type, nil) end def down change_column_default(:paypal_orders, :type, "PaypalOrder") end end
Remove last remaining page cache
class ThemeController < ContentController def stylesheets render_theme_item(:stylesheets, params[:filename], 'text/css; charset=utf-8') end def javascript render_theme_item(:javascript, params[:filename], 'text/javascript; charset=utf-8') end def images render_theme_item(:images, params[:filename]) end def fonts render_theme_item(:fonts, params[:filename]) end def error head :not_found end def static_view_test; end private def render_theme_item(type, file, mime = nil) mime ||= mime_for(file) if file.split(%r{[\\/]}).include?('..') return (render 'errors/404', status: 404, formats: ['html']) end src = this_blog.current_theme.path + "/#{type}/#{file}" return (render plain: 'Not Found', status: 404) unless File.exist? src cache_page File.read(src) if perform_caching send_file(src, type: mime, disposition: 'inline', stream: true) end def mime_for(filename) case filename.downcase when /\.js$/ 'text/javascript' when /\.css$/ 'text/css' when /\.gif$/ 'image/gif' when /(\.jpg|\.jpeg)$/ 'image/jpeg' when /\.png$/ 'image/png' when /\.swf$/ 'application/x-shockwave-flash' else 'application/binary' end end end
class ThemeController < ContentController def stylesheets render_theme_item(:stylesheets, params[:filename], 'text/css; charset=utf-8') end def javascript render_theme_item(:javascript, params[:filename], 'text/javascript; charset=utf-8') end def images render_theme_item(:images, params[:filename]) end def fonts render_theme_item(:fonts, params[:filename]) end def error head :not_found end def static_view_test; end private def render_theme_item(type, file, mime = nil) mime ||= mime_for(file) if file.split(%r{[\\/]}).include?('..') return (render 'errors/404', status: 404, formats: ['html']) end src = this_blog.current_theme.path + "/#{type}/#{file}" return (render plain: 'Not Found', status: 404) unless File.exist? src send_file(src, type: mime, disposition: 'inline', stream: true) end def mime_for(filename) case filename.downcase when /\.js$/ 'text/javascript' when /\.css$/ 'text/css' when /\.gif$/ 'image/gif' when /(\.jpg|\.jpeg)$/ 'image/jpeg' when /\.png$/ 'image/png' when /\.swf$/ 'application/x-shockwave-flash' else 'application/binary' end end end
Add basic rspec tests for the task model.
require 'spec_helper' describe Task do before(:each) do @task = InstanceTask.new( {} ) end it "should begin in a queued state" do @task.state.should eql('queued') end it "should be invalid with unknown type" do @task.should be_valid @task.type = 'TotallyInvalidTask' @task.should_not be_valid end it "should be invalid with unknown state" do @task.should be_valid @task.state = 'BetYouDidNotExpectThisState' @task.should_not be_valid end it "should be able to get canceled" do @task.cancel @task.state.should eql('canceled') end it "should provide a type label" do @task.type_label.should eql('Instance') end end
Add tests for Qubell::Revision class
require 'rspec' module Qubell describe Revision do let(:config) { FactoryGirl.build :configuration } let(:revision) { FactoryGirl.build :revision } let(:revision_url) { "#{config.endpoint}/revisions/#{revision.id}" } let(:instances) { FactoryGirl.build_list(:instance, 2) } describe '#instances' do before do stub_request(:get, "#{revision_url}/instances") .to_return( status: 200, body: instances.to_json, headers: { :'Content-type' => 'application/json' }) end it 'return array of application instances' do expect(revision.instances).to match_array(instances) end end end end
Use lowercase extention name for content type lookup
require 'sinatra/base' require 'mountable_image_server/image_locator' require 'mountable_image_server/image_processor' module MountableImageServer class Server < Sinatra::Base get '/:fid' do |fid| locator = ImageLocator.new(MountableImageServer.config.sources) if path = locator.path_for(fid) image_processor = ImageProcessor.new(path, params) image_processor.run do |processed_image_path| content_type(Rack::Mime::MIME_TYPES.fetch(processed_image_path.extname)) body(processed_image_path.read) end else halt(404) end end end end
require 'sinatra/base' require 'mountable_image_server/image_locator' require 'mountable_image_server/image_processor' module MountableImageServer class Server < Sinatra::Base get '/:fid' do |fid| locator = ImageLocator.new(MountableImageServer.config.sources) if path = locator.path_for(fid) image_processor = ImageProcessor.new(path, params) image_processor.run do |processed_image_path| content_type(Rack::Mime::MIME_TYPES.fetch(processed_image_path.extname.downcase)) body(processed_image_path.read) end else halt(404) end end end end
Use a sane separator in comma
class Bot::Plugin::Pick < Bot::Plugin def initialize(bot) @s = { trigger: { pick: [:pick, 0, 'pick [n=1] item1 item2 item3'], shuffle: [:shuffle, 0, 'shuffle item1 item2 item3'], dice: [:dice, 0, 'dice [n=6]'] }, subscribe: false } super(bot) end def pick(m) picks = m.args[0] =~ /[0-9]+/ ? m.args[0].to_i : 1 m.reply m.args[1..-1].sample(picks).join(', ') end def shuffle(m) m.reply m.args.shuffle.join(', ') end def dice(m) sides = !m.args.empty? ? m.args[0].to_i : 6 m.reply Random.rand(sides) end end
class Bot::Plugin::Pick < Bot::Plugin def initialize(bot) @s = { trigger: { pick: [:pick, 0, 'pick [n=1] item1 item2 item3'], shuffle: [:shuffle, 0, 'shuffle item1 item2 item3'], dice: [:dice, 0, 'dice [n=6]'] }, subscribe: false } super(bot) end def pick(m) picks_arg = m.args[0] =~ /[0-9]+/ picks = picks_arg ? m.args[0].to_i : 1 picks = picks > 2_147_483_647 ? 2_147_483_647 : picks starting_index = numeric?(picks_arg) ? 1 : 0 m.reply m.args[starting_index..-1].join(' ').split(',').sample(picks).map(&:strip).join(', ') end def shuffle(m) m.reply m.args.join(' ').split(',').shuffle.map(&:strip).join(', ') end def dice(m) sides = !m.args.empty? ? m.args[0].to_i : 6 m.reply Random.rand(sides) end def numeric?(obj) obj.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/).nil? ? false : true end end
Fix a breaking test. Want to keep these working until we switch over to specs entirely.
require File.dirname(__FILE__) + '/../test_helper' require 'resourceful/serialize' class SerializeTest < Test::Unit::TestCase fixtures :parties, :people, :parties_people def test_should_generate_hash_for_model assert_equal(hash_for_fun_party, parties(:fun_party).to_resourceful_hash([:name, {:people => [:name]}])) end def test_to_s_should_return_format assert_equal({'party' => hash_for_fun_party}, YAML.load(parties(:fun_party).serialize(:yaml, :attributes => [:name, {:people => [:name]}]))) end end
require File.dirname(__FILE__) + '/../test_helper' require 'resourceful/serialize' class SerializeTest < Test::Unit::TestCase fixtures :parties, :people, :parties_people def test_should_generate_hash_for_model assert_equal(hash_for_fun_party, parties(:fun_party).to_serializable([:name, {:people => [:name]}])) end def test_to_s_should_return_format assert_equal({'party' => hash_for_fun_party}, YAML.load(parties(:fun_party).serialize(:yaml, :attributes => [:name, {:people => [:name]}]))) end end
Add tests to ensure proper behavior of the Multiplication Table Class
require_relative '../lib/multiplication_table.rb' describe MultiplicationTable do it 'outputs a prime multiplication table to a matrix' end
require_relative '../lib/multiplication_table.rb' describe MultiplicationTable do let(:three) { [2, 3, 5] } it 'is a Multiplication Table Object' do expect(MultiplicationTable.new(three, three)).to be_a MultiplicationTable end it 'can transform a prime multiplication table to a matrix' do expect(MultiplicationTable.new(three, three).table).to eq([[nil, 2, 3, 5], [2, 4, 6, 10], [3, 6, 9, 15], [5, 10, 15, 25]]) end it 'can transform any set of numbers in an array to a matrix' do expect(MultiplicationTable.new([1, 2, 3], [4, 5, 6]).table).to eq([[nil, 1, 2, 3], [4, 4, 8, 12], [5, 5, 10, 15], [6, 6, 12, 18]]) end end
Improve err message in case of concurrent update
# frozen_string_literal: true class Api::V1::ApiMdaUpdaterController < Api::ApiController def check_mda_update raise Api::StaleObjectError.new("Analysis has been updated concurrently by another user.") if current_update_time > (request_time + 1.second) end def current_update_time raise "Cannot check mda update: Analysis not set" if @mda.nil? @mda.updated_at end def request_time raise "Cannot check mda update: Request time unknown. Set 'requested_at' parameter." if params[:requested_at].nil? DateTime.parse(params[:requested_at]) end end
# frozen_string_literal: true class Api::V1::ApiMdaUpdaterController < Api::ApiController def check_mda_update errmsg = "Analysis has been updated concurrently by another user. Please refresh and retry." raise Api::StaleObjectError.new(errmsg) if current_update_time > (request_time + 1.second) end def current_update_time raise "Cannot check mda update: Analysis not set" if @mda.nil? @mda.updated_at end def request_time raise "Cannot check mda update: Request time unknown. Set 'requested_at' parameter." if params[:requested_at].nil? DateTime.parse(params[:requested_at]) end end
Add a spec to ensure Javascript is filtered
require 'spec_helper' describe ApplicationHelper do describe '#markdown' do context 'string without HTML code' do let(:markdown_string) { '**hello**' } it 'renders string in Markdown as HTML' do helper.markdown(markdown_string).strip.should eq '<p><strong>hello</strong></p>' end end context 'string contains HTML code' do let(:markdown_string) { '<b class="class">abc</b>' } it 'HTML entities are escaped' do helper.markdown(markdown_string).strip.should eq '<p>abc</p>' end end end end
require 'spec_helper' describe ApplicationHelper do describe '#markdown' do context 'string without HTML code' do let(:markdown_string) { '**hello**' } it 'renders string in Markdown as HTML' do helper.markdown(markdown_string).strip.should eq '<p><strong>hello</strong></p>' end end context 'string contains HTML code' do let(:markdown_string) { '<b class="class">abc</b>' } it 'HTML entities are filtered' do helper.markdown(markdown_string).strip.should eq '<p>abc</p>' end end context 'string contains Javascript code' do let(:markdown_string) { "<script type='text/javascript'>alert('hello');</script>" } it '<script> tags are filtered, quotes are escaped' do helper.markdown(markdown_string).strip.should eq "<p>alert(&#39;hello&#39;);</p>" end end end end
Update link to homepage in podspec
Pod::Spec.new do |s| s.name = 'RxKeyboard' s.version = '0.4.1' s.summary = 'Reactive Keyboard in iOS' s.homepage = 'https://github.com/devxoul/RxKeyboard' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'Suyeol Jeon' => 'devxoul@gmail.com' } s.source = { :git => 'https://github.com/RxSwiftCommunity/RxKeyboard.git', :tag => s.version.to_s } s.source_files = 'Sources/*.swift' s.frameworks = 'UIKit', 'Foundation' s.requires_arc = true s.dependency 'RxSwift', '>= 3.0' s.dependency 'RxCocoa', '>= 3.0' s.ios.deployment_target = '8.0' s.pod_target_xcconfig = { 'SWIFT_VERSION' => '3.0' } end
Pod::Spec.new do |s| s.name = 'RxKeyboard' s.version = '0.4.1' s.summary = 'Reactive Keyboard in iOS' s.homepage = 'https://github.com/RxSwiftCommunity/RxKeyboard' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'Suyeol Jeon' => 'devxoul@gmail.com' } s.source = { :git => 'https://github.com/RxSwiftCommunity/RxKeyboard.git', :tag => s.version.to_s } s.source_files = 'Sources/*.swift' s.frameworks = 'UIKit', 'Foundation' s.requires_arc = true s.dependency 'RxSwift', '>= 3.0' s.dependency 'RxCocoa', '>= 3.0' s.ios.deployment_target = '8.0' s.pod_target_xcconfig = { 'SWIFT_VERSION' => '3.0' } end
Enable Rollbar only on production and staging environments
require 'rollbar/rails' Rollbar.configure do |config| config.access_token = Cartodb.config[:rollbar_api_key] # Add exception class names to the exception_level_filters hash to # change the level that exception is reported at. Note that if an exception # has already been reported and logged the level will need to be changed # via the rollbar interface. # Valid levels: 'critical', 'error', 'warning', 'info', 'debug', 'ignore' # 'ignore' will cause the exception to not be reported at all. # config.exception_level_filters.merge!('MyCriticalException' => 'critical') end module CartoDB def self.notify_exception(e, extra) user = extra.delete(:user) request = extra.delete(:request) Rollbar.report_exception(e, request, user) end end
require 'rollbar/rails' Rollbar.configure do |config| config.access_token = Cartodb.config[:rollbar_api_key] config.enabled = Rails.env.production? || Rails.env.staging? # Add exception class names to the exception_level_filters hash to # change the level that exception is reported at. Note that if an exception # has already been reported and logged the level will need to be changed # via the rollbar interface. # Valid levels: 'critical', 'error', 'warning', 'info', 'debug', 'ignore' # 'ignore' will cause the exception to not be reported at all. # config.exception_level_filters.merge!('MyCriticalException' => 'critical') end module CartoDB def self.notify_exception(e, extra) user = extra.delete(:user) request = extra.delete(:request) Rollbar.report_exception(e, request, user) end end
Fix ES search results size to 10000
# This class tries to reproduce an ActiveRecord relation class ElasticsearchRelation def initialize(params = {}) @params = params end def offset(x) @params[:from] = x @params[:size] ||= 10 self end def limit(x) @params[:size] = x self end def all Annotation.search(@params).results.map(&:load).reject{ |x| x.nil? } end def count Annotation.search(@params.merge({ size: 0 })).total end def to_a all end end
# This class tries to reproduce an ActiveRecord relation class ElasticsearchRelation def initialize(params = {}) @params = params.merge({ size: 10000 }) end def offset(x) @params[:from] = x self end def limit(x) @params[:size] = x self end def all Annotation.search(@params).results.map(&:load).reject{ |x| x.nil? } end def count Annotation.search(@params).total end def to_a all end end