Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add model methods for installer report info
class InstallerReport < ActiveRecord::Base end
class InstallerReport < ActiveRecord::Base # some helpers for extracting info out of the body text dump def cache_dir find /^Writeable cache dir: (.*)$/ end def saved_jar find /^Local jar url: (.*)$/ end def local_address find /^local_socket_address = (.*)$ / end def using_temp_dir? find(/^Writing to a (temp directory)!$/) == "temp directory" end # expects a regular expression with at least one capture group. # if more than one capture group is present, only the first group value will be reported def find(regexp) self.body[regexp] ? $1 : "not found" end end
Add the generation of the migration file
class RefinerycmsTranslations < Refinery::Generators::EngineInstaller source_root File.expand_path('../../', __FILE__) engine_name "translations" end
class RefinerycmsTranslations < Refinery::Generators::EngineInstaller source_root File.expand_path('../../', __FILE__) raise 'bouh' engine_name "translations" translation_root = Pathname.new(File.expand_path(File.dirname(__FILE__) << "/../..")) rails_root = if defined?(Rails.root) Rails.root elsif defined?(RAILS_ROOT) Pathname.new(RAILS_ROOT) else Pathname.new(ARGV.first) end if rails_root.exist? [%w(db migrate)].each do |dir| rails_root.join(dir.join(File::SEPARATOR)).mkpath end copies = [ {:from => %w(db migrate), :to => %w(db migrate), :filename => "20100705210405_create_translations.rb"} ] copies.each do |copy| copy_from = translation_root.join(copy[:from].join(File::SEPARATOR), copy[:filename]) copy_to = rails_root.join(copy[:to].join(File::SEPARATOR), copy[:filename]) unless copy_to.exist? FileUtils::copy_file copy_from.to_s, copy_to.to_s else puts "'#{File.join copy[:to], copy[:filename]}' already existed in your application so your existing file was not overwritten." end end puts "---------" puts "Copied refinerycms-translation migration files." puts "Now, run rake db:migrate" puts "Make sure 'i18n_frontend_translation_locales' and 'i18n_translation_default_frontend_locale' are defined to fit your needs in your Refinery Setting" else puts "Please specify the path of the project that you want to use the translation with, i.e. refinerycms-translation-install /path/to/project" end end
Add first unit test for IosRatingsFetcherForItunesConnect
require 'test_helper' class IosRatingsFetcherForItunesConnectTest < Minitest::Test def setup @ios_ratings_fetcher = AppReputation::IosRatingsFetcherForItunesConnect.new end def test_send_request_get_with_block headers = {'X-Requested-With' => 'XMLHttpRequest'} url = mock() resource = mock() response = mock() response_history = mock() resource.stubs(:get).with(headers).returns(response) response_history.stubs(:cookies).returns({'myacinfo' => 'f0F0f0F0'}) response.stubs(:history).returns([response_history]) response.stubs(:cookies).returns({'woinst' => '3072', 'wosid' => 'a1B2c3D4e5F6g7'}) expected_cookies = {'myacinfo' => 'f0F0f0F0', 'woinst' => '3072', 'wosid' => 'a1B2c3D4e5F6g7'} expected_headers = headers.merge({:cookies => expected_cookies}) RestClient::Resource.stub(:new, resource) do @ios_ratings_fetcher.send(:send_request, :get, url, headers) assert_equal(expected_headers, headers) end end def test_send_request_post_without_block end end
Remove warning when including Kaminari
require 'encore/version' require 'active_model_serializers' require 'active_record' require 'active_support' require 'kaminari' require 'encore/config' require 'encore/serializer/base' require 'encore/serializer/instance' require 'encore/persister/instance' module Encore end
require 'encore/version' require 'active_model_serializers' require 'active_record' require 'active_support' # This is a dirty hack to fix dirty code # https://github.com/amatsuda/kaminari/blob/7b049067b143212a172d5bb472184eac23121f34/lib/kaminari.rb#L11-L25 oldstderr = $stderr.dup $stderr = StringIO.new require 'kaminari' $stderr = oldstderr require 'encore/config' require 'encore/serializer/base' require 'encore/serializer/instance' require 'encore/persister/instance' module Encore end
Use string key instead of symbol for setting.
Settings.defaults = { :payment_period => 30.days, 'modules.enabled' => [] }
Settings.defaults = { 'payment_period' => 30.days, 'modules.enabled' => [] }
Add definition for highline gem
# # Copyright 2014 Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # name "highline-gem" default_version "1.6.21" dependency "ruby" dependency "rubygems" build do env = with_standard_compiler_flags(with_embedded_path) gem "install highline" \ " --version '#{version}'" \ " --bindir '#{install_dir}/embedded/bin'" \ " --no-ri --no-rdoc", env: env end
DEAL WITH RECIEVING JSON AND NOT A HSH
module ServiceImportExport def export_service(service_hash) SystemDebug.debug(SystemDebug.export_import, :export_service,service_hash) r = @core_api.export_service(service_hash) return failed(service_hash.to_s, @last_error, 'export service') if r.is_a?(FalseClass) return r end def import_service(params) SystemDebug.debug(SystemDebug.export_import, :input_service,params) SystemUtils.symbolize_keys(params) return success(params.to_s, 'import service') if @core_api.import_service(params) return failed(params.to_s, @last_error, 'import service') end end
module ServiceImportExport def export_service(service_hash) SystemDebug.debug(SystemDebug.export_import, :export_service,service_hash) r = @core_api.export_service(service_hash) return failed(service_hash.to_s, @last_error, 'export service') if r.is_a?(FalseClass) return r end def import_service(params) SystemDebug.debug(SystemDebug.export_import, :input_service,params) #SystemUtils.symbolize_keys(params) SystemUtils.deal_with_jason(params) return success(params.to_s, 'import service') if @core_api.import_service(params) return failed(params.to_s, @last_error, 'import service') end end
Fix deprecation warning about Capybara
# Define a bare test case to use with Capybara class ActiveSupport::IntegrationCase < ActiveSupport::TestCase include Capybara include Rails.application.routes.url_helpers end
# Define a bare test case to use with Capybara class ActiveSupport::IntegrationCase < ActiveSupport::TestCase include Capybara::DSL include Rails.application.routes.url_helpers end
Add test for smartd recipe
describe 'sys::smartd' do let(:chef_run) { ChefSpec::SoloRunner.new.converge(described_recipe) } context 'without related attributes' do it 'does nothing' do expect(chef_run.run_context.resource_collection).to be_empty end end context 'with attributes enabled' do let(:chef_run) { ChefSpec::SoloRunner.new } before do chef_run.node.default['sys']['smartd']['enable'] = true chef_run.node.default['sys']['smartd']['mailto'] = 'doedel@xyz.io' chef_run.converge(described_recipe) end it 'does stuff' do pkg_name = 'smartmontools' expect(chef_run).to install_package(pkg_name) expect(chef_run).to enable_service(pkg_name) expect(chef_run).to start_service(pkg_name) expect(chef_run).to create_template("/etc/default/#{pkg_name}") end it 'configures mail alerts' do expect(chef_run).to render_file('/etc/smartd.conf') .with_content(/DEVICESCAN .* -m doedel@xyz.io .*/) end end context 'inside a VM' do let(:chef_run) { ChefSpec::SoloRunner.new } before do chef_run.node.default['sys']['smartd']['enable'] = true chef_run.node.automatic['virtualization']['role'] = 'guest' chef_run.converge(described_recipe) end it 'emits a warning' do expect(chef_run).to write_log(/ not enabling smartd/) end end end
Use explicit list of non-statements
class SpeechType include ActiveRecordLikeInterface attr_accessor :id, :name, :genus, :explanation def slug name.downcase.gsub(/[^a-z]+/, "-") end def genus @genus || @name end def self.find_by_name(name) all.find { |pt| pt.name == name } end def self.find_by_slug(slug) all.find { |type| type.slug == slug } end def self.non_statements all - statements end def self.statements [WrittenStatement, OralStatement] end Transcript = create( id: 1, name: "Transcript", genus: "Speech", explanation: "This is a transcript of the speech, exactly as it was delivered." ) DraftText = create( id: 2, name: "Draft text", genus: "Speech", explanation: "This is the text of the speech as drafted, which may differ slightly from the delivered version." ) SpeakingNotes = create( id: 3, name: "Speaking notes", genus: "Speech", explanation: "These are the speaker's notes, not a transcript of the speech as it was delivered." ) WrittenStatement = create(id: 4, name: "Written statement") OralStatement = create(id: 5, name: "Oral statement") ImportedAwaitingType = create(id: 1000, name: "Imported - Awaiting Type") end
class SpeechType include ActiveRecordLikeInterface attr_accessor :id, :name, :genus, :explanation def slug name.downcase.gsub(/[^a-z]+/, "-") end def genus @genus || @name end def self.find_by_name(name) all.find { |pt| pt.name == name } end def self.find_by_slug(slug) all.find { |type| type.slug == slug } end def self.non_statements [Transcript, DraftText, SpeakingNotes] end def self.statements [WrittenStatement, OralStatement] end Transcript = create( id: 1, name: "Transcript", genus: "Speech", explanation: "This is a transcript of the speech, exactly as it was delivered." ) DraftText = create( id: 2, name: "Draft text", genus: "Speech", explanation: "This is the text of the speech as drafted, which may differ slightly from the delivered version." ) SpeakingNotes = create( id: 3, name: "Speaking notes", genus: "Speech", explanation: "These are the speaker's notes, not a transcript of the speech as it was delivered." ) WrittenStatement = create(id: 4, name: "Written statement") OralStatement = create(id: 5, name: "Oral statement") ImportedAwaitingType = create(id: 1000, name: "Imported - Awaiting Type") end
Update example app's breadcrumbs logger config
require_relative 'boot' 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 Rails60 class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 6.0 # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. config.consider_all_requests_local = false # https://github.com/getsentry/raven-ruby/issues/494 config.exceptions_app = self.routes Sentry.init do |config| config.breadcrumbs_logger = [:sentry_logger] config.send_default_pii = true config.traces_sample_rate = 1.0 config.dsn = 'https://2fb45f003d054a7ea47feb45898f7649@o447951.ingest.sentry.io/5434472' end end end
require_relative 'boot' 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 Rails60 class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 6.0 # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. config.consider_all_requests_local = false # https://github.com/getsentry/raven-ruby/issues/494 config.exceptions_app = self.routes Sentry.init do |config| config.breadcrumbs_logger = [:active_support_logger] config.send_default_pii = true config.traces_sample_rate = 1.0 config.dsn = 'https://2fb45f003d054a7ea47feb45898f7649@o447951.ingest.sentry.io/5434472' end end end
Send email when creating denuncia.
class DenunciasController < ApplicationController def create @denuncia = Denuncia.new(denuncia_params) @denuncia.ip = request.remote_ip if @denuncia.save redirect_to denuncia_path(@denuncia) else redirect_to root_path, error: 'Hubo errores procesando su denuncia.' end end def show @denuncia = Denuncia.find(params[:id]) end private def denuncia_params params.require(:denuncia).permit( :pais_id, :delito_id, item_denuncias_attributes: [ :pregunta_id, :opcion_id, :fecha, :observacion, opciones_multiples: [] ] ) end end
class DenunciasController < ApplicationController def create @denuncia = Denuncia.new(denuncia_params) @denuncia.ip = request.remote_ip if @denuncia.save DenunciaMailer.resultado(@denuncia.id).deliver_later redirect_to denuncia_path(@denuncia) else redirect_to root_path, error: 'Hubo errores procesando su denuncia.' end end def show @denuncia = Denuncia.find(params[:id]) end private def denuncia_params params.require(:denuncia).permit( :pais_id, :delito_id, item_denuncias_attributes: [ :pregunta_id, :opcion_id, :fecha, :observacion, opciones_multiples: [] ] ) end end
Use status 404 when the redirects controller can't find the redirect.
class RedirectsController < ActionController::Base def go redirect = ::Redirect.find_by(source_uri: source_uri) if redirect && redirect.enabled? redirect_to redirect.destination_uri, status: redirect.status_code else render text: 'No such redirect or disabled.' end end private def source_uri "/go/#{params[:slug]}" end end
class RedirectsController < ActionController::Base def go redirect = ::Redirect.find_by(source_uri: source_uri) if redirect && redirect.enabled? redirect_to redirect.destination_uri, status: redirect.status_code else render text: 'No such redirect or disabled.', status: 404 end end private def source_uri "/go/#{params[:slug]}" end end
Fix 'send current_user to notifier'
module VotingApp module Notifications extend ActiveSupport::Concern class Notification attr_accessor :submission, :options def initialize(submission, options) @submission = submission @options = options end end def notify_accepted(options = {}) notification = Notification.new self, options self.class.notify_observers :notify_accepted, options[:user], notification end def notify_completed(options = {}) notification = Notification.new self, options self.class.notify_observers :notify_completed, notification end def notify_created(options = {}) notification = Notification.new self, options self.class.notify_observers :notify_created, notification end def notify_promoted(options = {}) notification = Notification.new self, options self.class.notify_observers :notify_promoted, notification end def notify_rejected(options = {}) notification = Notification.new self, options self.class.notify_observers :notify_rejected, notification end def notify_liked(options = {}) notification = Notification.new self, options self.class.notify_observers :notify_liked, notification end def notify_commented(options = {}) notification = Notification.new self, options self.class.notify_observers :notify_commented, notification end end end
module VotingApp module Notifications extend ActiveSupport::Concern class Notification attr_accessor :submission, :options def initialize(submission, options) @submission = submission @options = options end end def notify_accepted(options = {}) notification = Notification.new self, options self.class.notify_observers :notify_accepted, notification end def notify_completed(options = {}) notification = Notification.new self, options self.class.notify_observers :notify_completed, notification end def notify_created(options = {}) notification = Notification.new self, options self.class.notify_observers :notify_created, notification end def notify_promoted(options = {}) notification = Notification.new self, options self.class.notify_observers :notify_promoted, notification end def notify_rejected(options = {}) notification = Notification.new self, options self.class.notify_observers :notify_rejected, notification end def notify_liked(options = {}) notification = Notification.new self, options self.class.notify_observers :notify_liked, notification end def notify_commented(options = {}) notification = Notification.new self, options self.class.notify_observers :notify_commented, notification end end end
Add ham and spam scopes
require 'refinery/core/base_model' require 'filters_spam' module Refinery module Inquiries class Inquiry < Refinery::Core::BaseModel if Inquiries.filter_spam filters_spam message_field: :message, email_field: :email, author_field: :name, other_fields: [:phone], extra_spam_words: %w() end validates :name, presence: true, length: { maximum: 255 } validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i }, length: { maximum: 255 } validates :message, presence: true default_scope { order('created_at DESC') } def self.latest(number = 7, include_spam = false) include_spam ? limit(number) : ham.limit(number) end end end end
require 'refinery/core/base_model' require 'filters_spam' module Refinery module Inquiries class Inquiry < Refinery::Core::BaseModel if Inquiries.filter_spam filters_spam message_field: :message, email_field: :email, author_field: :name, other_fields: [:phone], extra_spam_words: %w() end validates :name, presence: true, length: { maximum: 255 } validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i }, length: { maximum: 255 } validates :message, presence: true default_scope { order('created_at DESC') } scope :ham, -> { where(spam: false) } scope :spam, -> { where(spam: true) } def self.latest(number = 7, include_spam = false) include_spam ? limit(number) : ham.limit(number) end end end end
Simplify blue monday example by using with_synth_defaults
def drums 6.times do sample :heavy_kick, :rate, 0.8 sleep 0.5 end 8.times do sample :heavy_kick, :rate, 0.8 sleep 0.125 end end def snare sample :snare_soft sleep 1 end def synths with_synth "saw_beep" notes = [:F, :C, :D, :D, :G, :C, :D, :D] notes.each do |n| 2.times do play note(n, 1), :amp, 0.5, :attack, 0.01, :release, 0.5 play note(n, 2), :amp, 0.5, :attack, 0.01, :release, 0.75 sleep 0.25 play note(n, 2), :amp, 0.5, :attack, 0.01, :release, 0.5 play note(n, 3), :amp, 0.5, :attack, 0.01, :release, 0.75 sleep 0.25 end end end in_thread do sleep 6 loop{synths} end in_thread do loop{drums} end in_thread do sleep 12.5 loop{snare} end
def drums 6.times do sample :heavy_kick, :rate, 0.8 sleep 0.5 end 8.times do sample :heavy_kick, :rate, 0.8 sleep 0.125 end end def snare sample :snare_soft sleep 1 end def synths with_synth "saw_beep" with_synth_defaults :amp, 0.5, :attack, 0.01, :release, 0.75, :cutoff, 130 notes = [:F, :C, :D, :D, :G, :C, :D, :D] notes.each do |n| 2.times do play note(n, 1) play note(n, 2) sleep 0.25 play note(n, 2) play note(n, 3) sleep 0.25 end end end in_thread do sleep 6 loop{synths} end in_thread do loop{drums} end in_thread do sleep 12.5 loop{snare} end
Consolidate the Sidekiq config with production
# This file is overwritten on deploy Sidekiq.configure_client do |config| config.redis = { namespace: 'signon' } end Sidekiq.configure_server do |config| config.redis = { namespace: 'signon' } config.server_middleware do |chain| chain.add Sidekiq::Middleware::Server::RetryJobs, max_retries: 5 end end
require "sidekiq" redis_config = { namespace: "signon_sidekiq" } redis_config[:url] = ENV['REDIS_URL'] if ENV['REDIS_URL'] Sidekiq.configure_server do |config| config.redis = redis_config config.server_middleware do |chain| chain.add Sidekiq::Statsd::ServerMiddleware, env: 'govuk.app.signon', prefix: 'workers' end end Sidekiq.configure_client do |config| config.redis = redis_config end
Add the sengrid information for ActionMailer
ActionMailer::Base.smtp_settings = { :address => 'smtp.sendgrid.net', :port => '587', :authentication => :plain, :user_name => ENV['SENDGRID_USERNAME'], :password => ENV['SENDGRID_PASSWORD'], :domain => 'heroku.com' } ActionMailer::Base.delivery_method = :smtp
Add DB-level uniqueness constraint for stock items
class AddStockItemUniqueIndex < ActiveRecord::Migration def change # Add a database-level uniqueness constraint for databases that support it # (postgres & sqlite) if connection.adapter_name =~ /postgres|sqlite/i add_index 'spree_stock_items', ['variant_id', 'stock_location_id'], where: 'deleted_at is null', unique: true end end end
Fix migration to use integer for user_id
class SecretaryCreateVersions < ActiveRecord::Migration def change create_table "versions" do |t| t.integer "version_number" t.string "versioned_type" t.integer "versioned_id" t.string "user_id" t.text "description" t.text "object_changes" t.datetime "created_at" end add_index "versions", ["created_at"] add_index "versions", ["user_id"] add_index "versions", ["version_number"] add_index "versions", ["versioned_type", "versioned_id"] end end
class SecretaryCreateVersions < ActiveRecord::Migration def change create_table "versions" do |t| t.integer "version_number" t.string "versioned_type" t.integer "versioned_id" t.integer "user_id" t.text "description" t.text "object_changes" t.datetime "created_at" end add_index "versions", ["created_at"] add_index "versions", ["user_id"] add_index "versions", ["version_number"] add_index "versions", ["versioned_type", "versioned_id"] end end
Make username and API key optional
module Sauce module Generators class InstallGenerator < Rails::Generators::Base source_root File.expand_path("../templates", __FILE__) desc "Prep application for Sauce OnDemand Selenium tests" #argument :username, :type => nil #argument :api_key, :type => nil def copy_rake_tasks copy_file "sauce.rake", "lib/tasks/sauce.rake" end def configure_credentials system("sauce config #{username} #{api_key}") end def setup_spec if File.directory? 'spec' empty_directory "spec/selenium" append_file "spec/spec_helper.rb", generate_config end end def setup_test if File.directory? 'test' empty_directory "test/selenium" append_file "test/test_helper.rb", generate_config end end private def generate_config @random_id ||= rand(100000) return <<-CONFIG require 'sauce' Sauce.config do |conf| conf.browser_url = "http://#{@random_id}.test/" conf.browsers = [ ["Windows 2003", "firefox", "3."] ] conf.application_host = "127.0.0.1" conf.application_port = "3001" end CONFIG end end end end
module Sauce module Generators class InstallGenerator < Rails::Generators::Base source_root File.expand_path("../templates", __FILE__) desc "Prep application for Sauce OnDemand Selenium tests" argument :username, :type => :string, :required => false argument :api_key, :type => :string, :required => false def copy_rake_tasks copy_file "sauce.rake", "lib/tasks/sauce.rake" end def configure_credentials if username system("sauce config #{username} #{api_key}") end end def setup_spec if File.directory? 'spec' empty_directory "spec/selenium" append_file "spec/spec_helper.rb", generate_config end end def setup_test if File.directory? 'test' empty_directory "test/selenium" append_file "test/test_helper.rb", generate_config end end private def generate_config @random_id ||= rand(100000) return <<-CONFIG require 'sauce' Sauce.config do |conf| conf.browser_url = "http://#{@random_id}.test/" conf.browsers = [ ["Windows 2003", "firefox", "3."] ] conf.application_host = "127.0.0.1" conf.application_port = "3001" end CONFIG end end end end
Use correct values for "files"
Gem::Specification.new do |s| s.name = "ffxiv" s.version = "0.9.0" s.date = "2014-09-29" s.summary = "An unofficial FFXIV ARR toolkit for Ruby, featuring Lodestone scraper." s.description = "An unofficial FFXIV ARR toolkit for Ruby, featuring Lodestone scraper." s.authors = ["Isjaki Kveikur"] s.email = ["isjaki.xiv@gmail.com"] s.files = ["lib/*.rb"] s.homepage = "http://rubygems.org/gems/ffxiv" s.license = "MIT" end
Gem::Specification.new do |s| s.name = "ffxiv" s.version = "0.9.0" s.date = "2014-09-29" s.summary = "An unofficial FFXIV ARR toolkit for Ruby, featuring Lodestone scraper." s.description = "An unofficial FFXIV ARR toolkit for Ruby, featuring Lodestone scraper." s.authors = ["Isjaki Kveikur"] s.email = ["isjaki.xiv@gmail.com"] s.files = ["lib/ffxiv.rb", "lib/ffxiv/lodestone.rb", "lib/ffxiv/lodestone/model.rb", "lib/ffxiv/lodestone/character.rb", "lib/ffxiv/lodestone/free-company.rb"] s.homepage = "http://rubygems.org/gems/ffxiv" s.license = "MIT" end
Move constant injection closer to the code that depends on it
require 'stepping_stone/text_mapper/mapping' require 'stepping_stone/model/doc_string' module SteppingStone module TextMapper def self.mappers @mappers ||= [] end def self.all_mappings mappers.inject([]) do |acc, mapper| acc << mapper.mappings end.flatten end def self.extended(mapper) mapper.extend(Dsl) mapper.const_set(:DocString, Model::DocString) mappers << mapper end module Dsl def mappings @mappings ||= [] end def def_map(mapping) mappings << Mapping.from_fluent(mapping) end end end end
require 'stepping_stone/text_mapper/mapping' require 'stepping_stone/model/doc_string' module SteppingStone module TextMapper def self.mappers @mappers ||= [] end def self.all_mappings mappers.inject([]) do |acc, mapper| acc << mapper.mappings end.flatten end def self.extended(mapper) mapper.extend(Dsl) mappers << mapper end module Dsl def self.extended(mapper) mapper.const_set(:DocString, Model::DocString) end def mappings @mappings ||= [] end def def_map(mapping) mappings << Mapping.from_fluent(mapping) end end end end
Package version increased from 0.1.2.1 to 0.1.2.2
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'metrics-stream-divergence' s.version = '0.1.2.1' s.summary = 'Measurement of divergence in time of the heads of streams' s.description = ' ' s.authors = ['Obsidian Software, Inc'] s.email = 'opensource@obsidianexchange.com' s.homepage = 'https://github.com/obsidian-btc/metrics-stream-divergence' 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 'event_store-client-http' s.add_runtime_dependency 'serialize' s.add_development_dependency 'test_bench' end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'metrics-stream-divergence' s.version = '0.1.2.2' s.summary = 'Measurement of divergence in time of the heads of streams' s.description = ' ' s.authors = ['Obsidian Software, Inc'] s.email = 'opensource@obsidianexchange.com' s.homepage = 'https://github.com/obsidian-btc/metrics-stream-divergence' 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 'event_store-client-http' s.add_runtime_dependency 'serialize' s.add_development_dependency 'test_bench' end
Add method to extract zone ID
require 'aws-sdk' require 'contracts' require_relative 'service' module Cloudstrap module Amazon class Route53 < Service include ::Contracts::Core include ::Contracts::Builtin Contract None => ArrayOf[::Aws::Route53::Types::HostedZone] def zones @zones ||= zones! end Contract None => ArrayOf[::Aws::Route53::Types::HostedZone] def zones! @zones = call_api(:list_hosted_zones).hosted_zones end Contract String => Maybe[::Aws::Route53::Types::HostedZone] def zone(name) name.tap { |string| string.concat('.') unless string.end_with?('.') } zones.find { |zone| zone.name == name } end private def client ::Aws::Route53::Client end end end end
require 'aws-sdk' require 'contracts' require_relative 'service' module Cloudstrap module Amazon class Route53 < Service include ::Contracts::Core include ::Contracts::Builtin Contract None => ArrayOf[::Aws::Route53::Types::HostedZone] def zones @zones ||= zones! end Contract None => ArrayOf[::Aws::Route53::Types::HostedZone] def zones! @zones = call_api(:list_hosted_zones).hosted_zones end Contract String => Maybe[::Aws::Route53::Types::HostedZone] def zone(name) name.tap { |string| string.concat('.') unless string.end_with?('.') } zones.find { |zone| zone.name == name } end Contract String => Maybe[String] def zone_id(name) return unless zone = zone(name) zone(name).id.split('/').last end private def client ::Aws::Route53::Client end end end end
Remove the logger and unused gems, swap in the new ones
# frozen_string_literal: true $LOAD_PATH.unshift(__dir__) require 'benchmark' require 'fileutils' require 'logger' require 'tilt' require 'yaml' require 'dimples/frontable' require 'dimples/renderable' require 'dimples/category' require 'dimples/configuration' require 'dimples/errors' require 'dimples/logger' require 'dimples/page' require 'dimples/pagination' require 'dimples/post' require 'dimples/site' require 'dimples/template' # A static site generator. module Dimples class << self def logger @logger ||= Dimples::Logger.new(STDOUT) end end end
# frozen_string_literal: true $LOAD_PATH.unshift(__dir__) require 'hashie' require 'tilt' require 'yaml' require 'dimples/configuration' require 'dimples/errors' require 'dimples/frontable' require 'dimples/page' require 'dimples/plugin' require 'dimples/post' require 'dimples/site' require 'dimples/template'
Add retry around getting labels
class Sprint def check_labels(x, target) x.labels.map{|x| x.name }.include?(target) end def check_comments(x, target) #TODO Trello doesn't have an api for comments yet #x.comments.map{|x| x.body }.include?(target) true end def queries { :needs_qe => { :function => lambda{ |x| !check_labels(x, 'no-qe') } }, :qe_ready => { :parent => :needs_qe, :function => lambda{ |x| check_comments(x, 'tcms') } }, :approved => { :function => lambda{ |x| check_labels(x, 'tc-approved') || check_labels(x, 'no-qe') } }, :accepted => { :function => lambda{ |x| x.list.name == 'Accepted' } }, :completed => { :parent => :not_accepted, :function => lambda{ |x| list = x.list.name == 'Complete' } }, :not_dcut_complete => { :parent => :not_completed, :function => lambda{ |x| check_labels(x, 'devcut')} } } end end
class Sprint def check_labels(x, target) labels = nil i = 0 while true begin labels = x.labels break rescue Exception => e puts "Error getting labels: #{e.message}" raise if i >= 3 sleep 10 i += 1 end end labels.map{|x| x.name }.include?(target) end def check_comments(x, target) #TODO Trello doesn't have an api for comments yet #x.comments.map{|x| x.body }.include?(target) true end def queries { :needs_qe => { :function => lambda{ |x| !check_labels(x, 'no-qe') } }, :qe_ready => { :parent => :needs_qe, :function => lambda{ |x| check_comments(x, 'tcms') } }, :approved => { :function => lambda{ |x| check_labels(x, 'tc-approved') || check_labels(x, 'no-qe') } }, :accepted => { :function => lambda{ |x| x.list.name == 'Accepted' } }, :completed => { :parent => :not_accepted, :function => lambda{ |x| list = x.list.name == 'Complete' } }, :not_dcut_complete => { :parent => :not_completed, :function => lambda{ |x| check_labels(x, 'devcut')} } } end end
Fix interaction search result API
class InteractionSearchResultApiPresenter def initialize(search_result) @result = search_result end def search_term @result.search_term end def gene_name gene.name end def gene_long_name gene.long_name end def potentially_druggable_categories gene.gene_claims.flat_map { |gc| gc.gene_claim_categories } .map { |c| c.name } .uniq end def has_interactions? @interactions.size > 0 end def interactions @interactions ||= @result.interaction_claims.map do |i| InteractionWrapper.new(i) end end private def gene @result.interaction_claims .first .gene_claim .genes .first end InteractionWrapper = Struct.new(:interaction_claim) do def types_string interaction_claim .interaction_claim_types .map(&:type) .join(',') end def interaction_id interaction_claim.id end def source_db_name interaction_claim.source.source_db_name end def drug_name interaction_claim.drug_claim.primary_name || interaction_claim.drug_claim.name end end end
class InteractionSearchResultApiPresenter def initialize(search_result) @result = search_result end def search_term @result.search_term end def gene_name gene.name end def gene_long_name gene.long_name end def potentially_druggable_categories gene.gene_claims.flat_map { |gc| gc.gene_claim_categories } .map { |c| c.name } .uniq end def has_interactions? @interactions.size > 0 end def interactions @interactions ||= @result.interaction_claims.map do |i| InteractionWrapper.new(i) end end private def gene @result.interaction_claims .first .interaction .gene end InteractionWrapper = Struct.new(:interaction_claim) do def types_string interaction_claim .interaction_claim_types .map(&:type) .join(',') end def interaction_id interaction_claim.id end def source_db_name interaction_claim.source.source_db_name end def drug_name interaction_claim.drug_claim.primary_name || interaction_claim.drug_claim.name end end end
Work around issue in newest Vagrant
Vagrant.configure('2') do |c| if Vagrant.has_plugin?('vagrant-cachier') c.cache.auto_detect = true c.cache.scope = :box end c.vm.provider 'virtualbox' do |v| v.customize [ 'storagectl', :id, '--name', 'SATA Controller', '--hostiocache', 'on' ] end end
Vagrant.configure('2') do |c| c.ssh.insert_key = false if Vagrant.has_plugin?('vagrant-cachier') c.cache.auto_detect = true c.cache.scope = :box end c.vm.provider 'virtualbox' do |v| v.customize [ 'storagectl', :id, '--name', 'SATA Controller', '--hostiocache', 'on' ] end end
Remove unused `arguments` call in generator spec
require "rails_helper" require "generator_spec" require "generators/paul_revere/paul_revere_generator" describe PaulRevereGenerator, type: :generator do destination File.expand_path("../../tmp", __FILE__) arguments %w(something) before(:all) do prepare_destination run_generator end specify do expect(destination_root).to have_structure { directory "db" do directory "migrate" do migration "create_announcements" do contains "class CreateAnnouncements" contains "create_table :announcements" end end end } end end
require "rails_helper" require "generator_spec" require "generators/paul_revere/paul_revere_generator" describe PaulRevereGenerator, type: :generator do destination File.expand_path("../../tmp", __FILE__) before(:all) do prepare_destination run_generator end specify do expect(destination_root).to have_structure { directory "db" do directory "migrate" do migration "create_announcements" do contains "class CreateAnnouncements" contains "create_table :announcements" end end end } end end
Allow gem to be used with mongoid 5
Gem::Specification.new do |s| s.name = "mongoid-rails" s.version = "4.0.0" s.author = "Conrad Irwin" s.email = "conrad.irwin@gmail.com" s.homepage = "https://github.com/ConradIrwin/mongoid-rails" s.summary = "Strong parameter integration between rails and mongoid" s.license = "MIT" s.add_dependency("mongoid", ["~> 4.0"]) s.files = `git ls-files`.split("\n") s.require_path = 'lib' end
Gem::Specification.new do |s| s.name = "mongoid-rails" s.version = "4.0.0" s.author = "Conrad Irwin" s.email = "conrad.irwin@gmail.com" s.homepage = "https://github.com/ConradIrwin/mongoid-rails" s.summary = "Strong parameter integration between rails and mongoid" s.license = "MIT" s.add_dependency("mongoid", ["~> 5.0"]) s.files = `git ls-files`.split("\n") s.require_path = 'lib' end
Refactor to a named method, for sanity
require 'English' module GitTracker module Branch def self.story_number current[/#?(?<number>\d+)/, :number] end def self.current branch_path = `git symbolic-ref HEAD` abort unless $CHILD_STATUS.exitstatus == 0 branch_path[%r{refs/heads/(?<name>.+)}, :name] || '' end end end
require 'English' module GitTracker module Branch def self.story_number current[/#?(?<number>\d+)/, :number] end def self.current branch_path = `git symbolic-ref HEAD` abort unless exit_successful? branch_path[%r{refs/heads/(?<name>.+)}, :name] || '' end private def self.exit_successful? $CHILD_STATUS.exitstatus == 0 end end end
Set XML header to utf-8
module Jekyll module Commands class Serve class << self alias :_original_webrick_options :webrick_options end def self.webrick_options(config) options = _original_webrick_options(config) options[:MimeTypes].merge!({'html' => 'text/html; charset=utf-8'}) options end end end end
module Jekyll module Commands class Serve class << self alias :_original_webrick_options :webrick_options end def self.webrick_options(config) options = _original_webrick_options(config) options[:MimeTypes].merge!({'html' => 'text/html; charset=utf-8'}) options[:MimeTypes].merge!({'xml' => 'text/xml; charset=utf-8'}) options end end end end
Refresh parser require fixed in physical infra manager.
class ManageIQ::Providers::Lenovo::PhysicalInfraManager < ManageIQ::Providers::InfraManager include ManageIQ::Providers::Lenovo::ManagerMixin require_nested :Refresher # require_nested :RefreshParser # require_nested :RefreshWorker def self.ems_type @ems_type ||= "lenovo_ph_infra".freeze end def self.description @description ||= "Lenovo XClarity" end end
class ManageIQ::Providers::Lenovo::PhysicalInfraManager < ManageIQ::Providers::InfraManager include ManageIQ::Providers::Lenovo::ManagerMixin require_nested :Refresher require_nested :RefreshParser # require_nested :RefreshWorker def self.ems_type @ems_type ||= "lenovo_ph_infra".freeze end def self.description @description ||= "Lenovo XClarity" end end
Correct sending domain for emails.
class ApplicationMailer < ActionMailer::Base default from: 'membership@sheffieldviking.org.uk' layout 'mailer' end
class ApplicationMailer < ActionMailer::Base default from: 'renewals@email.sheffieldviking.org.uk', reply_to: 'membership@sheffieldviking.org.uk' layout 'mailer' end
Fix "undefined local method" bug
require "optparse" require "rubycritic" require "rubycritic/reporters/main" module Rubycritic class Cli STATUS_SUCCESS = 0 def initialize(argv) @argv = argv @argv << "." if @argv.empty? @main_command = true end def execute OptionParser.new do |opts| opts.banner = "Usage: rubycritic [options] [paths]" opts.on("-p", "--path [PATH]", "Set path where report will be saved (tmp/rubycritic by default)") do |path| configuration.root = path end opts.on_tail("-v", "--version", "Show gem's version") do require "rubycritic/version" puts "RubyCritic #{VERSION}" @main_command = false end opts.on_tail("-h", "--help", "Show this message") do puts opts @main_command = false end end.parse!(@argv) if @main_command analysed_files = Orchestrator.new.critique(@argv) report_location = Reporter::Main.new(analysed_files).generate_report puts "New critique at #{report_location}" end STATUS_SUCCESS end end end
require "optparse" require "rubycritic" require "rubycritic/reporters/main" module Rubycritic class Cli STATUS_SUCCESS = 0 def initialize(argv) @argv = argv @argv << "." if @argv.empty? @main_command = true end def execute OptionParser.new do |opts| opts.banner = "Usage: rubycritic [options] [paths]" opts.on("-p", "--path [PATH]", "Set path where report will be saved (tmp/rubycritic by default)") do |path| ::Rubycritic.configuration.root = path end opts.on_tail("-v", "--version", "Show gem's version") do require "rubycritic/version" puts "RubyCritic #{VERSION}" @main_command = false end opts.on_tail("-h", "--help", "Show this message") do puts opts @main_command = false end end.parse!(@argv) if @main_command analysed_files = Orchestrator.new.critique(@argv) report_location = Reporter::Main.new(analysed_files).generate_report puts "New critique at #{report_location}" end STATUS_SUCCESS end end end
Fix build for ruby 2.0
require 'digest/sha1' require 'openssl' module Encryption class Symmetric AES_BLOCKSIZE = 16 def encrypt(key, message) cipher = OpenSSL::Cipher::AES128.new(:CBC) cipher.encrypt cipher.key = get_encryption_key(key) cipher.padding = 0 iv = cipher.random_iv iv + cipher.update(pad_buffer(message)) + cipher.final end def decrypt(key, encrypted) cipher = OpenSSL::Cipher::AES128.new(:CBC) cipher.padding = 0 cipher.decrypt cipher.key = get_encryption_key(key) cipher.iv = encrypted[0..AES_BLOCKSIZE-1] unpad_buffer(cipher.update(encrypted[AES_BLOCKSIZE..encrypted.length]) + cipher.final) end def digest(value) Digest::SHA256.digest(value) end private def get_encryption_key(key) digest(key)[0..AES_BLOCKSIZE-1] end def pad_buffer(message) bytes_to_pad = AES_BLOCKSIZE - message.length % AES_BLOCKSIZE message + "\x80" + "\x00" * (bytes_to_pad - 1) end def unpad_buffer(message) raise OpenSSL::Cipher::CipherError unless message.match(/\x80\x00*$/) message.gsub(/\x80\x00*$/, '') end end end
# coding: US-ASCII require 'digest/sha1' require 'openssl' module Encryption class Symmetric AES_BLOCKSIZE = 16 def encrypt(key, message) cipher = OpenSSL::Cipher::AES128.new(:CBC) cipher.encrypt cipher.key = get_encryption_key(key) cipher.padding = 0 iv = cipher.random_iv iv + cipher.update(pad_buffer(message)) + cipher.final end def decrypt(key, encrypted) cipher = OpenSSL::Cipher::AES128.new(:CBC) cipher.padding = 0 cipher.decrypt cipher.key = get_encryption_key(key) cipher.iv = encrypted[0..AES_BLOCKSIZE-1] unpad_buffer(cipher.update(encrypted[AES_BLOCKSIZE..encrypted.length]) + cipher.final) end def digest(value) Digest::SHA256.digest(value) end private def get_encryption_key(key) digest(key)[0..AES_BLOCKSIZE-1] end def pad_buffer(message) bytes_to_pad = AES_BLOCKSIZE - message.length % AES_BLOCKSIZE message + "\x80" + "\x00" * (bytes_to_pad - 1) end def unpad_buffer(message) raise OpenSSL::Cipher::CipherError unless message.match(/\x80\x00*$/) message.gsub(/\x80\x00*$/, '') end end end
Fix version in gemspec to match released version.
Gem::Specification.new do |s| s.name = 'queue_classic' s.email = 'ryan@heroku.com' s.version = '1.0.0.rc1' s.date = '2011-08-22' s.description = "queue_classic is a queueing library for Ruby apps. (Rails, Sinatra, Etc...) queue_classic features asynchronous job polling, database maintained locks and no ridiculous dependencies. As a matter of fact, queue_classic only requires pg." s.summary = "postgres backed queue" s.authors = ["Ryan Smith"] s.homepage = "http://github.com/ryandotsmith/queue_classic" s.files = %w[readme.md] + Dir["{lib,test}/**/*.rb"] s.test_files = s.files.select {|path| path =~ /^test\/.*_test.rb/} s.require_paths = %w[lib] s.add_dependency 'pg', "~> 0.11.0" s.add_dependency 'json', "~> 1.6.1" end
Gem::Specification.new do |s| s.name = 'queue_classic' s.email = 'ryan@heroku.com' s.version = '1.0.0' s.date = '2011-08-22' s.description = "queue_classic is a queueing library for Ruby apps. (Rails, Sinatra, Etc...) queue_classic features asynchronous job polling, database maintained locks and no ridiculous dependencies. As a matter of fact, queue_classic only requires pg." s.summary = "postgres backed queue" s.authors = ["Ryan Smith"] s.homepage = "http://github.com/ryandotsmith/queue_classic" s.files = %w[readme.md] + Dir["{lib,test}/**/*.rb"] s.test_files = s.files.select {|path| path =~ /^test\/.*_test.rb/} s.require_paths = %w[lib] s.add_dependency 'pg', "~> 0.11.0" s.add_dependency 'json', "~> 1.6.1" end
Refactor and fix body text nil issue
require "base64" module RuleIo class DeliveryMethod < Base attr_reader :mailer def initialize(_) end def settings { :return_response => false } end def deliver!(mail) from = mail[:from].addresses.first to = mail[:to].addresses response = self.class.post("transactionals", { transaction_type: "email", transaction_name: mail.subject, subject: mail.subject, from: { name: "Lärarförbundet", email: from }, to: { email: to.first }, content: { plain: Base64.strict_encode64(mail.text_part.decoded), html: Base64.strict_encode64(mail.html_part.decoded) } }) response.body["transaction_id"] end end end
require "base64" module RuleIo class DeliveryMethod < Base attr_reader :mailer def initialize(_); end def settings { return_response: false } end def deliver_later binding.pry end def deliver!(mail) binding.pry response = self.class.post("transactionals", mail_content(mail)) response.body["transaction_id"] end def mail_content(mail) { transaction_type: "email", transaction_name: mail.subject, subject: mail.subject, from: { name: "Lärarförbundet", email: mail[:from].addresses.first }, to: { email: mail[:to].addresses.first }, content: multipart_content(mail) } end def multipart_content(mail) if mail.text_part.nil? return { plain: Base64.strict_encode64(mail.body.decoded), html: Base64.strict_encode64(mail.body.decoded) } end { plain: Base64.strict_encode64(mail.text_part.decoded), html: Base64.strict_encode64(mail.html_part.decoded) } end alias deliver_now deliver! end end
Remove hiera creation (now done by Beaker auto)
require 'beaker-rspec' unless ENV['RS_PROVISION'] == 'no' hosts.each do |host| if host.is_pe? install_pe else install_puppet on host, "mkdir -p #{host['distmoduledir']}" end end end UNSUPPORTED_PLATFORMS = ['windows'] RSpec.configure do |c| # Project root proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) # Readable test descriptions c.formatter = :documentation # Configure all nodes in nodeset c.before :suite do # Install module and dependencies puppet_module_install(:source => proj_root, :module_name => 'swap_file') hosts.each do |host| shell('/bin/touch /etc/puppet/hiera.yaml') shell('puppet module install puppetlabs-stdlib --version 3.2.0', { :acceptable_exit_codes => [0,1] }) end end end
require 'beaker-rspec' unless ENV['RS_PROVISION'] == 'no' hosts.each do |host| if host.is_pe? install_pe else install_puppet on host, "mkdir -p #{host['distmoduledir']}" end end end UNSUPPORTED_PLATFORMS = ['windows'] RSpec.configure do |c| # Project root proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) # Readable test descriptions c.formatter = :documentation # Configure all nodes in nodeset c.before :suite do # Install module and dependencies puppet_module_install(:source => proj_root, :module_name => 'swap_file') hosts.each do |host| shell('puppet module install puppetlabs-stdlib --version 3.2.0', { :acceptable_exit_codes => [0,1] }) end end end
Fix test failure by accessing Content-Type header directly.
require "spec_helper" describe Projects::RepositoriesController do let(:project) { create(:project) } describe "GET archive" do context 'as a guest' do it 'responds with redirect in correct format' do get :archive, namespace_id: project.namespace.path, project_id: project.path, format: "zip" expect(response.content_type).to start_with 'text/html' expect(response).to be_redirect end end context 'as a user' do let(:user) { create(:user) } before do project.team << [user, :developer] sign_in(user) end it "uses Gitlab::Workhorse" do get :archive, namespace_id: project.namespace.path, project_id: project.path, ref: "master", format: "zip" expect(response.header[Gitlab::Workhorse::SEND_DATA_HEADER]).to start_with("git-archive:") end context "when the service raises an error" do before do allow(Gitlab::Workhorse).to receive(:send_git_archive).and_raise("Archive failed") end it "renders Not Found" do get :archive, namespace_id: project.namespace.path, project_id: project.path, ref: "master", format: "zip" expect(response).to have_http_status(404) end end end end end
require "spec_helper" describe Projects::RepositoriesController do let(:project) { create(:project) } describe "GET archive" do context 'as a guest' do it 'responds with redirect in correct format' do get :archive, namespace_id: project.namespace.path, project_id: project.path, format: "zip" expect(response.header["Content-Type"]).to start_with('text/html') expect(response).to be_redirect end end context 'as a user' do let(:user) { create(:user) } before do project.team << [user, :developer] sign_in(user) end it "uses Gitlab::Workhorse" do get :archive, namespace_id: project.namespace.path, project_id: project.path, ref: "master", format: "zip" expect(response.header[Gitlab::Workhorse::SEND_DATA_HEADER]).to start_with("git-archive:") end context "when the service raises an error" do before do allow(Gitlab::Workhorse).to receive(:send_git_archive).and_raise("Archive failed") end it "renders Not Found" do get :archive, namespace_id: project.namespace.path, project_id: project.path, ref: "master", format: "zip" expect(response).to have_http_status(404) end end end end end
Swap rescue statement for all errors
require 'thor' module Stevenson class Application < Thor desc 'stevenson new PROJECT_NAME', 'generates a Jekyll at PROJECT_NAME' method_option :template, aliases: '-t', default: 'hyde-base', desc: 'The template to use' # Template Options method_option :branch, aliases: '-b', desc: 'The git branch you would like to use from your template' method_option :subdirectory, aliases: '-s', desc: 'The subdirectory to use from the template, if any' # Output Options method_option :jekyll, type: :boolean, aliases: '-j', desc: 'Jekyll compiles the output directory' method_option :zip, type: :boolean, aliases: "-z", desc: 'Zip compresses the output directory' def new(output_directory) # Load the template using the template loader template = Stevenson::Template.load(options[:template], options) # If the jekyll flag is set, compile the template output template.extend(Stevenson::OutputFilters::JekyllFilter) if options[:jekyll] # If the zip flag is set, zip up the template output template.extend(Stevenson::OutputFilters::ZipFilter) if options[:zip] # Save the repo to the output directory template.output output_directory rescue Templates::InvalidTemplateException => e say e.message end desc 'generate_config', 'Generates a Stevenson configuration dotfile' def generate_config Dotfile.install puts "Generated dotfile at #{Dotfile.path}" end end end
require 'thor' module Stevenson class Application < Thor desc 'stevenson new PROJECT_NAME', 'generates a Jekyll at PROJECT_NAME' method_option :template, aliases: '-t', default: 'hyde-base', desc: 'The template to use' # Template Options method_option :branch, aliases: '-b', desc: 'The git branch you would like to use from your template' method_option :subdirectory, aliases: '-s', desc: 'The subdirectory to use from the template, if any' # Output Options method_option :jekyll, type: :boolean, aliases: '-j', desc: 'Jekyll compiles the output directory' method_option :zip, type: :boolean, aliases: "-z", desc: 'Zip compresses the output directory' def new(output_directory) # Load the template using the template loader template = Stevenson::Template.load(options[:template], options) # If the jekyll flag is set, compile the template output template.extend(Stevenson::OutputFilters::JekyllFilter) if options[:jekyll] # If the zip flag is set, zip up the template output template.extend(Stevenson::OutputFilters::ZipFilter) if options[:zip] # Save the repo to the output directory template.output output_directory rescue StandardError => e say e.message end desc 'generate_config', 'Generates a Stevenson configuration dotfile' def generate_config Dotfile.install puts "Generated dotfile at #{Dotfile.path}" end end end
Use ERB templates for all outcomes
module SmartAnswer class ReportALostOrStolenPassportFlow < Flow def define name 'report-a-lost-or-stolen-passport' status :published satisfies_need "100221" exclude_countries = %w(holy-see british-antarctic-territory) multiple_choice :where_was_the_passport_lost_or_stolen? do option in_the_uk: :complete_LS01_form option abroad: :which_country? save_input_as :location next_node do case location when 'in_the_uk' then :complete_LS01_form when 'abroad' then :which_country? end end end country_select :which_country?, exclude_countries: exclude_countries do save_input_as :country calculate :overseas_passports_embassies do location = WorldLocation.find(country) raise InvalidResponse unless location if location.fco_organisation location.fco_organisation.offices_with_service 'Lost or Stolen Passports' else [] end end next_node_if(:contact_the_embassy_canada, responded_with('canada')) next_node :contact_the_embassy end outcome :contact_the_embassy, use_outcome_templates: true outcome :contact_the_embassy_canada, use_outcome_templates: true outcome :complete_LS01_form, use_outcome_templates: true end end end
module SmartAnswer class ReportALostOrStolenPassportFlow < Flow def define name 'report-a-lost-or-stolen-passport' status :published satisfies_need "100221" exclude_countries = %w(holy-see british-antarctic-territory) multiple_choice :where_was_the_passport_lost_or_stolen? do option in_the_uk: :complete_LS01_form option abroad: :which_country? save_input_as :location next_node do case location when 'in_the_uk' then :complete_LS01_form when 'abroad' then :which_country? end end end country_select :which_country?, exclude_countries: exclude_countries do save_input_as :country calculate :overseas_passports_embassies do location = WorldLocation.find(country) raise InvalidResponse unless location if location.fco_organisation location.fco_organisation.offices_with_service 'Lost or Stolen Passports' else [] end end next_node_if(:contact_the_embassy_canada, responded_with('canada')) next_node :contact_the_embassy end use_outcome_templates outcome :contact_the_embassy outcome :contact_the_embassy_canada outcome :complete_LS01_form end end end
Fix dibs_referrals scope on user
module Spree User.class_eval do scope :dibs_referrers, lambda { includes(:roles).where("#{::Spree::Role.table_name}.name" => "dibs_referral") } has_many :dibs_referrals, class_name: '::Spree::Order', uniq: true end end
module Spree User.class_eval do scope :dibs_referrers, lambda { includes(:roles).where("#{::Spree::Role.table_name}.name" => "dibs_referral") } has_many :dibs_referrals, class_name: '::Spree::Order', foreign_key: 'dibs_referral_id', uniq: true end end
Revert "set ShopifyAPI::Base.site to string"
require_dependency "shop_product_sink/application_controller" module ShopProductSink class WebhooksController < ApplicationController include ShopProductSink::Webhooks include ShopProductSink::Shop def create handle_creation handle_update handle_deletion head :ok end def application_secret ENV['SHOPIFY_APP_SECRET'] || ENV['SHOPIFY_API_SECRET'] end def handle_creation return unless create? initialize_model.save! unless resource_class.exists?(resource_id) end def handle_update return unless update? remove_resource initialize_model.save! end def handle_deletion return unless delete? remove_resource end private def remove_resource resource_class.where(id: resource_id).destroy_all end def resource_class ShopProductSink::Product end def shopify_resource # set site to string or ActiveResource raises on call to .prefix on nil ShopifyAPI::Base.site = '' if ShopifyAPI::Base.site.nil? ShopifyAPI::Product end def shopify_object shopify_resource.new(request.params) end def initialize_model model = resource_class.initialize_from_resource(shopify_object) model.shop_id = shop_id model end end end
require_dependency "shop_product_sink/application_controller" module ShopProductSink class WebhooksController < ApplicationController include ShopProductSink::Webhooks include ShopProductSink::Shop def create handle_creation handle_update handle_deletion head :ok end def application_secret ENV['SHOPIFY_APP_SECRET'] || ENV['SHOPIFY_API_SECRET'] end def handle_creation return unless create? initialize_model.save! unless resource_class.exists?(resource_id) end def handle_update return unless update? remove_resource initialize_model.save! end def handle_deletion return unless delete? remove_resource end private def remove_resource resource_class.where(id: resource_id).destroy_all end def resource_class ShopProductSink::Product end def shopify_resource ShopifyAPI::Product end def shopify_object shopify_resource.new(request.params) end def initialize_model model = resource_class.initialize_from_resource(shopify_object) model.shop_id = shop_id model end end end
Put back AppConfig defaults to fix some IssuesController specs.
require 'ostruct' require 'yaml' unless Rails.env.test? AppConfig = YAML.load_file(Rails.root.join('config', 'cfme_bz.yml'))[Rails.env] rescue {"bugzilla"=>{}} AppConfig['bugzilla']['uri'] ||= "https://bugzilla.redhat.com/" AppConfig['bugzilla']['product'] ||= "CloudForms Management Engine" AppConfig['bugzilla']['bug_display_uri'] = AppConfig['bugzilla']['uri'] + "/show_bug.cgi?id=" end
require 'ostruct' require 'yaml' AppConfig = YAML.load_file(Rails.root.join('config', 'cfme_bz.yml'))[Rails.env] rescue {"bugzilla"=>{}} AppConfig['bugzilla']['uri'] ||= "https://bugzilla.redhat.com/" AppConfig['bugzilla']['product'] ||= "CloudForms Management Engine" AppConfig['bugzilla']['bug_display_uri'] = AppConfig['bugzilla']['uri'] + "/show_bug.cgi?id="
Change to rails version 4.1.0
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "ct_angular_ui_router_rails/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "ct_angular_ui_router_rails" s.version = CtAngularUiRouterRails::VERSION s.authors = ["Codetalay"] s.email = ["developer.codetalay@gmail.com"] s.homepage = "http://www.codetalay.com" s.summary = "Summary" s.description = "Description" s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 4.0.0" s.add_development_dependency "sqlite3" end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "ct_angular_ui_router_rails/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "ct_angular_ui_router_rails" s.version = CtAngularUiRouterRails::VERSION s.authors = ["Codetalay"] s.email = ["developer.codetalay@gmail.com"] s.homepage = "http://www.codetalay.com" s.summary = "Summary" s.description = "Description" s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 4.1.0" s.add_development_dependency "sqlite3" end
Add dot '.' on .field spec.
require 'spec_helper' describe ActiveForce::SObject do describe ".new" do it "create with valid values" do @SObject = Whizbang.new expect(@SObject).to be_an_instance_of Whizbang end end describe ".build" do let(:sobject_hash) { YAML.load(fixture('sobject/single_sobject_hash')) } it "build a valid sobject from a JSON" do expect(Whizbang.build sobject_hash).to be_an_instance_of Whizbang end end describe "field" do it "add a mappings" do expect(Whizbang.mappings).to include( checkbox: 'Checkbox_Label', text: 'Text_Label', date: 'Date_Label', datetime: 'DateTime_Label', picklist_multiselect: 'Picklist_Multiselect_Label' ) end it "set an attribute" do %w[checkbox text date datetime picklist_multiselect].each do |name| expect(Whizbang.attribute_names).to include(name) end end end end
require 'spec_helper' describe ActiveForce::SObject do describe ".new" do it "create with valid values" do @SObject = Whizbang.new expect(@SObject).to be_an_instance_of Whizbang end end describe ".build" do let(:sobject_hash) { YAML.load(fixture('sobject/single_sobject_hash')) } it "build a valid sobject from a JSON" do expect(Whizbang.build sobject_hash).to be_an_instance_of Whizbang end end describe ".field" do it "add a mappings" do expect(Whizbang.mappings).to include( checkbox: 'Checkbox_Label', text: 'Text_Label', date: 'Date_Label', datetime: 'DateTime_Label', picklist_multiselect: 'Picklist_Multiselect_Label' ) end it "set an attribute" do %w[checkbox text date datetime picklist_multiselect].each do |name| expect(Whizbang.attribute_names).to include(name) end end end end
Add fgdc reader module 'range' include minitest
# Reader - fgdc to internal data structure # unpack fgdc entity range domain # History: # Stan Smith 2017-09-06 original script require 'nokogiri' require 'adiwg/mdtranslator/internal/internal_metadata_obj' module ADIWG module Mdtranslator module Readers module Fgdc module Range def self.unpack(xRange, hAttribute, hResponseObj) # entity attribute 5.1.2.4.2.1 (rdommin) - range minimum # -> dataDictionary.entities.attributes.minValue min = xRange.xpath('./rdommin').text unless min.empty? hAttribute[:minValue] = min end # entity attribute 5.1.2.4.2.2 (rdommax) - range maximum # -> dataDictionary.entities.attributes.maxValue max = xRange.xpath('./rdommax').text unless max.empty? hAttribute[:maxValue] = max end # entity attribute 5.1.2.4.2.3 (attrunit) - units of measure # -> dataDictionary.entities.attributes.unitOfMeasure units = xRange.xpath('./attrunit').text unless units.empty? hAttribute[:unitOfMeasure] = units end # entity attribute 5.1.2.4.2.4 (attrmres) - measurement resolution # -> not mapped end end end end end end
Improve naming of variables in VariantOverridesIndexed for readability
# frozen_string_literal: true class VariantOverridesIndexed def initialize(variant_ids, distributor_ids) @variant_ids = variant_ids @distributor_ids = distributor_ids end def indexed variant_overrides.each_with_object(hash_of_hashes) do |variant_override, indexed| indexed[variant_override.hub_id][variant_override.variant] = variant_override end end private attr_reader :variant_ids, :distributor_ids def variant_overrides VariantOverride .joins(:variant) .preload(:variant) .where( hub_id: distributor_ids, variant_id: variant_ids, ) end def hash_of_hashes Hash.new { |h, k| h[k] = {} } end end
# frozen_string_literal: true # Produces mappings of variant overrides by distributor id and variant id # The primary use case for data structured in this way is for injection into # the initializer of the OpenFoodNetwork::ScopeVariantToHub class class VariantOverridesIndexed def initialize(variant_ids, distributor_ids) @variant_ids = variant_ids @distributor_ids = distributor_ids end def indexed scoped_variant_overrides.each_with_object(hash_of_hashes) do |variant_override, indexed| indexed[variant_override.hub_id][variant_override.variant] = variant_override end end private attr_reader :variant_ids, :distributor_ids def scoped_variant_overrides VariantOverride .joins(:variant) .preload(:variant) .where( hub_id: distributor_ids, variant_id: variant_ids, ) end def hash_of_hashes Hash.new { |hash, key| hash[key] = {} } end end
Add "add" command and add run_command to handling output when tty is false
require "git/si/version" require "thor" require "pager" module Git module Si class SvnInterface < Thor include Thor::Actions include Pager desc "hello <name>", "say hello" def hello(name) puts "Hello #{name}" end desc "status [FILES]", "Perform an svn status." def status(*args) command = "svn status --ignore-externals " + args.join(' ') run(command) end desc "diff [FILES]", "Perform an svn diff piped through a colorizer. Also tests to be sure a rebase is not needed." def diff(*args) command = "svn diff " + args.join(' ') results = `#{command}` if STDOUT.tty? page print_colordiff results else say results end end private def print_colordiff(diff) diff.each_line do |line| line.strip! case line when /^\+/ line = set_color line, :green when /^\-/ line = set_color line, :red end say line end end end end end
require "git/si/version" require "thor" require "pager" module Git module Si class SvnInterface < Thor include Thor::Actions include Pager desc "hello <name>", "say hello" def hello(name) puts "Hello #{name}" end desc "status [FILES]", "Perform an svn status." def status(*args) command = "svn status --ignore-externals " + args.join(' ') run_command(command) end desc "diff [FILES]", "Perform an svn diff piped through a colorizer. Also tests to be sure a rebase is not needed." def diff(*args) command = "svn diff " + args.join(' ') results = `#{command}` if STDOUT.tty? page print_colordiff results else say results end end desc "add [FILES]", "Perform an svn and a git add on the files." def add(*args) command = "svn add " + args.join(' ') run_command(command) command = "git add " + args.join(' ') run_command(command) end private def run_command(command, options={}) if STDOUT.tty? run(command, options) else run(command, options.update(verbose: false)) end end def print_colordiff(diff) diff.each_line do |line| line.strip! case line when /^\+/ line = set_color line, :green when /^\-/ line = set_color line, :red end say line end end end end end
Read image dimensions with FastImage instead of MiniMagick
class ImageUploader < ApplicationUploader def path "/#{model.class.table_name}/#{model.token}" end # Example with a 600x400 picture: thumb_size('x200') -> '300x200' def thumb_size(geometry) w, _, h = geometry.partition("x") return unless h.present? || w.present? if h.present? h = h.to_i w = model.image_width * h / model.image_height else w = w.to_i h = model.image_height * w / model.image_width end [w, h].join("x") end process :store_dimensions private def store_dimensions return unless file && model image = MiniMagick::Image.open(file.file) model.image_width = image.width model.image_height = image.height end end
class ImageUploader < ApplicationUploader def path "/#{model.class.table_name}/#{model.token}" end # Example with a 600x400 picture: thumb_size('x200') -> '300x200' def thumb_size(geometry) w, _, h = geometry.partition("x") return unless h.present? || w.present? if h.present? h = h.to_i w = model.image_width * h / model.image_height else w = w.to_i h = model.image_height * w / model.image_width end [w, h].join("x") end process :store_dimensions private def store_dimensions return unless file && model model.image_width, model.image_height = FastImage.size(file.file) end end
Add User association to Character factory
FactoryGirl.define do factory :character do name "MyString" age "MyString" end end
FactoryGirl.define do factory :character do name "MyString" age "MyString" user end end
Add tests for mergeable feature
require_relative '../../assets/lib/filters/mergeable' require_relative '../../assets/lib/pull_request' require_relative '../../assets/lib/input' require 'webmock/rspec' describe Filters::Mergeable do let(:ignore_pr) do PullRequest.new(pr: { 'number' => 1, 'head' => { 'sha' => 'abc' }, 'mergeable' => false, 'base' => { 'repo' => {'full_name' => 'user/repo', 'permissions' => {'push' => true} } } }) end let(:pr) do PullRequest.new(pr: { 'number' => 2, 'head' => { 'sha' => 'def' }, 'mergeable' => true , 'base' => { 'repo' => {'full_name' => 'user/repo', 'permissions' => {'push' => true} } } }) end let(:pull_requests) { [ignore_pr, pr] } def stub_json(uri, body) stub_request(:get, uri) .to_return(headers: { 'Content-Type' => 'application/json' }, body: body.to_json) end context 'when mergeable requirement is disabled' do it 'does not filter' do payload = { 'source' => { 'repo' => 'user/repo' } } filter = described_class.new(pull_requests: pull_requests, input: Input.instance(payload: payload)) expect(filter.pull_requests).to eq pull_requests end it 'does not filter when explictly disabled' do payload = { 'source' => { 'repo' => 'user/repo', 'only_mergeable' => false } } filter = described_class.new(pull_requests: pull_requests, input: Input.instance(payload: payload)) expect(filter.pull_requests).to eq pull_requests end end context 'when the mergeable filtering is enabled' do before do stub_json(%r{https://api.github.com/repos/user/repo/pulls/1/reviews}, [{ 'state' => 'CHANGES_REQUESTED' }]) stub_json(%r{https://api.github.com/repos/user/repo/pulls/2/reviews}, [{ 'state' => 'APPROVED' }]) end it 'only returns PRs with that label' do payload = { 'source' => { 'repo' => 'user/repo', 'only_mergeable' => true } } filter = described_class.new(pull_requests: pull_requests, input: Input.instance(payload: payload)) expect(filter.pull_requests).to eq [pr] end end end
Use context for rendering by default
require_relative 'exhibit' module DisplayCase class BasicExhibit < Exhibit def self.applicable_to?(*args) true end def to_partial_path if __getobj__.respond_to?(:to_partial_path) __getobj__.to_partial_path.dup else partialize_name(__getobj__.class.name) end end def render(template) template.render(:partial => to_partial_path, :object => self) end end end
require_relative 'exhibit' module DisplayCase class BasicExhibit < Exhibit def self.applicable_to?(*args) true end def to_partial_path if __getobj__.respond_to?(:to_partial_path) __getobj__.to_partial_path.dup else partialize_name(__getobj__.class.name) end end def render(template = self.context) template.render(:partial => to_partial_path, :object => self) end end end
Add time range to condition for query of MetricRollups
OUTPUT_CSV_FILE_PATH = 'cores_usage_per_label.csv'.freeze HEADERS_AND_COLUMNS = ['Hour', 'Date', 'Label of image (key : value)', 'Project', 'Used Cores'].freeze CSV.open(OUTPUT_CSV_FILE_PATH, "wb") do |csv| csv << HEADERS_AND_COLUMNS MetricRollup.where(:resource_type => 'CustomAttribute').order(:timestamp).select(:timestamp, :resource_name, :cpu_usage_rate_average, :resource_id, :resource_type).each do |mr| date = mr.timestamp.to_date hour = mr.timestamp.hour project_name = mr.resource_name label_name = "#{mr.resource.name}:#{mr.resource.value}" csv << [hour, date, label_name, project_name, mr.cpu_usage_rate_average] end end
#!/usr/bin/env ruby require File.expand_path("../config/environment", __dir__) require 'trollop' opts = Trollop.options(ARGV) do banner "USAGE: #{__FILE__} -h <number of days back to query metrics>\n" opt :days, "Days", :short => "d", :type => :int, :default => 1 end time_range = [opts[:days].days.ago.utc.beginning_of_hour..Time.now.utc.end_of_hour] OUTPUT_CSV_FILE_PATH = 'cores_usage_per_label.csv'.freeze HEADERS_AND_COLUMNS = ['Hour', 'Date', 'Label of image (key : value)', 'Project', 'Used Cores'].freeze CSV.open(OUTPUT_CSV_FILE_PATH, "wb") do |csv| csv << HEADERS_AND_COLUMNS MetricRollup.where(:timestamp => time_range, :resource_type => 'CustomAttribute').order(:timestamp).select(:timestamp, :resource_name, :cpu_usage_rate_average, :resource_id, :resource_type).each do |mr| date = mr.timestamp.to_date hour = mr.timestamp.hour project_name = mr.resource_name label_name = "#{mr.resource.name}:#{mr.resource.value}" csv << [hour, date, label_name, project_name, mr.cpu_usage_rate_average] end end
Update consul lookup in get-postgresql-primary
require 'resolv' module GitlabCtl class PostgreSQL class EE class << self def get_primary node_attributes = GitlabCtl::Util.get_node_attributes consul_enable = node_attributes.dig('consul', 'enable') postgresql_service_name = node_attributes.dig('patroni', 'scope') raise 'Consul agent is not enabled on this node' unless consul_enable raise 'PostgreSQL service name is not defined' if postgresql_service_name.nil? || postgresql_service_name.empty? Resolv::DNS.open(nameserver_port: [['127.0.0.1', 8600]]) do |dns| dns.getresources("master.#{postgresql_service_name}.service", Resolv::DNS::Resource::IN::SRV).map do |srv| "#{dns.getaddress(srv.target)}:#{srv.port}" end end end end end end end
require 'resolv' module GitlabCtl class PostgreSQL class EE class << self def get_primary node_attributes = GitlabCtl::Util.get_node_attributes consul_enable = node_attributes.dig('consul', 'enable') postgresql_service_name = node_attributes.dig('patroni', 'scope') raise 'Consul agent is not enabled on this node' unless consul_enable raise 'PostgreSQL service name is not defined' if postgresql_service_name.nil? || postgresql_service_name.empty? Resolv::DNS.open(nameserver_port: [['127.0.0.1', 8600]]) do |dns| dns.getresources("master.#{postgresql_service_name}.service.consul", Resolv::DNS::Resource::IN::SRV).map do |srv| "#{dns.getaddress(srv.target)}:#{srv.port}" end end end end end end end
Revert "Add `/lib` to eager_load_paths"
require_relative 'boot' require "action_controller/railtie" require "action_mailer/railtie" require "sprockets/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module ManualsPublisher class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.1 # 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. # These paths are non-standard (they are subdirectories of # app/models) so they need to be added to the autoload_paths config.autoload_paths << "#{Rails.root}/app/exporters/formatters" config.autoload_paths << "#{Rails.root}/app/models/validators" config.autoload_paths << "#{Rails.root}/app/services/manual" config.autoload_paths << "#{Rails.root}/app/services/section" config.autoload_paths << "#{Rails.root}/app/services/attachment" config.eager_load_paths << "#{Rails.root}/lib" end end
require_relative 'boot' require "action_controller/railtie" require "action_mailer/railtie" require "sprockets/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module ManualsPublisher class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.1 # 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. # These paths are non-standard (they are subdirectories of # app/models) so they need to be added to the autoload_paths config.autoload_paths << "#{Rails.root}/app/exporters/formatters" config.autoload_paths << "#{Rails.root}/app/models/validators" config.autoload_paths << "#{Rails.root}/app/services/manual" config.autoload_paths << "#{Rails.root}/app/services/section" config.autoload_paths << "#{Rails.root}/app/services/attachment" end end
Use auth method for blcoking user from viewing pages without login.
# Set up gems listed in the Gemfile. # See: http://gembundler.com/bundler_setup.html # http://stackoverflow.com/questions/7243486/why-do-you-need-require-bundler-setup ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) # Require gems we care about require 'rubygems' require 'uri' require 'pathname' require 'pg' require 'active_record' require 'logger' require 'sinatra' require "sinatra/reloader" if development? require 'erb' # Some helper constants for path-centric logic APP_ROOT = Pathname.new(File.expand_path('../../', __FILE__)) APP_NAME = APP_ROOT.basename.to_s # Set up the controllers and helpers Dir[APP_ROOT.join('app', 'controllers', '*.rb')].each { |file| require file } Dir[APP_ROOT.join('app', 'helpers', '*.rb')].each { |file| require file } # Set up the database and models require APP_ROOT.join('config', 'database')
# Set up gems listed in the Gemfile. # See: http://gembundler.com/bundler_setup.html # http://stackoverflow.com/questions/7243486/why-do-you-need-require-bundler-setup ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) # Require gems we care about require 'rubygems' require 'uri' require 'pathname' require 'pg' require 'active_record' require 'logger' require 'sinatra' require "sinatra/reloader" if development? require 'erb' # Some helper constants for path-centric logic APP_ROOT = Pathname.new(File.expand_path('../../', __FILE__)) APP_NAME = APP_ROOT.basename.to_s configure do # By default, Sinatra assumes that the root is the file that calls the configure block. # Since this is not the case for us, we set it manually. set :root, APP_ROOT.to_path # See: http://www.sinatrarb.com/faq.html#sessions enable :sessions set :session_secret, ENV['SESSION_SECRET'] || 'this is a secret shhhhh' # Set the views to set :views, File.join(Sinatra::Application.root, "app", "views") register do def auth (type) condition do redirect "/" unless send("current_#{type}") end end end end # Set up the controllers and helpers Dir[APP_ROOT.join('app', 'controllers', '*.rb')].each { |file| require file } Dir[APP_ROOT.join('app', 'helpers', '*.rb')].each { |file| require file } # Set up the database and models require APP_ROOT.join('config', 'database')
Update spec to version 2.1.17
Pod::Spec.new do |s| s.name = "LightRoute" s.version = "2.1.16" s.summary = "LightRoute is easy transition between view controllers and support many popylar arhitectures" s.description = <<-DESC LightRoute is easy transition between view controllers and support many popylar arhitectures. This framework very flow for settings your transition and have userfriendly API. DESC s.homepage = "https://github.com/SpectralDragon/LightRoute" s.documentation_url = "https://github.com/SpectralDragon/LightRoute" s.license = "MIT" s.author = { "Vladislav Prusakov" => "hipsterknights@gmail.com" } s.source = { :git => "https://github.com/SpectralDragon/LightRoute.git", :tag => "#{s.version}", :submodules => false } s.ios.deployment_target = "8.0" s.source_files = "Sources/*.swift", "Sources/TransitionNodes/*.swift", "Sources/Protocols/*.swift" end
Pod::Spec.new do |s| s.name = "LightRoute" s.version = "2.1.17" s.summary = "LightRoute is easy transition between view controllers and support many popylar arhitectures" s.description = <<-DESC LightRoute is easy transition between view controllers and support many popylar arhitectures. This framework very flow for settings your transition and have userfriendly API. DESC s.homepage = "https://github.com/SpectralDragon/LightRoute" s.documentation_url = "https://github.com/SpectralDragon/LightRoute" s.license = "MIT" s.author = { "Vladislav Prusakov" => "hipsterknights@gmail.com" } s.source = { :git => "https://github.com/SpectralDragon/LightRoute.git", :tag => "#{s.version}", :submodules => false } s.ios.deployment_target = "8.0" s.source_files = "Sources/*.swift", "Sources/TransitionNodes/*.swift", "Sources/Protocols/*.swift" end
Update pod file with new swift version and new dependencies
Pod::Spec.new do |s| s.name = 'RxKeyboard' s.version = '0.8.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', '>= 4.0.0' s.dependency 'RxCocoa', '>= 4.0.0' s.ios.deployment_target = '8.0' end
Pod::Spec.new do |s| s.name = 'RxKeyboard' s.version = '0.8.2' 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', '>= 4.1.2' s.dependency 'RxCocoa', '>= 4.1.2' s.ios.deployment_target = '8.0' end
Copy bash script from Jenkins as a starting point.
#!/usr/bin/env ruby # TODO: loop through all open pull requests. # fetch the merge-commit for the pull request. # NOTE: this automatically created by GitHub. `git fetch origin refs/pull/104/merge:` `git checkout FETCH_HEAD` # navigate into sub-directory if necessary `cd glue` # setup project with latest code. `bundle install` `rake db:create` `rake db:migrate` # setup jenkins and run tests. `rake -f /usr/lib/ruby/gems/1.9.1/gems/ci_reporter-1.7.0/stub.rake` `rake ci:setup:testunit` `rake test:all` # comment on the pull request on GitHub. `if [ $? == 0 ]; then # GitHub account for success: suse-jenkins-success / galileo224 curl -d '{ "body": "Well done! All tests are still passing after merging this pull request." }' -u "suse-jenkins-success:galileo224" -X POST https://api.github.com/repos/SUSE/happy-customer/issues/104/comments; else # GitHub account for failure: suse-jenkins-fail / galileo224 curl -d '{ "body": "Unfortunately your tests are failing after merging this pull request." }' -u "suse-jenkins-fail:galileo224" -X POST https://api.github.com/repos/SUSE/happy-customer/issues/104/comments; fi`
Include DelayedJob errors in Errbit exceptions
Airbrake.configure do |config| config.host = Rails.application.secrets.errbit_host config.project_id = Rails.application.secrets.errbit_project_id config.project_key = Rails.application.secrets.errbit_project_key config.environment = Rails.env config.ignore_environments = %w[development test] if config.host.blank? || config.project_id.blank? || config.project_key.blank? config.ignore_environments += [Rails.env] end config.performance_stats = false end Airbrake.add_filter do |notice| ignorables = %w[ActiveRecord::RecordNotFound] notice.ignore! if ignorables.include? notice[:errors].first[:type] end if Rails.application.secrets.errbit_self_hosted_ssl.present? # Patch from: https://mensfeld.pl/2016/05/setting-up-errbit-reporter-airbrake-v5-gem-to-work-with-self-signed-https-certificate/ module Patches module Airbrake module SyncSender def build_https(uri) super.tap do |req| req.verify_mode = OpenSSL::SSL::VERIFY_NONE end end end end end Airbrake::SyncSender.prepend(::Patches::Airbrake::SyncSender) end
require "airbrake/delayed_job" if defined?(Delayed) Airbrake.configure do |config| config.host = Rails.application.secrets.errbit_host config.project_id = Rails.application.secrets.errbit_project_id config.project_key = Rails.application.secrets.errbit_project_key config.environment = Rails.env config.ignore_environments = %w[development test] if config.host.blank? || config.project_id.blank? || config.project_key.blank? config.ignore_environments += [Rails.env] end config.performance_stats = false end Airbrake.add_filter do |notice| ignorables = %w[ActiveRecord::RecordNotFound] notice.ignore! if ignorables.include? notice[:errors].first[:type] end if Rails.application.secrets.errbit_self_hosted_ssl.present? # Patch from: https://mensfeld.pl/2016/05/setting-up-errbit-reporter-airbrake-v5-gem-to-work-with-self-signed-https-certificate/ module Patches module Airbrake module SyncSender def build_https(uri) super.tap do |req| req.verify_mode = OpenSSL::SSL::VERIFY_NONE end end end end end Airbrake::SyncSender.prepend(::Patches::Airbrake::SyncSender) end
Update the method names according to the previous commit to the HtmlEntities module
require "spec_helper" require "str_sanitizer/html_entities" RSpec.describe StrSanitizer::HtmlEntities do before(:each) do @methods = ExampleClass @encode_string = "<div>Hello world</div>" @decode_string = "&lt;div&gt;Hello world&lt;/div&gt;" end it "has some method for encoding and decoding" do expect(@methods.respond_to? :encode).to eq(true) expect(@methods.respond_to? :decode).to eq(true) end it "returns a encoded string" do encoded = @methods.encode(@encode_string) # The encoded string was done by `htmlentities` gem manually and pasted in here expect(encoded).to eq("&lt;div&gt;Hello world&lt;/div&gt;") end it "returns a decoded string" do decoded = @methods.decode(@decode_string) # The decoded string was done by `htmlentities` gem manually and pasted in here expect(decoded).to eq("<div>Hello world</div>") end it "doesn't throw any exception if nothing was there to encode and decode" do simple_string = "Hello world" expect(@methods.encode simple_string).to eq(simple_string) expect(@methods.decode simple_string).to eq(simple_string) end end class ExampleClass extend StrSanitizer::HtmlEntities end
require "spec_helper" require "str_sanitizer/html_entities" RSpec.describe StrSanitizer::HtmlEntities do before(:each) do @methods = ExampleClass @encode_string = "<div>Hello world</div>" @decode_string = "&lt;div&gt;Hello world&lt;/div&gt;" end it "has some method for encoding and decoding" do expect(@methods.respond_to? :html_encode).to eq(true) expect(@methods.respond_to? :html_decode).to eq(true) end it "returns a encoded string" do encoded = @methods.html_encode(@encode_string) # The encoded string was done by `htmlentities` gem manually and pasted in here expect(encoded).to eq("&lt;div&gt;Hello world&lt;/div&gt;") end it "returns a decoded string" do decoded = @methods.html_decode(@decode_string) # The decoded string was done by `htmlentities` gem manually and pasted in here expect(decoded).to eq("<div>Hello world</div>") end it "doesn't throw any exception if nothing was there to encode and decode" do simple_string = "Hello world" expect(@methods.html_encode simple_string).to eq(simple_string) expect(@methods.html_decode simple_string).to eq(simple_string) end end class ExampleClass extend StrSanitizer::HtmlEntities end
Update the group slugs and restore the index
class RestoreSlugIndexToGroups < ActiveRecord::Migration Group.all.each do |group| group.slug = nil group.save! end def change add_index :groups, :slug end end
class RestoreSlugIndexToGroups < ActiveRecord::Migration class Group < ActiveRecord::Base extend FriendlyId friendly_id :slug_candidates, use: :slugged has_ancestry cache_depth: true def slug_candidates candidates = [name] candidates << [parent.name, name] if parent.present? candidates end end def change Group.all.each do |group| group.slug = nil group.save end add_index :groups, :slug end end
Split out unwrapping of payload in TravisPayload to improve clarity
class TravisJsonPayload < Payload def building? status_content.first['state'] == 'started' end def build_status_is_processable? status_is_processable? end private def unwrap_params_hash(content) if content.respond_to?(:key?) && content.key?('payload') content['payload'] else content end end def convert_content!(content) status_content = unwrap_params_hash(content) Array.wrap(JSON.parse(status_content)) rescue JSON::ParserError self.processable = false [] end def parse_success(content) return if content['state'] == 'started' content['result'].to_i == 0 end def parse_url(content) end def parse_build_id(content) content['id'] end def parse_published_at(content) published_at = content['finished_at'] Time.parse(published_at).localtime if published_at.present? end end
class TravisJsonPayload < Payload def building? status_content.first['state'] == 'started' end def build_status_is_processable? status_is_processable? end private def unwrap_webhook_content(content) content['payload'] end def unwrap_polled_content(content) content end def convert_content!(content) status_content = if content.respond_to?(:key?) && content.key?('payload') unwrap_webhook_content(content) else unwrap_polled_content(content) end Array.wrap(JSON.parse(status_content)) rescue JSON::ParserError self.processable = false [] end def parse_success(content) return if content['state'] == 'started' content['result'].to_i == 0 end def parse_url(content) end def parse_build_id(content) content['id'] end def parse_published_at(content) published_at = content['finished_at'] Time.parse(published_at).localtime if published_at.present? end end
Check retutned response in test post campus
require 'test_helper' class CampusesTest < ActiveSupport::TestCase include Rack::Test::Methods include TestHelpers::AuthHelper include TestHelpers::JsonHelper def app Rails.application end def create_campus { name: 'Cloud', mode: 'online' } end def test_get_all_campuses get '/api/campuses' expected_data = Campus.all assert_equal expected_data.count, last_response_body.count end def test_post_campuses data_to_post = { campus: create_campus, auth_token: auth_token } post_json '/api/campuses', data_to_post assert_equal 201, last_response.status end def test_put_campuses campus = Campus.first data_to_put = { campus: campus, auth_token: auth_token } put_json '/api/campuses/1', data_to_put assert_equal 200, last_response.status end end
require 'test_helper' class CampusesTest < ActiveSupport::TestCase include Rack::Test::Methods include TestHelpers::AuthHelper include TestHelpers::JsonHelper def app Rails.application end def campus { name: 'Cloud', mode: 'timetable', abbreviation: 'C' } end def test_get_all_campuses get '/api/campuses' expected_data = Campus.all assert_equal expected_data.count, last_response_body.count end def test_post_campuses data_to_post = { campus: campus, auth_token: auth_token } post_json '/api/campuses', data_to_post assert_equal 201, last_response.status response_keys = %w(name abbreviation) campus = Campus.find(last_response_body['id']) assert_json_matches_model(last_response_body, campus, response_keys) assert_equal 0, campus[:mode] end def test_put_campuses campus = Campus.first data_to_put = { campus: campus, auth_token: auth_token } put_json '/api/campuses/1', data_to_put assert_equal 200, last_response.status end end
Fix hide keyboard on iOS
# encoding: utf-8 module Appium::Ios # @private # class_eval inside a method because class Selenium::WebDriver::Element # will trigger as soon as the file is required. in contrast a method # will trigger only when invoked. def patch_webdriver_element Selenium::WebDriver::Element.class_eval do # Cross platform way of entering text into a textfield def type text # enter text then tap window to hide the keyboard. js = <<-JS au.getElement('#{self.ref}').setValue('#{text}'); au.lookup('window')[0].tap(); JS @driver.execute_script js end end end end
# encoding: utf-8 module Appium::Ios # @private # class_eval inside a method because class Selenium::WebDriver::Element # will trigger as soon as the file is required. in contrast a method # will trigger only when invoked. def patch_webdriver_element Selenium::WebDriver::Element.class_eval do # Cross platform way of entering text into a textfield def type text # enter text then tap window to hide the keyboard. =begin Find the top left corner of the keyboard and move up 10 pixels (origin.y - 10) now swipe down until the end of the window - 10 pixels. -10 to ensure we're not going outside the window bounds. Swiping inside the keyboard will not dismiss it. =end js = <<-JS au.getElement('#{self.ref}').setValue('#{text}'); if (au.mainApp.keyboard().type() !== "UIAElementNil") { var startY = au.mainApp.keyboard().rect().origin.y - 10; var endY = au.mainWindow.rect().size.height - 10; au.flickApp(0, startY, 0, endY); } JS @driver.execute_script js end end end end
Make virtual attributes with explicit setter editable by default
module Netzke module Basepack # Common parts of FieldConfig and ColumnConfig class AttrConfig < ActiveSupport::OrderedOptions def initialize(c, data_adapter) c = {name: c.to_s} if c.is_a?(Symbol) || c.is_a?(String) c[:name] = c[:name].to_s self.replace(c) @data_adapter = data_adapter || NullDataAdapter.new(nil) end def primary? @data_adapter.primary_key_attr?(self) end def association? @data_adapter.association_attr?(self) end def set_defaults! set_read_only! if read_only.nil? end def set_read_only! self.read_only = primary? || virtual? || !responded_to_by_model? && !association? end private def responded_to_by_model? # if no model class is provided, assume the attribute is being responded to @data_adapter.model_class.nil? || @data_adapter.model_class.instance_methods.include?(:"#{name}=") || @data_adapter.model_class.attribute_names.include?(name) end end end end
module Netzke module Basepack # Common parts of FieldConfig and ColumnConfig class AttrConfig < ActiveSupport::OrderedOptions def initialize(c, data_adapter) c = {name: c.to_s} if c.is_a?(Symbol) || c.is_a?(String) c[:name] = c[:name].to_s self.replace(c) @data_adapter = data_adapter || NullDataAdapter.new(nil) end def primary? @data_adapter.primary_key_attr?(self) end def association? @data_adapter.association_attr?(self) end def set_defaults! set_read_only! if read_only.nil? end def set_read_only! self.read_only = primary? || !responded_to_by_model? && !association? end private def responded_to_by_model? # if no model class is provided, assume the attribute is being responded to @data_adapter.model_class.nil? || !setter.nil? || @data_adapter.model_class.instance_methods.include?(:"#{name}=") || @data_adapter.model_class.attribute_names.include?(name) end end end end
Define a test to check the generator generates new configuration file in YAML
require 'spec_helper' require 'generators/rakuten_web_service/config_generator' describe RakutenWebService::ConfigGenerator, type: :generator do before do end end
require 'spec_helper' require 'generators/rakuten_web_service/config_generator' describe RakutenWebService::ConfigGenerator, type: :generator do destination File.expand_path("./../../../tmp", __FILE__) before do prepare_destination run_generator end describe "generated configuration file" do subject { file('config/rakuten_web_service.yml') } it { is_expected.to exist } end end
Add "_fabicator" to the name of generated files
require 'rails/generators/fabrication_generator' module Fabrication module Generators class ModelGenerator < Base argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" class_option :dir, :type => :string, :default => "test/fabricators", :desc => "The directory where the fabricators should go" class_option :extension, :type => :string, :default => "rb", :desc => "file extension name" def create_fabrication_file template 'fabricator.rb', File.join(options[:dir], "#{table_name}.#{options[:extension].to_s}") end end end end
require 'rails/generators/fabrication_generator' module Fabrication module Generators class ModelGenerator < Base argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" class_option :dir, :type => :string, :default => "test/fabricators", :desc => "The directory where the fabricators should go" class_option :extension, :type => :string, :default => "rb", :desc => "file extension name" def create_fabrication_file template 'fabricator.rb', File.join(options[:dir], "#{table_name}_fabricator.#{options[:extension].to_s}") end end end end
Fix framework reference in podspec
Pod::Spec.new do |s| s.name = "plaid-ios-link" s.version = "0.1.1" s.summary = "Native iOS implementation of Plaid Link" s.homepage = "https://github.com/vouch/plaid-ios-link" s.license = 'MIT' s.author = { "Simon Levy" => "simon@vouch.com", "Andres Ugarte" => "andres@vouch.com" } s.source = { :git => "https://github.com/vouch/plaid-ios-link.git", :tag => s.version.to_s } s.platform = :ios, '8.0' s.requires_arc = true s.source_files = 'PlaidLink/Classes/**/*', 'plaid_ios_link.framework/Headers/*.h' s.public_header_files = 'PlaidLink/Classes/*.h', 'plaid_ios_link.framework/Headers/*.h' s.resource_bundle = { 'Resources' => ['PlaidLink/Resources/Images/*.png'] } s.dependency 'plaid-ios-sdk' end
Pod::Spec.new do |s| s.name = "plaid-ios-link" s.version = "0.1.1" s.summary = "Native iOS implementation of Plaid Link" s.homepage = "https://github.com/vouch/plaid-ios-link" s.license = 'MIT' s.author = { "Simon Levy" => "simon@vouch.com", "Andres Ugarte" => "andres@vouch.com" } s.source = { :git => "https://github.com/vouch/plaid-ios-link.git", :tag => s.version.to_s } s.platform = :ios, '8.0' s.requires_arc = true s.source_files = 'PlaidLink/Classes/**/*', 'plaid_ios_sdk.framework/Headers/*.h' s.public_header_files = 'PlaidLink/Classes/*.h', 'plaid_ios_sdk.framework/Headers/*.h' s.resource_bundle = { 'Resources' => ['PlaidLink/Resources/Images/*.png'] } s.dependency 'plaid-ios-sdk' end
Fix factory for NewsItem so tests pass.
FactoryGirl.define do factory :news_item do title 'News Headline' link 'http://example.com/news/1' end end
FactoryGirl.define do factory :news_item do title 'News Headline' link 'http://example.com/news/1' body 'news body' end end
Add logger example with validation
require 'spec_helper' class Logger alias :m :method def initialize(repository) @repository = repository end def log(item) validate(item) >> m(:transform) >= m(:save) end private attr_reader :repository def validate(item) return Failure(["Item cannot be empty"]) if item.blank? return Failure(["Item must be a Hash"]) unless item.is_a?(Hash) validate_required_params(item).match { none { Success(item) } some { |errors| Failure(errors) } } end def transform(params) ttl = params.delete(:ttl) params.merge!(_ttl: ttl) unless ttl.nil? Success(params) end def save(item) Success(repository.bulk_insert([item])) end def validate_required_params(params) required_params = %w(date tenant contract user facility short data) Option.any?(required_params .select{|key| Option.some?(params[key.to_sym]).none? } .map{|key| "#{key} is required"} ) end end class Ensure include Deterministic include Deterministic::Monad None = Deterministic::Option::None.instance attr_accessor :value def method_missing(m, *args) validator_m = "#{m}!".to_sym super unless respond_to? validator_m send(validator_m, *args).map { |v| Some([Error.new(m, v)])} end class Error attr_accessor :name, :value def initialize(name, value) @name, @value = name, value end def inspect "#{@name}(#{@value.inspect})" end end def not_empty! value.nil? || value.empty? ? Some(value) : None end def is_a!(type) value.is_a?(type) ? None : Some({obj: value, actual: value.class, expected: type}) end def has_key!(key) value.has_key?(key) ? None : Some(key) end end class Validator < Ensure def date_is_one! value[:date] == 1 ? None : Some({actual: value[:date], expected: 1}) end def required_params! params = %w(date tenant contract user facility short data) params.inject(None) { |errors, param| errors + (value[:param].nil? || value[:param].empty? ? Some([param]) : None) } end def call not_empty + is_a(Array) + None + has_key(:tenant) + Some("error").value_to_a + date_is_one + required_params end end describe Ensure do # None = Deterministic::Option::None.instance it "Ensure" do params = {date: 2} v = Validator.new(params) errors = v.call expect(errors).to be_a Deterministic::Some expect(errors.value).not_to be_empty end end
Use symbols rather than selectors for :within option. This is so we can change the tags the element use and change only one location to update them
module CapybaraExt # Just a shorter way of writing it. def assert_seen(text, opts={}) if opts[:within] within(opts[:within]) do page.should have_content(text) end else page.should have_content(text) end end def flash_error!(text) within("#flash_error") do assert_seen(text) end end def flash_notice!(text) within("#flash_notice") do assert_seen(text) end end end RSpec.configure do |config| config.include CapybaraExt end
module CapybaraExt # Just a shorter way of writing it. def assert_seen(text, opts={}) if opts[:within] within(selector_for(opts[:within])) do page.should have_content(text) end else page.should have_content(text) end end def flash_error!(text) within("#flash_error") do assert_seen(text) end end def flash_notice!(text) within("#flash_notice") do assert_seen(text) end end def selector_for(identifier) case identifier when :topic_header "#topic h2" when :post_text "#posts .post .text" when :post_user "#posts .post .user" else pending "No selector defined for #{identifier}. Please define one in spec/support/capybara_ext.rb" end end end RSpec.configure do |config| config.include CapybaraExt end
Use shared core API to satisfy Embedded and Server
module Neo4j::ActiveRel module Initialize extend ActiveSupport::Concern include Neo4j::Shared::Initialize # called when loading the rel from the database # @param [Neo4j::Embedded::EmbeddedRelationship, Neo4j::Server::CypherRelationship] persisted_rel properties of this relationship # @param [Neo4j::Relationship] from_node_id The neo_id of the starting node of this rel # @param [Neo4j::Relationship] to_node_id The neo_id of the ending node of this rel # @param [String] type the relationship type def init_on_load(persisted_rel, from_node_id, to_node_id, type) @rel_type = type @_persisted_obj = persisted_rel changed_attributes && changed_attributes.clear @attributes = convert_and_assign_attributes(persisted_rel.props) load_nodes(from_node_id, to_node_id) end def init_on_reload(unwrapped_reloaded) @attributes = nil init_on_load(unwrapped_reloaded, unwrapped_reloaded.start_node_neo_id, unwrapped_reloaded.end_node_neo_id, unwrapped_reloaded.rel_type) self end end end
module Neo4j::ActiveRel module Initialize extend ActiveSupport::Concern include Neo4j::Shared::Initialize # called when loading the rel from the database # @param [Neo4j::Embedded::EmbeddedRelationship, Neo4j::Server::CypherRelationship] persisted_rel properties of this relationship # @param [Neo4j::Relationship] from_node_id The neo_id of the starting node of this rel # @param [Neo4j::Relationship] to_node_id The neo_id of the ending node of this rel # @param [String] type the relationship type def init_on_load(persisted_rel, from_node_id, to_node_id, type) @rel_type = type @_persisted_obj = persisted_rel changed_attributes && changed_attributes.clear @attributes = convert_and_assign_attributes(persisted_rel.props) load_nodes(from_node_id, to_node_id) end def init_on_reload(unwrapped_reloaded) @attributes = nil init_on_load(unwrapped_reloaded, unwrapped_reloaded._start_node_id, unwrapped_reloaded._end_node_id, unwrapped_reloaded.rel_type) self end end end
Fix an issue to show minute with 0
require 'uri' require 'cgi' module VideosHelper def get_title(video) if video && video.title.length > 0 video.title else "(no title)" end end def get_thumbnail(video) videoId = get_id(video) if videoId "http://i.ytimg.com/vi/#{videoId}/default.jpg" else "" end end def get_duration(video) duration = video.duration if duration sec = duration % 60; min = (duration / 60).floor % 60; hour = (duration / 3600).floor; (hour > 0 ? hour.to_s + ':' : '') + min.to_s + ':' + (sec < 10 ? '0' + sec.to_s : sec.to_s) else "" end end def get_player(video) videoId = get_id(video) if videoId "http://www.youtube.com/embed/#{videoId}?enablejsapi=1" else "" end end def simple_time(time) time.strftime("%b/%d/%y %H:%M") end private def get_id(video) uri = URI(video.url) if uri.host == "www.youtube.com" params = CGI::parse("#{uri.query}") params['v'].first else nil end end end
require 'uri' require 'cgi' module VideosHelper def get_title(video) if video && video.title.length > 0 video.title else "(no title)" end end def get_thumbnail(video) videoId = get_id(video) if videoId "http://i.ytimg.com/vi/#{videoId}/default.jpg" else "" end end def get_duration(video) duration = video.duration if duration sec = duration % 60; min = (duration / 60).floor % 60; hour = (duration / 3600).floor; (hour > 0 ? hour.to_s + ':' : '') + (min < 10 ? '0' : '' ) + min.to_s + ':' + (sec < 10 ? '0' : '') + sec.to_s else "" end end def get_player(video) videoId = get_id(video) if videoId "http://www.youtube.com/embed/#{videoId}?enablejsapi=1" else "" end end def simple_time(time) time.strftime("%b/%d/%y %H:%M") end private def get_id(video) uri = URI(video.url) if uri.host == "www.youtube.com" params = CGI::parse("#{uri.query}") params['v'].first else nil end end end
Update description, summary, homepage in gemspec
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'git_pissed/version' Gem::Specification.new do |spec| spec.name = 'git_pissed' spec.version = GitPissed::VERSION spec.authors = ['Chris Hunt'] spec.email = ['c@chrishunt.co'] spec.description = %q{Track words over time in your git repository} spec.summary = %q{Track words over time in your git repository} spec.homepage = '' spec.license = 'MIT' spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.add_dependency 'ruby-progressbar' spec.add_development_dependency 'bundler', '~> 1.3' spec.add_development_dependency 'rake' end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'git_pissed/version' Gem::Specification.new do |spec| spec.name = 'git_pissed' spec.version = GitPissed::VERSION spec.authors = ['Chris Hunt'] spec.email = ['c@chrishunt.co'] spec.description = %q{Gitting pissed about your code} spec.summary = %q{Gitting pissed about your code} spec.homepage = 'http://chrishunt.co/git-pissed' spec.license = 'MIT' spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.add_dependency 'ruby-progressbar' spec.add_development_dependency 'bundler', '~> 1.3' spec.add_development_dependency 'rake' end
Add code to run if standalone feature
#! ruby require File.dirname(__FILE__) + '/legal_markdown/version' require File.dirname(__FILE__) + '/legal_markdown/make_yaml_frontmatter.rb' require File.dirname(__FILE__) + '/legal_markdown/legal_to_markdown.rb' module LegalMarkdown def self.parse(*args) args = ARGV.dup if(!args[0]) STDERR.puts "Sorry, I didn't understand that. Please give me your legal_markdown filenames or \"-\" for stdin." exit 0 elsif args.include?("--headers") LegalMarkdown::MakeYamlFrontMatter.new(args) else LegalMarkdown::LegalToMarkdown.parse_markdown(args) end end end
#! ruby require File.dirname(__FILE__) + '/legal_markdown/version' require File.dirname(__FILE__) + '/legal_markdown/make_yaml_frontmatter.rb' require File.dirname(__FILE__) + '/legal_markdown/legal_to_markdown.rb' module LegalMarkdown def self.parse(*args) args = ARGV.dup if(!args[0]) STDERR.puts "Sorry, I didn't understand that. Please give me your legal_markdown filenames or \"-\" for stdin." exit 0 elsif args.include?("--headers") LegalMarkdown::MakeYamlFrontMatter.new(args) else LegalMarkdown::LegalToMarkdown.parse_markdown(args) end end end # if launched as a standalone program, not loaded as a module LegalToMarkdown.parse if __FILE__ == $0
Add script for seeing how many students create a Bibliography sandbox
campaign = Campaign.find_by_slug 'fall_2021' no_bibliography = [['course', 'title', 'exists?']] campaign.courses.each do |course| puts course.slug sandboxes = course.sandboxes.map(&:title) course.assignments.each do |assignment| assignment_sandboxes = sandboxes.select { |sb| sb.include? assignment.article_title } next if assignment_sandboxes.empty? next if assignment_sandboxes.any? { |sb| sb.include? 'Bibliography' } no_bibliography << [course.slug, assignment.article_title, assignment.article_id.present?] + assignment_sandboxes end end File.write("/alloc/data/no_bibliography.csv", no_bibliography.map(&:to_csv).join) ## Bibliographies campaign = Campaign.find_by_slug 'fall_2021' bibliography_count = 0 campaign.courses.each do |course| bibliographies = course.sandboxes.map(&:title).select { |sb| sb.include? 'Bibliography' } bibliography_count += bibliographies.count end puts "Bibliography count: #{bibliography_count}"
Add URL of event at the end of summary in calendar entry
class StaticPagesController < ApplicationController def home end def contact end def feed @title = "Developers Connect Philippines" @entries = (Event.include_subevents.all + Article.all) .sort_by(&:updated_at).reverse @updated = unless @entries.empty? @entries.first.updated_at else DateTime.now end respond_to do |format| format.atom { render :layout => false } format.rss { redirect_to feed_path(:format => :atom), :status => :moved_permanently } end end def calendar cal = Icalendar::Calendar.new cal.custom_property("X-WR-CALNAME", "DevCon Calendar of Events") cal.custom_property("X-WR-TIMEZONE", "Asia/Manila") Event.all.each do |event_temp| url = event_url(event_temp) cal.event do dtstart event_temp.start_at.strftime("%Y%m%dT%H%M00") dtend event_temp.end_at.strftime("%Y%m%dT%H%M00") dtstamp event_temp.updated_at.strftime("%Y%m%dT%H%M00") uid "#{event_temp.slug}@devcon.ph" summary event_temp.name description event_temp.summary klass 'PUBLIC' url url end end send_data cal.to_ical, filename: "calendar.ics", type: 'text/calendar', x_sendfile: true end end
class StaticPagesController < ApplicationController def home end def contact end def feed @title = "Developers Connect Philippines" @entries = (Event.include_subevents.all + Article.all) .sort_by(&:updated_at).reverse @updated = unless @entries.empty? @entries.first.updated_at else DateTime.now end respond_to do |format| format.atom { render :layout => false } format.rss { redirect_to feed_path(:format => :atom), :status => :moved_permanently } end end def calendar cal = Icalendar::Calendar.new cal.custom_property("X-WR-CALNAME", "DevCon Calendar of Events") cal.custom_property("X-WR-TIMEZONE", "Asia/Manila") Event.all.each do |event_temp| url = event_url(event_temp) cal.event do dtstart event_temp.start_at.strftime("%Y%m%dT%H%M00") dtend event_temp.end_at.strftime("%Y%m%dT%H%M00") dtstamp event_temp.updated_at.strftime("%Y%m%dT%H%M00") uid "#{event_temp.slug}@devcon.ph" summary event_temp.name description (event_temp.summary || "") + " " + url klass 'PUBLIC' url url end end send_data cal.to_ical, filename: "calendar.ics", type: 'text/calendar', x_sendfile: true end end
Make it easier on _ in names.
activate :aria_current activate :directory_indexes activate :syntax do |syntax| syntax.css_class = "syntax-highlight" end set :markdown, tables: true, autolink: true, gh_blockcode: true, fenced_code_blocks: true, with_toc_data: false set :markdown_engine, :redcarpet set :res_version, File.read('../RES_VERSION') page "/", layout: "landing" page "/docs/*", layout: "documentation"
activate :aria_current activate :directory_indexes activate :syntax do |syntax| syntax.css_class = "syntax-highlight" end set :markdown, tables: true, autolink: true, gh_blockcode: true, fenced_code_blocks: true, with_toc_data: false, no_intra_emphasis: true set :markdown_engine, :redcarpet set :res_version, File.read('../RES_VERSION') page "/", layout: "landing" page "/docs/*", layout: "documentation"
Add plugin to track connections from netfilter and percent of connections available.
class ConnectionTracking < Scout::Plugin def build_report conntrack_max_output = `cat /proc/sys/net/netfilter/nf_conntrack_max` max = conntrack_max_output.split("\n")[0].to_i conntrack_count_output = `cat /proc/sys/net/netfilter/nf_conntrack_count` count = conntrack_count_output.split("\n")[0].to_i percent = (count.to_f / max.to_f) * 100 report(:conntrack_count => count, :conntrack_max => max, :conntrack_percent_used => percent) end end
Order versions by build date
class StatsController < ApplicationController before_filter :find_gem, :only => :show before_filter :ensure_hosted, :only => :show def index @number_of_gems = Rubygem.total_count @number_of_users = User.count @number_of_downloads = Download.count @most_downloaded = Rubygem.downloaded(10) end def show if params[:version_id] @subtitle = I18n.t('stats.show.for', :for => params[:version_id]) @version = Version.find_from_slug!(@rubygem.id, params[:version_id]) @versions = [@version] @downloads_today = Download.today(@version) @rank = Download.rank(@version) else @subtitle = I18n.t('stats.show.overview') @version = @rubygem.versions.most_recent @versions = @rubygem.versions.with_indexed.by_position.limit(5) @downloads_today = Download.today(@rubygem.versions) @rank = Download.highest_rank(@rubygem.versions) end @downloads_total = @version.rubygem.downloads @cardinality = Download.cardinality end private def ensure_hosted render :file => 'public/404.html', :status => :not_found if !@rubygem.hosted? end end
class StatsController < ApplicationController before_filter :find_gem, :only => :show before_filter :ensure_hosted, :only => :show def index @number_of_gems = Rubygem.total_count @number_of_users = User.count @number_of_downloads = Download.count @most_downloaded = Rubygem.downloaded(10) end def show if params[:version_id] @subtitle = I18n.t('stats.show.for', :for => params[:version_id]) @version = Version.find_from_slug!(@rubygem.id, params[:version_id]) @versions = [@version] @downloads_today = Download.today(@version) @rank = Download.rank(@version) else @subtitle = I18n.t('stats.show.overview') @version = @rubygem.versions.most_recent @versions = @rubygem.versions.with_indexed.by_built_at.limit(5) @downloads_today = Download.today(@rubygem.versions) @rank = Download.highest_rank(@rubygem.versions) end @downloads_total = @version.rubygem.downloads @cardinality = Download.cardinality end private def ensure_hosted render :file => 'public/404.html', :status => :not_found if !@rubygem.hosted? end end
Sort Freckle projects by name
module Hamckle class Freckle def initialize(options) LetsFreckle.configure do account_host options[:account_host] username options[:username] token options[:token] end end def projects @projects ||= LetsFreckle::Project.all end def create(project_id, date, duration, description) response = LetsFreckle::Entry.create(project_id: project_id, date: date, minutes: duration, description: description) (response.status == 201) end end end
module Hamckle class Freckle def initialize(options) LetsFreckle.configure do account_host options[:account_host] username options[:username] token options[:token] end end def projects @projects ||= LetsFreckle::Project.all.sort_by(&:name) end def create(project_id, date, duration, description) response = LetsFreckle::Entry.create(project_id: project_id, date: date, minutes: duration, description: description) (response.status == 201) end end end
Implement new format of stats
class GetStats def call(team_params) team = PrepareTeam.new.call(team_params) data = fetch_data(team) format(data) end private def fetch_data team team.team_members.order('team_members.points DESC') end def format data data.map{|tm| "#{tm.slack_user_name}: #{tm.points}"}.join(", ") end end
class GetStats def call(team_params) team = PrepareTeam.new.call(team_params) data = fetch_data(team) format(data) end private def fetch_data team team.team_members end def format data grouped_data = data.group_by(&:points) grouped_data.keys .sort .reverse_each .map do |key| members = grouped_data[key].map { |tm| tm.slack_user_name }.join(', ') "#{key}: #{members}" end.join("\n") end end
Remove deprecated use of Connection::Client
module HTTP module Commands class Connect attr_reader :host attr_reader :port attr_reader :scheduler attr_reader :ssl_context def initialize(host, port, ssl_context, scheduler=nil) @host = host @port = port @ssl_context = ssl_context @scheduler = scheduler end def self.build(uri, scheduler: nil, verify_certs: nil) verify_certs = true if verify_certs.nil? host = uri.host port = uri.port if uri.scheme == 'https' ssl_context = self.ssl_context verify_certs end new(host, port, ssl_context, scheduler) end def self.call(*arguments) instance = build *arguments instance.() end def call Connection.client( host, port, scheduler: scheduler, ssl: ssl_context ) end def self.configure_connection(receiver, uri) connection = self.(uri) receiver.connection = connection connection end def self.ssl_context(verify_certs) ssl_context = OpenSSL::SSL::SSLContext.new if verify_certs ssl_context.set_params verify_mode: OpenSSL::SSL::VERIFY_PEER else ssl_context.set_params verify_mode: OpenSSL::SSL::VERIFY_NONE end ssl_context end end end end
module HTTP module Commands class Connect attr_reader :host attr_reader :port attr_reader :scheduler attr_reader :ssl_context def initialize(host, port, ssl_context, scheduler=nil) @host = host @port = port @ssl_context = ssl_context @scheduler = scheduler end def self.build(uri, scheduler: nil, verify_certs: nil) verify_certs = true if verify_certs.nil? host = uri.host port = uri.port if uri.scheme == 'https' ssl_context = self.ssl_context verify_certs end new(host, port, ssl_context, scheduler) end def self.call(*arguments) instance = build *arguments instance.() end def call Connection::Client.build( host, port, scheduler: scheduler, ssl: ssl_context ) end def self.configure_connection(receiver, uri) connection = self.(uri) receiver.connection = connection connection end def self.ssl_context(verify_certs) ssl_context = OpenSSL::SSL::SSLContext.new if verify_certs ssl_context.set_params verify_mode: OpenSSL::SSL::VERIFY_PEER else ssl_context.set_params verify_mode: OpenSSL::SSL::VERIFY_NONE end ssl_context end end end end
Use the CancelsCourseMembership service when destroying a course membership
class CourseMembershipsController < ApplicationController before_filter :ensure_staff? def create @course_membership = current_course.course_memberships.create(params[:course_membership]) @course_membership.save respond_with @course_membership expire_action :action => :index end def destroy @course_membership = current_course.course_memberships.find(params[:id]) @course_membership.destroy respond_to do |format| format.html { redirect_to students_path, notice: 'Student was successfully removed from course.' } format.json { head :ok } end end end
class CourseMembershipsController < ApplicationController before_filter :ensure_staff? def create @course_membership = current_course.course_memberships.create(params[:course_membership]) @course_membership.save respond_with @course_membership expire_action :action => :index end def destroy course_membership = current_course.course_memberships.find(params[:id]) CancelsCourseMembership.for_student course_membership respond_to do |format| format.html { redirect_to students_path, notice: 'Student was successfully removed from course.' } format.json { head :ok } end end end
Switch to python-pgmagick on buildserver too
user = node[:settings][:user] execute "apt-get-update" do command "apt-get update" end %w{ant ant-contrib autoconf autopoint bison cmake expect libtool libsaxonb-java libssl1.0.0 libssl-dev maven openjdk-7-jdk javacc python python-magic git-core mercurial subversion bzr git-svn make perlmagick pkg-config zip ruby rubygems librmagick-ruby yasm imagemagick gettext realpath transfig texinfo curl librsvg2-bin xsltproc vorbis-tools}.each do |pkg| package pkg do action :install end end if node['kernel']['machine'] == "x86_64" %w{libstdc++6:i386 libgcc1:i386 zlib1g:i386 libncurses5:i386}.each do |pkg| package pkg do action :install end end end execute "add-bsenv" do user user command "echo \". ./.bsenv \" >> /home/#{user}/.bashrc" not_if "grep bsenv /home/#{user}/.bashrc" end
user = node[:settings][:user] execute "apt-get-update" do command "apt-get update" end %w{ant ant-contrib autoconf autopoint bison cmake expect libtool libsaxonb-java libssl1.0.0 libssl-dev maven openjdk-7-jdk javacc python python-pgmagick git-core mercurial subversion bzr git-svn make perlmagick pkg-config zip ruby rubygems librmagick-ruby yasm imagemagick gettext realpath transfig texinfo curl librsvg2-bin xsltproc vorbis-tools}.each do |pkg| package pkg do action :install end end if node['kernel']['machine'] == "x86_64" %w{libstdc++6:i386 libgcc1:i386 zlib1g:i386 libncurses5:i386}.each do |pkg| package pkg do action :install end end end execute "add-bsenv" do user user command "echo \". ./.bsenv \" >> /home/#{user}/.bashrc" not_if "grep bsenv /home/#{user}/.bashrc" end
Remove non existing policy relations
#These records are `Policy` associations for Detailed Guides where the policy #does no exist in publishing api. As there doesn't seem to be any other way of #identifying the policies that they relate to we may as well tidy them up # #433102,/guidance/being-inspected-as-a-childrens-centre-guidance-for-providers # ["5d646277-7631-11e4-a3cb-005056011aef"] not in publishing api #441050,/guidance/fashion-and-textiles-technical-apprenticeships # ["6053a0e7-7631-11e4-a3cb-005056011aef"] not in publishing api #480715,/guidance/being-inspected-as-a-boarding-andor-residential-school # ["5d646277-7631-11e4-a3cb-005056011aef"] not in publishing api EditionPolicy.where(edition_id: [433102, 441050, 480715]).destroy
Add rubocop as development dependency
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'uchiwa/version' Gem::Specification.new do |spec| spec.name = "uchiwa" spec.version = Uchiwa::VERSION spec.authors = ["meganemura"] spec.email = ["mura2megane@gmail.com"] spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com' to prevent pushes to rubygems.org, or delete to allow pushes to any server." spec.required_rubygems_version = ">= 2.0" spec.summary = %q{TODO: Write a short summary, because Rubygems requires one.} spec.description = %q{TODO: Write a longer description or delete this line.} spec.homepage = "TODO: Put your gem's website or public repo URL here." spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'uchiwa/version' Gem::Specification.new do |spec| spec.name = "uchiwa" spec.version = Uchiwa::VERSION spec.authors = ["meganemura"] spec.email = ["mura2megane@gmail.com"] spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com' to prevent pushes to rubygems.org, or delete to allow pushes to any server." spec.required_rubygems_version = ">= 2.0" spec.summary = %q{TODO: Write a short summary, because Rubygems requires one.} spec.description = %q{TODO: Write a longer description or delete this line.} spec.homepage = "TODO: Put your gem's website or public repo URL here." spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rubocop" end
Fix improper deferral of network overhead to Query layer with large data sets
module FogTracker # Tracks a single Fog collection in a single account class ResourceTracker attr_accessor :collection # Creates an object for tracking a single Fog collection in a single account # # ==== Attributes # # * +resource_type+ - the Fog collection name (String) for this resource type # * +account_tracker+ - the AccountTracker for this tracker's @collection def initialize(resource_type, account_tracker) @type = resource_type @account_tracker = account_tracker @account = account_tracker.account @account_name = account_tracker.name @log = account_tracker.log @collection = Array.new @log.debug "Created tracker for #{@type} on #{@account_name}." end # Polls the account's connection for updated info on all existing # instances of the relevant resource type, and saves them as @collection def update @log.info "Polling #{@type} on #{@account_name}..." @collection = @account_tracker.connection.send(@type) @log.info "Discovered #{@collection.count} #{@type} on #{@account_name}." end end end
module FogTracker # Tracks a single Fog collection in a single account class ResourceTracker attr_accessor :collection # Creates an object for tracking a single Fog collection in a single account # # ==== Attributes # # * +resource_type+ - the Fog collection name (String) for this resource type # * +account_tracker+ - the AccountTracker for this tracker's @collection def initialize(resource_type, account_tracker) @type = resource_type @account_tracker = account_tracker @account = account_tracker.account @account_name = account_tracker.name @log = account_tracker.log @collection = Array.new @log.debug "Created tracker for #{@type} on #{@account_name}." end # Polls the account's connection for updated info on all existing # instances of the relevant resource type, and saves them as @collection def update @log.info "Polling #{@type} on #{@account_name}..." fog_collection = @account_tracker.connection.send(@type) || Array.new @log.info "Fetching #{fog_collection.count} #{@type} on #{@account_name}." new_collection = Array.new # Here's where most of the network overhead is actually incurred fog_collection.each do |resource| @log.debug "Fetching resource: #{resource.class} #{resource.identity}" new_collection << resource @log.debug "Got resource: #{resource.inspect}" end @collection = new_collection end end end
Change Jekyll to a runtime dependency
# coding: utf-8 Gem::Specification.new do |spec| spec.name = "minimal-mistakes-jekyll" spec.version = "4.1.0" spec.authors = ["Michael Rose"] spec.summary = %q{A flexible two-column Jekyll theme.} spec.homepage = "https://github.com/mmistakes/minimal-mistakes" spec.license = "MIT" spec.metadata["plugin_type"] = "theme" spec.files = `git ls-files -z`.split("\x0").select do |f| f.match(%r{^(assets|_(includes|layouts|sass)/|(LICENSE|README|CHANGELOG)((\.(txt|md|markdown)|$)))}i) end spec.add_dependency "jekyll", "~> 3.3" spec.add_development_dependency "bundler", "~> 1.12" spec.add_development_dependency "rake", "~> 10.0" spec.add_runtime_dependency "jekyll-paginate", "~> 1.1" spec.add_runtime_dependency "jekyll-sitemap", "~> 0.12" spec.add_runtime_dependency "jekyll-gist", "~> 1.4" spec.add_runtime_dependency "jekyll-feed", "~> 0.8" spec.add_runtime_dependency "jemoji", "~> 0.7" end
# coding: utf-8 Gem::Specification.new do |spec| spec.name = "minimal-mistakes-jekyll" spec.version = "4.1.0" spec.authors = ["Michael Rose"] spec.summary = %q{A flexible two-column Jekyll theme.} spec.homepage = "https://github.com/mmistakes/minimal-mistakes" spec.license = "MIT" spec.metadata["plugin_type"] = "theme" spec.files = `git ls-files -z`.split("\x0").select do |f| f.match(%r{^(assets|_(includes|layouts|sass)/|(LICENSE|README|CHANGELOG)((\.(txt|md|markdown)|$)))}i) end spec.add_runtime_dependency "jekyll", "~> 3.3" spec.add_runtime_dependency "jekyll-paginate", "~> 1.1" spec.add_runtime_dependency "jekyll-sitemap", "~> 0.12" spec.add_runtime_dependency "jekyll-gist", "~> 1.4" spec.add_runtime_dependency "jekyll-feed", "~> 0.8" spec.add_runtime_dependency "jemoji", "~> 0.7" spec.add_development_dependency "bundler", "~> 1.12" spec.add_development_dependency "rake", "~> 10.0" end
Add more attributes to Sense
require 'virtus' # Sense class Sense include Virtus.model attribute :id, String attribute :antonyms, Array[OpenStruct] attribute :cross_references, Array[OpenStruct] attribute :cross_reference_markers, Array[String] attribute :definitions, Array[String] attribute :domains, Array[String] attribute :examples, Array[OpenStruct] attribute :registers, Array[String] attribute :subsenses, Array[Sense] attribute :synonyms, Array[OpenStruct] attribute :translations, Array[OpenStruct] end
require 'virtus' # Sense class Sense include Virtus.model attribute :id, String attribute :antonyms, Array[OpenStruct] attribute :cross_references, Array[OpenStruct] attribute :cross_reference_markers, Array[String] attribute :definitions, Array[String] attribute :domains, Array[String] attribute :examples, Array[OpenStruct] attribute :regions, Array[String] attribute :registers, Array[String] attribute :subsenses, Array[Sense] attribute :synonyms, Array[OpenStruct] attribute :translations, Array[OpenStruct] attribute :variant_forms, Array[OpenStruct] end
Fix title test - capybara uses a different syntax than webrat.
require 'spec_helper' describe HomeController do render_views describe "GET 'index'" do it "returns http success" do get 'index' response.should be_success response.should have_selector("title", :content => "Circle - Continuous Integration made easy") end end end
require 'spec_helper' describe HomeController do render_views describe "GET 'index'" do it "returns http success" do get 'index' response.should be_success response.body.should have_selector("title", :content => "Circle - Continuous Integration made easy") end end end
Change promotion_choice default choice to 'none'
module PresentationToggles extend ActiveSupport::Concern included do field :presentation_toggles, type: Hash, default: default_presentation_toggles validates :promotion_choice_url, presence: true, if: :promotes_something? validates :promotion_choice, inclusion: { in: %w(none organ_donor register_to_vote) } end def promotion_choice=(value) promotion_choice_key["choice"] = value end def promotion_choice_url=(value) promotion_choice_key['url'] = value end def promotion_choice choice = promotion_choice_key["choice"] choice.empty? ? "none" : choice end def promotes_something? promotion_choice != 'none' end def promotion_choice_url promotion_choice_key["url"] end def promotion_choice_key unless presentation_toggles.key? 'promotion_choice' presentation_toggles['promotion_choice'] = self.class.default_presentation_toggles['promotion_choice'] end presentation_toggles['promotion_choice'] end module ClassMethods def default_presentation_toggles { 'promotion_choice' => { 'choice' => '', 'url' => '' } } end end end
module PresentationToggles extend ActiveSupport::Concern included do field :presentation_toggles, type: Hash, default: default_presentation_toggles validates :promotion_choice_url, presence: true, if: :promotes_something? validates :promotion_choice, inclusion: { in: %w(none organ_donor register_to_vote) } end def promotion_choice=(value) promotion_choice_key["choice"] = value end def promotion_choice_url=(value) promotion_choice_key['url'] = value end def promotion_choice choice = promotion_choice_key["choice"] choice.empty? ? "none" : choice end def promotes_something? promotion_choice != 'none' end def promotion_choice_url promotion_choice_key["url"] end def promotion_choice_key unless presentation_toggles.key? 'promotion_choice' presentation_toggles['promotion_choice'] = self.class.default_presentation_toggles['promotion_choice'] end presentation_toggles['promotion_choice'] end module ClassMethods def default_presentation_toggles { 'promotion_choice' => { 'choice' => 'none', 'url' => '' } } end end end
Make sure panopticon slug checks don't get stuck because slugs are too long
class PanopticonSlugValidator < ActiveModel::EachValidator def claim_slug(endpoint_url, attributes_to_send) uri = URI.parse(endpoint_url) res = Net::HTTP.post_form(uri, attributes_to_send) case res when Net::HTTPCreated return true when Net::HTTPNotAcceptable return false else Rails.logger.warn "Panopticon communications error: #{res.inspect}" return false end end # implement the method called during validation def validate_each(record, attribute, value) endpoint_url = "#{PANOPTICON_HOST}/slugs" attributes_to_send = { 'slug[kind]' => record.class.to_s, 'slug[owning_app]' => 'publisher', 'slug[name]' => record.send(attribute) } record.errors[attribute] << 'must be unique across Gov.UK' unless claim_slug(endpoint_url, attributes_to_send) rescue Errno::ECONNREFUSED record.errors[attribute] << 'panopticon seems to be unavailable' end end
class PanopticonSlugValidator < ActiveModel::EachValidator def claim_slug(endpoint_url, attributes_to_send) uri = URI.parse(endpoint_url) res = Net::HTTP.post_form(uri, attributes_to_send) case res when Net::HTTPCreated return true when Net::HTTPNotAcceptable return false else Rails.logger.warn "Panopticon communications error: #{res.inspect}" return false end end # implement the method called during validation def validate_each(record, attribute, value) the_slug = record.send(attribute) if the_slug.length < 4 or the_slug.length > 32 record.errors[attribute] << "must be between 4 and 32 characters" return end endpoint_url = "#{PANOPTICON_HOST}/slugs" attributes_to_send = { 'slug[kind]' => record.class.to_s, 'slug[owning_app]' => 'publisher', 'slug[name]' => the_slug } record.errors[attribute] << 'must be unique across Gov.UK' unless claim_slug(endpoint_url, attributes_to_send) rescue Errno::ECONNREFUSED record.errors[attribute] << 'panopticon seems to be unavailable' end end
Update middleware for new middleware API
require 'faraday' # @api private module Faraday class Response::RaiseError < Response::Middleware def self.register_on_complete(env) env[:response].on_complete do |response| case response[:status].to_i when 400 raise Open311::BadRequest, error_message(response) when 401 raise Open311::Unauthorized, error_message(response) when 403 raise Open311::Forbidden, error_message(response) when 404 raise Open311::NotFound, error_message(response) when 406 raise Open311::NotAcceptable, error_message(response) when 500 raise Open311::InternalServerError, error_message(response) when 502 raise Open311::BadGateway, error_message(response) when 503 raise Open311::ServiceUnavailable, error_message(response) end end end def initialize(app) super @parser = nil end private def self.error_message(response) "#{response[:method].to_s.upcase} #{response[:url].to_s}: #{response[:response_headers]['status']}#{(': ' + response[:body]['error']) if response[:body] && response[:body]['error']}" end end end
require 'faraday' # @api private module Faraday class Response::RaiseError < Response::Middleware def on_complete(response) case response[:status].to_i when 400 raise Open311::BadRequest, error_message(response) when 401 raise Open311::Unauthorized, error_message(response) when 403 raise Open311::Forbidden, error_message(response) when 404 raise Open311::NotFound, error_message(response) when 406 raise Open311::NotAcceptable, error_message(response) when 500 raise Open311::InternalServerError, error_message(response) when 502 raise Open311::BadGateway, error_message(response) when 503 raise Open311::ServiceUnavailable, error_message(response) end end def error_message(response) "#{response[:method].to_s.upcase} #{response[:url].to_s}: #{response[:response_headers]['status']}#{(': ' + response[:body]['error']) if response[:body] && response[:body]['error']}" end end end
Delete unnesesarry method and variable
require "rake_shared_context/version" require "rake" begin require "rspec/core" shared_context "rake" do let(:rake) { Rake::Application.new } let(:task_name) { self.class.top_level_description } let(:task_path) { "lib/tasks/#{task_name.split(":").first}" } subject { rake[task_name] } def loaded_files_excluding_current_rake_file $".reject {|file| file == Rails.root.join("#{task_path}.rake").to_s } end before do Rake.application = rake Dir::glob("lib/tasks/*.rake").each do |task| Rake.application.rake_require(task.sub(/.rake$/,''), [Rails.root.to_s], loaded_files_excluding_current_rake_file) end Rake::Task.define_task(:environment) end end rescue LoadError end
require "rake_shared_context/version" require "rake" begin require "rspec/core" shared_context "rake" do let(:rake) { Rake::Application.new } let(:task_name) { self.class.top_level_description } subject { rake[task_name] } before do loaded_files = [] Rake.application = rake Dir::glob("lib/tasks/*.rake").each do |task| Rake.application.rake_require(task.sub(/.rake$/,''), [Rails.root.to_s], loaded_files) end Rake::Task.define_task(:environment) end end rescue LoadError end
Remove headers with a nil value
require 'httparty' require 'diesel/utils/inflections' module Diesel class RequestContext include Diesel::Utils::Inflections attr_reader :options, :group, :endpoint, :attributes def initialize(options, group, endpoint, attributes) @options, @group, @endpoint, @attributes = options, group, endpoint, attributes end def perform url = endpoint.url.dup if url.base_host url.subdomain = options[:subdomain] end env = { method: endpoint.request_method, url: url, params: {}, request_headers: {}, logger: logger, context: self } endpoint.middleware_stack.call(env) perform_request(env) end def authenticator group.authenticator end def logger group.logger end def get_attribute(name) name = name.to_sym unless attributes.has_key?(name) name = underscore(name).to_sym end attributes[name] end protected def perform_request(env) HTTParty.send(env[:method], env[:url].to_s, headers: env[:request_headers], query: env[:params], body: env[:body]) end end end
require 'httparty' require 'diesel/utils/inflections' module Diesel class RequestContext include Diesel::Utils::Inflections attr_reader :options, :group, :endpoint, :attributes def initialize(options, group, endpoint, attributes) @options, @group, @endpoint, @attributes = options, group, endpoint, attributes end def perform url = endpoint.url.dup if url.base_host url.subdomain = options[:subdomain] end env = { method: endpoint.request_method, url: url, params: {}, request_headers: {}, logger: logger, context: self } endpoint.middleware_stack.call(env) perform_request(env) end def authenticator group.authenticator end def logger group.logger end def get_attribute(name) name = name.to_sym unless attributes.has_key?(name) name = underscore(name).to_sym end attributes[name] end protected def perform_request(env) headers = env[:request_headers].reject { |_,v| v.nil? } HTTParty.send(env[:method], env[:url].to_s, headers: headers, query: env[:params], body: env[:body]) end end end