Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add string stripper plugin to sequel models
# frozen_string_literal: true require 'sequel' require 'ditty/services/logger' require 'active_support' require 'active_support/core_ext/object/blank' pool_timeout = (ENV['DB_POOL_TIMEOUT'] || 5).to_i if defined? DB ::Ditty::Services::Logger.warn 'Database connection already set up' elsif ENV['DATABASE_URL'].blank? == false # Delete DATABASE_URL from the environment, so it isn't accidently # passed to subprocesses. DATABASE_URL may contain passwords. DB = Sequel.connect( ENV['RACK_ENV'] == 'production' ? ENV.delete('DATABASE_URL') : ENV['DATABASE_URL'], pool_timeout: pool_timeout ) DB.sql_log_level = (ENV['SEQUEL_LOGGING_LEVEL'] || :debug).to_sym DB.loggers << ::Ditty::Services::Logger if ENV['DB_DEBUG'].to_i == 1 DB.extension(:pagination) DB.extension(:schema_caching) DB.load_schema_cache?('./config/schema.dump') Sequel::Model.plugin :validation_helpers Sequel::Model.plugin :update_or_create Sequel::Model.plugin :timestamps, update_on_create: true Sequel::Model.plugin :auto_validations else ::Ditty::Services::Logger.error 'No database connection set up' end
# frozen_string_literal: true require 'sequel' require 'ditty/services/logger' require 'active_support' require 'active_support/core_ext/object/blank' pool_timeout = (ENV['DB_POOL_TIMEOUT'] || 5).to_i if defined? DB ::Ditty::Services::Logger.warn 'Database connection already set up' elsif ENV['DATABASE_URL'].blank? == false # Delete DATABASE_URL from the environment, so it isn't accidently # passed to subprocesses. DATABASE_URL may contain passwords. DB = Sequel.connect( ENV['RACK_ENV'] == 'production' ? ENV.delete('DATABASE_URL') : ENV['DATABASE_URL'], pool_timeout: pool_timeout ) DB.sql_log_level = (ENV['SEQUEL_LOGGING_LEVEL'] || :debug).to_sym DB.loggers << ::Ditty::Services::Logger if ENV['DB_DEBUG'].to_i == 1 DB.extension(:pagination) DB.extension(:schema_caching) DB.load_schema_cache?('./config/schema.dump') Sequel::Model.plugin :auto_validations Sequel::Model.plugin :string_stripper Sequel::Model.plugin :timestamps, update_on_create: true Sequel::Model.plugin :update_or_create Sequel::Model.plugin :validation_helpers else ::Ditty::Services::Logger.error 'No database connection set up' end
Remove unused method on PopularityScorer
class PopularityScorer # The number of months of activity we will look at for scoring. MONTHS_OF_ACTIVITY = 3 # For scoring, the number of commits we consider extremely busy. MAX_COMMITS = 100 # For scoring, the number of issues opened to consider extremely busy. MAX_ISSUES = 20 # Maximum number of points allowed per scoring facet. POINTS_PER_FACET = 10 def initialize(nickname, token, project) @nickname = nickname @token = token @project = project end def score points = 0 points += recent_activity points += score_recent_issues points end private def recent_activity updated_at = @project.repo(@nickname, @token).updated_at if updated_at updated_at > Time.zone.today - MONTHS_OF_ACTIVITY ? 5 : 0 else 0 end end def score_recent_commits commit_count = @project.commits(@nickname, @token, MONTHS_OF_ACTIVITY).size points_earned_for_facet(commit_count, MAX_COMMITS) end def score_recent_issues issue_count = @project.issues(@nickname, @token, MONTHS_OF_ACTIVITY, per_page: MAX_ISSUES).size points_earned_for_facet(issue_count, MAX_ISSUES) end def points_earned_for_facet(current, maximum) item_count = [current, maximum].min (item_count.to_f / maximum * POINTS_PER_FACET).round end end
class PopularityScorer # The number of months of activity we will look at for scoring. MONTHS_OF_ACTIVITY = 3 # For scoring, the number of commits we consider extremely busy. MAX_COMMITS = 100 # For scoring, the number of issues opened to consider extremely busy. MAX_ISSUES = 20 # Maximum number of points allowed per scoring facet. POINTS_PER_FACET = 10 def initialize(nickname, token, project) @nickname = nickname @token = token @project = project end def score points = 0 points += recent_activity points += score_recent_issues points end private def recent_activity updated_at = @project.repo(@nickname, @token).updated_at if updated_at updated_at > Time.zone.today - MONTHS_OF_ACTIVITY ? 5 : 0 else 0 end end def score_recent_issues issue_count = @project.issues(@nickname, @token, MONTHS_OF_ACTIVITY, per_page: MAX_ISSUES).size points_earned_for_facet(issue_count, MAX_ISSUES) end def points_earned_for_facet(current, maximum) item_count = [current, maximum].min (item_count.to_f / maximum * POINTS_PER_FACET).round end end
Create integration test for method lookups.
require File.expand_path('../gir_ffi_test_helper.rb', File.dirname(__FILE__)) # Tests how methods are looked up and generated on first use. describe "Looking up methods" do before do save_module :Regress GirFFI.setup :Regress end describe "an instance method" do it "is found from a subclass" do defined_in_subclass = Regress::TestSubObj.instance_methods(false).map &:to_s defined_in_subclass.wont_include 'forced_method' sub_object = Regress::TestSubObj.new sub_object.forced_method end end describe "a class method" do it "is found from a subclass" do defined_in_subclass = Regress::TestSubObj.singleton_methods(false).map &:to_s defined_in_subclass.wont_include 'static_method' defined_in_class = Regress::TestObj.singleton_methods(false).map &:to_s defined_in_class.must_include 'static_method' Regress::TestSubObj.static_method 42 end end after do restore_module :Regress end end
Add upsertList action to work orders
module NetSuite module Records class WorkOrder include Support::Fields include Support::RecordRefs include Support::Records include Support::Actions include Namespaces::TranInvt actions :get, :add, :initialize, :delete, :update, :upsert, :search fields :buildable, :built, :created_date, :end_date, :expanded_assembly, :firmed, :is_wip, :last_modified_date, :memo, :order_status, :partners_list, :quantity, :sales_team_list, :source_transaction_id, :source_transaction_line, :special_order, :start_date, :status, :tran_date, :tran_id field :custom_field_list, CustomFieldList field :options, CustomFieldList field :item_list, WorkOrderItemList record_refs :assembly_item, :created_from, :custom_form, :department, :entity, :job, :location, :manufacturing_routing, :revision, :subsidiary, :units attr_reader :internal_id attr_accessor :external_id attr_accessor :search_joins def initialize(attributes = {}) @internal_id = attributes.delete(:internal_id) || attributes.delete(:@internal_id) @external_id = attributes.delete(:external_id) || attributes.delete(:@external_id) initialize_from_attributes_hash(attributes) end end end end
module NetSuite module Records class WorkOrder include Support::Fields include Support::RecordRefs include Support::Records include Support::Actions include Namespaces::TranInvt actions :get, :add, :initialize, :delete, :update, :upsert, :upsert_list, :search fields :buildable, :built, :created_date, :end_date, :expanded_assembly, :firmed, :is_wip, :last_modified_date, :memo, :order_status, :partners_list, :quantity, :sales_team_list, :source_transaction_id, :source_transaction_line, :special_order, :start_date, :status, :tran_date, :tran_id field :custom_field_list, CustomFieldList field :options, CustomFieldList field :item_list, WorkOrderItemList record_refs :assembly_item, :created_from, :custom_form, :department, :entity, :job, :location, :manufacturing_routing, :revision, :subsidiary, :units attr_reader :internal_id attr_accessor :external_id attr_accessor :search_joins def initialize(attributes = {}) @internal_id = attributes.delete(:internal_id) || attributes.delete(:@internal_id) @external_id = attributes.delete(:external_id) || attributes.delete(:@external_id) initialize_from_attributes_hash(attributes) end end end end
Change spec helper to explicit auto-migrate all models in a repository
module DataMapper module Spec module Adapters module Helpers def supported_by(*adapters, &block) adapters = adapters.map { |adapter| adapter.to_sym } adapter = DataMapper::Spec.adapter_name.to_sym if adapters.include?(:all) || adapters.include?(adapter) describe_adapter(:default, &block) end end def with_alternate_adapter(&block) describe_adapter(:alternate, &block) end def describe_adapter(kind, &block) describe("with #{kind} adapter") do before :all do # store these in instance vars for the shared adapter specs @adapter = DataMapper::Spec.adapter(kind) @repository = DataMapper.repository(@adapter.name) @repository.scope { DataMapper.finalize } # create all tables and constraints before each spec if @repository.respond_to?(:auto_migrate!) @repository.auto_migrate! end end after :all do # remove all tables and constraints after each spec if @repository.respond_to?(:auto_migrate_down!, true) @repository.send(:auto_migrate_down!, @repository.name) end # TODO consider proper automigrate functionality if @adapter.respond_to?(:reset) @adapter.reset end end instance_eval(&block) end end end end end end
module DataMapper module Spec module Adapters module Helpers def supported_by(*adapters, &block) adapters = adapters.map { |adapter| adapter.to_sym } adapter = DataMapper::Spec.adapter_name.to_sym if adapters.include?(:all) || adapters.include?(adapter) describe_adapter(:default, &block) end end def with_alternate_adapter(&block) describe_adapter(:alternate, &block) end def describe_adapter(kind, &block) describe("with #{kind} adapter") do before :all do # store these in instance vars for the shared adapter specs @adapter = DataMapper::Spec.adapter(kind) @repository = DataMapper.repository(@adapter.name) @repository.scope { DataMapper.finalize } # create all tables and constraints before each spec DataMapper::Model.descendants.each do |model| next unless model.respond_to?(:auto_migrate!) model.auto_migrate!(@repository.name) end end after :all do # remove all tables and constraints after each spec DataMapper::Model.descendants.each do |model| next unless model.respond_to?(:auto_migrate_down!) model.auto_migrate_down!(@repository.name) end # TODO consider proper automigrate functionality if @adapter.respond_to?(:reset) @adapter.reset end end instance_eval(&block) end end end end end end
Rename "children" in MultiSelectHash to "kv_pairs"
module JMESPath # @api private module Nodes class MultiSelectHash < Node def initialize(children) @children = children end def visit(value) if value.nil? nil else @children.each_with_object({}) do |pair, hash| hash[pair.key] = pair.value.visit(value) end end end def optimize self.class.new(@children.map(&:optimize)) end class KeyValuePair attr_reader :key, :value def initialize(key, value) @key = key @value = value end def optimize self.class.new(@key, @value.optimize) end end end end end
module JMESPath # @api private module Nodes class MultiSelectHash < Node def initialize(kv_pairs) @kv_pairs = kv_pairs end def visit(value) if value.nil? nil else @kv_pairs.each_with_object({}) do |pair, hash| hash[pair.key] = pair.value.visit(value) end end end def optimize self.class.new(@kv_pairs.map(&:optimize)) end class KeyValuePair attr_reader :key, :value def initialize(key, value) @key = key @value = value end def optimize self.class.new(@key, @value.optimize) end end end end end
Make podspec point to commit since we don't have any tags yet.
Pod::Spec.new do |spec| spec.name = 'objc-geohash' spec.version = '0.1' spec.author = { 'Lyo Kato' => 'lyo.kato@gmail.com' } spec.source = { :git => 'https://github.com/lyokato/objc-geohash.git', :tag => spec.version.to_s } spec.source_files = 'Classes/ARC/*' spec.requires_arc = true end
Pod::Spec.new do |spec| spec.name = 'objc-geohash' spec.version = '0.1' spec.author = { 'Lyo Kato' => 'lyo.kato@gmail.com' } spec.source = { :git => 'https://github.com/lyokato/objc-geohash.git', :commit => 'f9be65bcba9b009429a13cae90cff9e10e1e11b7' } spec.source_files = 'Classes/ARC/*' spec.requires_arc = true end
Create unit test to ensure backend parser coverage
require 'test_helper' class TestImageBackend def tested Parsers::ImageBackend.new end def test_vips_formats assert_includes tested.vips_formats, 'vips' end def test_magick_formats assert_includes tested.magick_formats, 'jpeg' end end
Fix initialization issue with access_token
module WeiboOAuth2 module Config def self.api_key=(val) @@api_key = val end def self.api_key @@api_key end def self.api_secret=(val) @@api_secret = val end def self.api_secret @@api_secret end def self.redirect_uri=(val) @@redirect_uri = val end def self.redirect_uri @@redirect_uri end end end
module WeiboOAuth2 module Config def self.api_key=(val) @@api_key = val end def self.api_key @@api_key ||= nil end def self.api_secret=(val) @@api_secret = val end def self.api_secret @@api_secret ||= nil end def self.redirect_uri=(val) @@redirect_uri = val end def self.redirect_uri @@redirect_uri ||= nil end end end
Set dependency versions for gems
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'vagrant-powder/version' Gem::Specification.new do |spec| spec.name = "vagrant-powder" spec.version = VagrantPlugins::Powder::VERSION spec.authors = ["Joe Kratzat"] spec.email = ["joe.kratzat@gmail.com"] spec.summary = %q{Allows vagrant to handle the powder gem} spec.description = %q{Makes sure that pow isn't running when you vagrant up} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake" spec.add_runtime_dependency "powder" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'vagrant-powder/version' Gem::Specification.new do |spec| spec.name = "vagrant-powder" spec.version = VagrantPlugins::Powder::VERSION spec.authors = ["Joe Kratzat"] spec.email = ["joe.kratzat@gmail.com"] spec.summary = %q{Allows vagrant to handle the powder gem} spec.description = %q{Makes sure that pow isn't running when you vagrant up} spec.homepage = "https://github.com/joekr/vagrant-powder" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake", '~> 10.1', '>= 10.1.1' spec.add_runtime_dependency "powder", '~> 0.2', '>= 0.2.1' end
Add support for excluding paths from rake task
require 'puppet-parse' require 'rake' require 'rake/tasklib' desc 'Run puppet-parse' task :parse do matched_files = FileList['**/*.pp'] run = PuppetParse::Runner.new puts run.run(matched_files.to_a).to_yaml end
require 'puppet-parse' require 'rake' require 'rake/tasklib' desc 'Run puppet-parse' task :parse do matched_files = FileList['**/*.pp'] if ignore_paths = PuppetParse.configuration.ignore_paths matched_files = matched_files.exclude(*ignore_paths) end run = PuppetParse::Runner.new puts run.run(matched_files.to_a).to_yaml end
Remove convert_paths_to_urls as its in Govspeak now
require "govspeak/link_extractor" class EditionLinkExtractor def initialize(edition:) @edition = edition end def call convert_paths_to_urls(find_links_in_edition) end private attr_reader :edition def convert_paths_to_urls(links) links.map { |link| link.starts_with?('/') ? "#{public_root}#{link}" : link } end def public_root @public_root ||= Plek.new.website_root end def find_links_in_edition if has_parts? links_in_govspeak_fields + links_in_parts else links_in_govspeak_fields end end def has_parts? edition.parts.any? rescue NoMethodError false end def links_in_govspeak_fields edition.class::GOVSPEAK_FIELDS.flat_map do |govspeak_field_name| govspeak_body = edition.read_attribute(govspeak_field_name) govspeak_document(govspeak_body).extracted_links end end def links_in_parts edition.parts.flat_map do |part| govspeak_document(part.body).extracted_links end end def govspeak_document(string) Govspeak::Document.new(string) end end
require "govspeak/link_extractor" class EditionLinkExtractor def initialize(edition:) @edition = edition end def call find_links_in_edition end private attr_reader :edition def website_root @website_root ||= Plek.new.website_root end def find_links_in_edition if has_parts? links_in_govspeak_fields + links_in_parts else links_in_govspeak_fields end end def has_parts? edition.parts.any? rescue NoMethodError false end def links_in_govspeak_fields edition.class::GOVSPEAK_FIELDS.flat_map do |govspeak_field_name| govspeak_body = edition.read_attribute(govspeak_field_name) extract_links_from_document(govspeak_body) end end def links_in_parts edition.parts.flat_map do |part| extract_links_from_document(part.body) end end def extract_links_from_document(body) govspeak_document(body).extracted_links(website_root: website_root) end def govspeak_document(string) Govspeak::Document.new(string) end end
Set location for UK tile cache
name "jump" description "Role applied to all servers at Jump Networks" default_attributes( :networking => { :nameservers => [ "185.73.44.3", "2001:ba8:0:2c02::", "2001:ba8:0:2c03::", "2001:ba8:0:2c04::" ], :roles => { :external => { :zone => "jn" } } } ) override_attributes( :ntp => { :servers => ["0.uk.pool.ntp.org", "1.uk.pool.ntp.org", "europe.pool.ntp.org"] } ) run_list( "role[gb]" )
name "jump" description "Role applied to all servers at Jump Networks" default_attributes( :location => "London, England", :networking => { :nameservers => [ "185.73.44.3", "2001:ba8:0:2c02::", "2001:ba8:0:2c03::", "2001:ba8:0:2c04::" ], :roles => { :external => { :zone => "jn" } } } ) override_attributes( :ntp => { :servers => ["0.uk.pool.ntp.org", "1.uk.pool.ntp.org", "europe.pool.ntp.org"] } ) run_list( "role[gb]" )
Remove unnecessary flash messages about logging in and out
module Casein class UserSessionsController < Casein::CaseinController unloadable skip_before_filter :authorise, :only => [:new, :create] before_filter :requires_no_session_user, :except => [:destroy] layout 'casein_auth' def new @user_session = Casein::UserSession.new end def create @user_session = Casein::UserSession.new params[:casein_user_session] if @user_session.save flash[:notice] = "Login successful" redirect_back_or_default :controller => :casein, :action => :index else render :action => :new end end def destroy current_user_session.destroy flash[:notice] = "Logout successful" redirect_back_or_default new_casein_user_session_url end private def requires_no_session_user if current_user redirect_to :controller => :casein, :action => :index end end end end
module Casein class UserSessionsController < Casein::CaseinController unloadable skip_before_filter :authorise, :only => [:new, :create] before_filter :requires_no_session_user, :except => [:destroy] layout 'casein_auth' def new @user_session = Casein::UserSession.new end def create @user_session = Casein::UserSession.new params[:casein_user_session] if @user_session.save redirect_back_or_default :controller => :casein, :action => :index else render :action => :new end end def destroy current_user_session.destroy redirect_back_or_default new_casein_user_session_url end private def requires_no_session_user if current_user redirect_to :controller => :casein, :action => :index end end end end
Modify migration to make sure it doesn't run if column exists.
class AddToiletToPois < ActiveRecord::Migration def change add_column :pois, :toilet, :boolean add_index :pois, [ :toilet, :status ] end end
class AddToiletToPois < ActiveRecord::Migration def up add_column(:pois, :toilet, :boolean) unless column_exists?(:pois, :toilet) add_index(:pois, [ :toilet, :status ]) unless index_exists?(:pois, [ :toilet, :status ]) end def down remove_index(:pois, [ :toilet, :status ]) if index_exists?(:pois, [ :toilet, :status ]) remove_column(:pois, :toilet) if column_exists?(:pois, :toilet) end end # This is an alternative way, which can be used to add this column using a temporary table #columns = Poi.column_names #ActiveRecord::Base.connection.execute "CREATE TABLE new_pois LIKE pois" #ActiveRecord::Base.connection.execute "ALTER TABLE new_pois ADD toilet TINYINT(1) DEFAULT NULL" #ActiveRecord::Base.connection.execute "INSERT INTO new_pois (#{columns.join(', ')}) SELECT #{columns.join(', ')} FROM pois" #ActiveRecord::Base.connection.execute "CREATE INDEX index_pois_on_toilet_and_status ON new_pois(toilet,status)" #ActiveRecord::Base.connection.execute "RENAME TABLE pois TO old_pois, new_pois TO pois" #ActiveRecord::Base.connection.execute "DROP TABLE old_pois"
Write an rspec table matcher that gives informative error messages
RSpec::Matchers.define :have_table_row do |row| match_for_should do |node| @row = row node.has_selector? "tr", text: row.join(" ").strip # Check for appearance rows_under(node).include? row # Robust check of columns end match_for_should_not do |node| @row = row node.has_no_selector? "tr", text: row.join(" ").strip # Check for appearance !rows_under(node).include? row # Robust check of columns end failure_message_for_should do |text| "expected to find table row #{@row}" end failure_message_for_should_not do |text| "expected not to find table row #{@row}" end def rows_under(node) node.all('tr').map { |tr| tr.all('th, td').map(&:text) } end end
RSpec::Matchers.define :have_table_row do |row| match_for_should do |node| @row = row node.has_selector? "tr", text: row.join(" ").strip # Check for appearance rows_under(node).include? row # Robust check of columns end match_for_should_not do |node| @row = row node.has_no_selector? "tr", text: row.join(" ").strip # Check for appearance !rows_under(node).include? row # Robust check of columns end failure_message_for_should do |text| "expected to find table row #{@row}" end failure_message_for_should_not do |text| "expected not to find table row #{@row}" end def rows_under(node) node.all('tr').map { |tr| tr.all('th, td').map(&:text) } end end # find("#my-table").should match_table [[...]] RSpec::Matchers.define :match_table do |expected_table| match_for_should do |node| rows = node. all("tr"). map { |r| r.all("th,td").map { |c| c.text.strip } } if rows.count != expected_table.count @failure_message = "found table with #{rows.count} rows, expected #{expected_table.count}" else rows.each_with_index do |row, i| expected_row = expected_table[i] if row.count != expected_row.count @failure_message = "row #{i} has #{row.count} columns, expected #{expected_row.count}" break elsif row != expected_row row.each_with_index do |cell, j| if cell != expected_row[j] @failure_message = "cell [#{i}, #{j}] has content '#{cell}', expected '#{expected_row[j]}'" break end end break if @failure_message end end end @failure_message.nil? end failure_message_for_should do |text| @failure_message end end
Swap unless ... .nil? to if ...
module Refinery class Plugins < Array def find_activity_by_model(model) unless (plugin = find_by_model(model)).nil? plugin.activity.detect {|activity| activity.class == model} end end def find_by_model(model) model = model.constantize if model.is_a? String detect { |plugin| plugin.activity.any? {|activity| activity.class == model } } end def find_by_name(name) detect { |plugin| plugin.name == name } end alias :[] :find_by_name def find_by_title(title) detect { |plugin| plugin.title == title } end def in_menu self.class.new(reject(&:hide_from_menu)) end def names map(&:name) end def pathnames map(&:pathname).compact.uniq end def titles map(&:title) end class << self def active @active_plugins ||= new end def always_allowed new(registered.reject { |p| !p.always_allow_access? }) end def registered @registered_plugins ||= new end def activate(name) active << registered[name] if registered[name] && !active[name] end def deactivate(name) active.delete_if {|p| p.name == name} end def set_active(names) @active_plugins = new names.each do |name| activate(name) end end end end end
module Refinery class Plugins < Array def find_activity_by_model(model) if (plugin = find_by_model(model)) plugin.activity.detect {|activity| activity.class == model} end end def find_by_model(model) model = model.constantize if model.is_a? String detect { |plugin| plugin.activity.any? {|activity| activity.class == model } } end def find_by_name(name) detect { |plugin| plugin.name == name } end alias :[] :find_by_name def find_by_title(title) detect { |plugin| plugin.title == title } end def in_menu self.class.new(reject(&:hide_from_menu)) end def names map(&:name) end def pathnames map(&:pathname).compact.uniq end def titles map(&:title) end class << self def active @active_plugins ||= new end def always_allowed new(registered.reject { |p| !p.always_allow_access? }) end def registered @registered_plugins ||= new end def activate(name) active << registered[name] if registered[name] && !active[name] end def deactivate(name) active.delete_if {|p| p.name == name} end def set_active(names) @active_plugins = new names.each do |name| activate(name) end end end end end
Complete test gem is correctly desvribe
# frozen_string_literal: true require 'spec_helper' describe 'RubyRabbitmqJanus::RRJ', type: :config do it 'Has a version number' do expect(RubyRabbitmqJanus::VERSION).not_to be nil end it 'Has a description' do expect(RubyRabbitmqJanus::DESCRIPTION).not_to be nil end it 'Has a summary description' do expect(RubyRabbitmqJanus::SUMMARY).not_to be nil end end
# frozen_string_literal: true require 'spec_helper' describe 'RubyRabbitmqJanus::RRJ', type: :config do it 'Has a version number' do expect(RubyRabbitmqJanus::VERSION).not_to be nil end it 'Has a description' do expect(RubyRabbitmqJanus::DESCRIPTION).not_to be nil end it 'Has a summary description' do expect(RubyRabbitmqJanus::SUMMARY).not_to be nil end it 'Has a homepage' do expect(RubyRabbitmqJanus::HOMEPAGE).not_to be nil end it 'Has a post install message' do expect(RubyRabbitmqJanus::POST_INSTALL).not_to be nil end end
Add a development dependency gem
require File.expand_path('../lib/rack/revision/version', __FILE__) Gem::Specification.new do |s| s.name = "rack-revision" s.version = Rack::Revision::VERSION s.summary = "Code ravision rack middleware" s.description = "Adds an extra X-REVISION header with source code revision string (git, svn, etc)" s.homepage = "http://github.com/sosedoff/rack-revision" s.authors = ["Dan Sosedoff"] s.email = ["dan.sosedoff@gmail.com"] s.add_runtime_dependency 'rack', '>= 1.0' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)} s.require_paths = ["lib"] end
require File.expand_path('../lib/rack/revision/version', __FILE__) Gem::Specification.new do |s| s.name = "rack-revision" s.version = Rack::Revision::VERSION s.summary = "Code ravision rack middleware" s.description = "Adds an extra X-REVISION header with source code revision string (git, svn, etc)" s.homepage = "http://github.com/sosedoff/rack-revision" s.authors = ["Dan Sosedoff"] s.email = ["dan.sosedoff@gmail.com"] s.add_runtime_dependency 'rack', '>= 1.0' s.add_development_dependency 'rack-test', '>= 0' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)} s.require_paths = ["lib"] end
Add interface to IAM service
require 'aws-sdk' require 'contracts' require_relative 'service' module StackatoLKG module Amazon class IAM < Service Contract None => ::Aws::IAM::Types::User def user @user ||= call_api(:get_user).user end private def client Aws::IAM::Client end end end end
Add option to remove the last update time of whois DB
require 'rack/ssl-enforcer' require 'simpleidn' require 'sinatra' require 'slim' require 'whois' require_relative 'helpers' helpers { prepend Helpers } configure :production do use Rack::SslEnforcer if ENV['ENFORCE_HTTPS'] end get '/' do slim :index end get '/lookup' do redirect to "/#{URI.escape(params['domain'])}" end get '/*' do |domain| redirect to(domain.gsub(%r[/.*], '')) if domain.include?('/') result = lookup(domain) slim :result, locals: { result: result, domain: domain } end
require 'rack/ssl-enforcer' require 'simpleidn' require 'sinatra' require 'slim' require 'whois' require_relative 'helpers' helpers { prepend Helpers } configure :production do use Rack::SslEnforcer if ENV['ENFORCE_HTTPS'] end get '/' do slim :index end get '/lookup' do redirect to "/#{URI.escape(params['domain'])}" end get '/*' do |domain| redirect to(domain.gsub(%r[/.*], '')) if domain.include?('/') result = lookup(domain).to_s result.gsub!(/>>>[^<]+<<</, '') if params[:body_only] slim :result, locals: { result: result, domain: domain } end
Use the version constant rather than rubygems to get the version.
module Qless class Lua LUA_SCRIPT_DIR = File.expand_path("../qless-core/", __FILE__) # the #evalsha method signature changed between v2.x and v3.x of the redis ruby gem # to maintain backwards compatibility with v2.x of that gem we need this constant USE_LEGACY_EVALSHA = Gem.loaded_specs['redis'].version < Gem::Version.create('3.0.0') def initialize(name, redis) @sha = nil @name = name @redis = redis reload() end def reload() @sha = @redis.script(:load, File.read(File.join(LUA_SCRIPT_DIR, "#{@name}.lua"))) end def call(keys, argv) begin return @redis.evalsha(@sha, keys.length, *(keys + argv)) if USE_LEGACY_EVALSHA return @redis.evalsha(@sha, keys: keys, argv: argv) rescue reload return @redis.evalsha(@sha, keys.length, *(keys + argv)) if USE_LEGACY_EVALSHA return @redis.evalsha(@sha, keys: keys, argv: argv) end end end end
module Qless class Lua LUA_SCRIPT_DIR = File.expand_path("../qless-core/", __FILE__) # the #evalsha method signature changed between v2.x and v3.x of the redis ruby gem # to maintain backwards compatibility with v2.x of that gem we need this constant USE_LEGACY_EVALSHA = ::Redis::VERSION.to_f < 3.0 def initialize(name, redis) @sha = nil @name = name @redis = redis reload() end def reload() @sha = @redis.script(:load, File.read(File.join(LUA_SCRIPT_DIR, "#{@name}.lua"))) end def call(keys, argv) begin return @redis.evalsha(@sha, keys.length, *(keys + argv)) if USE_LEGACY_EVALSHA return @redis.evalsha(@sha, keys: keys, argv: argv) rescue reload return @redis.evalsha(@sha, keys.length, *(keys + argv)) if USE_LEGACY_EVALSHA return @redis.evalsha(@sha, keys: keys, argv: argv) end end end end
Add test for missing layout
# encoding: UTF-8 # Generators register themself on the CLI module require "test_helper" require "./lib/roger/renderer.rb" module Roger # Roger template tests class RendererBaseTest < ::Test::Unit::TestCase def setup @base = Pathname.new(File.dirname(__FILE__) + "/../../project") @config = { partials_path: @base + "partials", layouts_path: @base + "layouts", source_path: @base + "html/test.html.erb" } @template_path = @base + "html" @renderer = Renderer.new({}, @config) end def test_basic_layout template = "---\nlayout: \"yield\"\n---\nTEMPLATE" assert_equal "TEMPLATE", render_erb_template(template) end def test_layout_with_partial template = "---\nlayout: \"partial\"\n---\nTEMPLATE" assert_equal "TEMPLATEERB", render_erb_template(template) end def test_layout_with_block_partial template = "---\nlayout: \"partial_with_block\"\n---\nTEMPLATE" assert_equal "TEMPLATEB-PARTIAL-A", render_erb_template(template) end def render_erb_template(template) @renderer.render(@base + "html/layouts/test.html.erb", source: template) end end end
# encoding: UTF-8 # Generators register themself on the CLI module require "test_helper" require "./lib/roger/renderer.rb" module Roger # Roger template tests class RendererBaseTest < ::Test::Unit::TestCase def setup @base = Pathname.new(File.dirname(__FILE__) + "/../../project") @config = { partials_path: @base + "partials", layouts_path: @base + "layouts", source_path: @base + "html/test.html.erb" } @template_path = @base + "html" @renderer = Renderer.new({}, @config) end def test_basic_layout template = "---\nlayout: \"yield\"\n---\nTEMPLATE" assert_equal "TEMPLATE", render_erb_template(template) end def test_layout_with_partial template = "---\nlayout: \"partial\"\n---\nTEMPLATE" assert_equal "TEMPLATEERB", render_erb_template(template) end def test_layout_with_block_partial template = "---\nlayout: \"partial_with_block\"\n---\nTEMPLATE" assert_equal "TEMPLATEB-PARTIAL-A", render_erb_template(template) end def test_missing_layout template = "---\nlayout: \"not-there\"\n---\nTEMPLATE" assert_raise ArgumentError do render_erb_template(template) end end def render_erb_template(template) @renderer.render(@base + "html/layouts/test.html.erb", source: template) end end end
Remove circular require in spec support file
require 'spec_helper' class Model include ActiveModel::Validations attr_accessor :attributes def initialize(attributes = {}) @attributes = attributes end def read_attribute_for_validation(key) @attributes[key] end def email @attributes[:email] end def email=(email) @attributes[:email] = email end end class Person < Model validates :email, email: true end
class Model include ActiveModel::Validations attr_accessor :attributes def initialize(attributes = {}) @attributes = attributes end def read_attribute_for_validation(key) @attributes[key] end def email @attributes[:email] end def email=(email) @attributes[:email] = email end end class Person < Model validates :email, email: true end
Fix issue where passing no options gives a NilError
require 'openssl' module AnsibleTowerClient class Connection attr_reader :connection def initialize(options = nil) raise "Credentials are required" unless options[:username] && options[:password] raise ":base_url is required" unless options[:base_url] logger = options[:logger] || AnsibleTowerClient.logger verify_ssl = options[:verify_ssl] || OpenSSL::SSL::VERIFY_PEER verify_ssl = verify_ssl == OpenSSL::SSL::VERIFY_NONE ? false : true require 'faraday' require 'faraday_middleware' require 'ansible_tower_client/middleware/raise_tower_error' Faraday::Response.register_middleware :raise_tower_error => -> { Middleware::RaiseTowerError } @connection = Faraday.new(options[:base_url], :ssl => {:verify => verify_ssl}) do |f| f.use(FaradayMiddleware::EncodeJson) f.use(FaradayMiddleware::FollowRedirects, :limit => 3, :standards_compliant => true) f.request(:url_encoded) f.response(:raise_tower_error) f.response(:logger, logger) f.adapter(Faraday.default_adapter) f.basic_auth(options[:username], options[:password]) end end def api @api ||= Api.new(connection) end end end
require 'openssl' module AnsibleTowerClient class Connection attr_reader :connection def initialize(options = nil) raise ":username and :password are required" if options.nil? || !options[:username] || !options[:password] raise ":base_url is required" unless options[:base_url] logger = options[:logger] || AnsibleTowerClient.logger verify_ssl = options[:verify_ssl] || OpenSSL::SSL::VERIFY_PEER verify_ssl = verify_ssl == OpenSSL::SSL::VERIFY_NONE ? false : true require 'faraday' require 'faraday_middleware' require 'ansible_tower_client/middleware/raise_tower_error' Faraday::Response.register_middleware :raise_tower_error => -> { Middleware::RaiseTowerError } @connection = Faraday.new(options[:base_url], :ssl => {:verify => verify_ssl}) do |f| f.use(FaradayMiddleware::EncodeJson) f.use(FaradayMiddleware::FollowRedirects, :limit => 3, :standards_compliant => true) f.request(:url_encoded) f.response(:raise_tower_error) f.response(:logger, logger) f.adapter(Faraday.default_adapter) f.basic_auth(options[:username], options[:password]) end end def api @api ||= Api.new(connection) end end end
Fix headers how the app expects
require "bundler/setup" ENV["RACK_ENV"] ||= "development" Bundler.require(:default, ENV["RACK_ENV"].to_sym) Dotenv.load require "./hook_delivery" configure do MongoMapper.setup({'production' => {'uri' => ENV['MONGOHQ_URL']}}, 'production') end post "/" do headers = { "X-GitHub-Event" => env["X-GitHub-Event"], "X-GitHub-Delivery" => env["X-GitHub-Delivery"], "X-Hub-Signature" => env["X-Hub-Signature"] }.to_json payload = request.body.read HookDelivery.create( :payload => payload, :headers => headers ) status 200 end get "/" do @hook_deliveries = HookDelivery.all erb :index end delete "/" do HookDelivery.destroy_all status 200 end #### # Simple presentation helper #### helpers do def seconds_ago(number) if number == 1 "#{number} second ago" else "#{number} seconds ago" end end end
require "bundler/setup" ENV["RACK_ENV"] ||= "development" Bundler.require(:default, ENV["RACK_ENV"].to_sym) Dotenv.load require "./hook_delivery" configure do MongoMapper.setup({'production' => {'uri' => ENV['MONGOHQ_URL']}}, 'production') end post "/" do headers = { "X-GitHub-Event" => request["HTTP_X_GITHUB_EVENT"], "X-GitHub-Delivery" => request["HTTP_X_GITHUB_DELIVERY"], "X-Hub-Signature" => request["HTTP_X_HUB_SIGNATURE"] }.to_json payload = request.body.read HookDelivery.create( :payload => payload, :headers => headers ) status 200 end get "/" do @hook_deliveries = HookDelivery.all erb :index end delete "/" do HookDelivery.destroy_all status 200 end #### # Simple presentation helper #### helpers do def seconds_ago(number) if number == 1 "#{number} second ago" else "#{number} seconds ago" end end end
Include linter name in XMLReporter
module SCSSLint # Reports lints in an XML format. class Reporter::XMLReporter < Reporter def report_lints output = '<?xml version="1.0" encoding="utf-8"?>' output << '<lint>' lints.group_by(&:filename).each do |filename, file_lints| output << "<file name=#{filename.encode(xml: :attr)}>" file_lints.each do |lint| output << "<issue line=\"#{lint.location.line}\" " \ "column=\"#{lint.location.column}\" " \ "length=\"#{lint.location.length}\" " \ "severity=\"#{lint.severity}\" " \ "reason=#{lint.description.encode(xml: :attr)} />" end output << '</file>' end output << '</lint>' output end end end
module SCSSLint # Reports lints in an XML format. class Reporter::XMLReporter < Reporter def report_lints output = '<?xml version="1.0" encoding="utf-8"?>' output << '<lint>' lints.group_by(&:filename).each do |filename, file_lints| output << "<file name=#{filename.encode(xml: :attr)}>" file_lints.each do |lint| output << "<issue linter=\"#{lint.linter.name if lint.linter}\" " \ "line=\"#{lint.location.line}\" " \ "column=\"#{lint.location.column}\" " \ "length=\"#{lint.location.length}\" " \ "severity=\"#{lint.severity}\" " \ "reason=#{lint.description.encode(xml: :attr)} />" end output << '</file>' end output << '</lint>' output end end end
Extend needs CSV export to include format
require 'csv_renderer' require 'csv' class NeedsCsv < CsvRenderer def to_csv CSV.generate do |csv| csv << ["Id", "Title", "Context", "Tags", "Status", "Audiences", "Updated at", "Statutory", "Search rank", "Pairwise rank", "Traffic", "Usage volume", "Interaction", "Related needs"] @data.each do |need| csv << [need.id, need.title, need.description, need.tag_list, need.status, need.audiences.collect { |a| a.name }.join(", "), need.updated_at.to_formatted_s(:db), need.statutory, need.search_rank, need.pairwise_rank, need.traffic, need.usage_volume, need.interaction, need.related_needs] end end end def csv_filename(params) "needs-#{params['in_state']}-#{@timestamp.to_formatted_s(:filename_timestamp)}.csv" end end
require 'csv_renderer' require 'csv' class NeedsCsv < CsvRenderer def to_csv CSV.generate do |csv| csv << ["Id", "Title", "Context", "Tags", "Status", "Audiences", "Updated at", "Statutory", "Search rank", "Pairwise rank", "Traffic", "Usage volume", "Interaction", "Related needs", "Format"] @data.each do |need| csv << [need.id, need.title, need.description, need.tag_list, need.status, need.audiences.collect { |a| a.name }.join(", "), need.updated_at.to_formatted_s(:db), need.statutory, need.search_rank, need.pairwise_rank, need.traffic, need.usage_volume, need.interaction, need.related_needs, need.kind.to_s] end end end def csv_filename(params) "needs-#{params['in_state']}-#{@timestamp.to_formatted_s(:filename_timestamp)}.csv" end end
Use to_s on message in the Util.raise_error! method.
class RabbitMQ::FFI::Error < RuntimeError; end module RabbitMQ::Util class << self def raise_error! message="unspecified error", action=nil message = "while #{action} - #{message}" if action raise RabbitMQ::FFI::Error, message end def error_check rc, action=nil return if rc == 0 raise_error! RabbitMQ::FFI.amqp_error_string2(rc), action end def null_check obj, action=nil return unless obj.nil? raise_error! "got unexpected null", action end def mem_ptr size, count: 1, clear: true, release: true ptr = ::FFI::MemoryPointer.new(size, count, clear) ptr.autorelease = false unless release ptr end def arg_ptr type, **kwargs type = ::FFI::TypeDefs[type] if type.is_a?(Symbol) mem_ptr(type.size, clear: false, **kwargs) end def strdup_ptr str, **kwargs str = str + "\x00" ptr = mem_ptr(str.bytesize, **kwargs) ptr.write_string(str) ptr end end end
class RabbitMQ::FFI::Error < RuntimeError; end module RabbitMQ::Util class << self def raise_error! message="unspecified error", action=nil message = "while #{action} - #{message}" if action raise RabbitMQ::FFI::Error, message.to_s end def error_check rc, action=nil return if rc == 0 raise_error! RabbitMQ::FFI.amqp_error_string2(rc), action end def null_check obj, action=nil return unless obj.nil? raise_error! "got unexpected null", action end def mem_ptr size, count: 1, clear: true, release: true ptr = ::FFI::MemoryPointer.new(size, count, clear) ptr.autorelease = false unless release ptr end def arg_ptr type, **kwargs type = ::FFI::TypeDefs[type] if type.is_a?(Symbol) mem_ptr(type.size, clear: false, **kwargs) end def strdup_ptr str, **kwargs str = str + "\x00" ptr = mem_ptr(str.bytesize, **kwargs) ptr.write_string(str) ptr end end end
Make leave_group method work for realz
module Groupable #:nodoc: def self.included(base) base.extend ClassMethods end module ClassMethods def acts_as_groupable has_and_belongs_to_many :groups include Groupable::InstanceMethods end end module InstanceMethods def join_group(group) groups << group end def leave_group(group) groups.find(group).destroy end end end ActiveRecord::Base.send(:include, Groupable)
module Groupable #:nodoc: def self.included(base) base.extend ClassMethods end module ClassMethods def acts_as_groupable has_and_belongs_to_many :groups include Groupable::InstanceMethods end end module InstanceMethods def join_group(group) groups << group end def leave_group(group) ActiveRecord::Base.connection.execute("delete from groups_users where group_id = #{group.id} and user_id = #{id}") end end end ActiveRecord::Base.send(:include, Groupable)
Add test to see blending in Canvas
require 'ruby2d' set width: 800 set height: 600 Square.new(size: 500, color: 'red') # Canvas options: # x, y, z, width, height, rotate, fill, color, update # If `update: false` is set, `canvas.update` must be manually called to update the rendered texture canvas = Canvas.new(x: 50, y: 50, width: Window.width - 100, height: Window.height - 100, fill: [1, 1, 1, 0.5], update: false) (1..10).each do |ix| canvas.fill_rectangle( x: 10 + ix * 30, y: 10 + ix * 30, width: 100, height: 100, color: Color.new([0, 1, 0, 0.5]) ) end # # Currently fat lines don't blend so we don't get the # same effect ... yet. (1..3).each do |ix| canvas.draw_line( x1: 10, y1: 75 + (ix * 15), x2: 310, y2: 420 + (ix * 15), width: 30, color: Color.new([0.5 + (ix * 0.1), 0.5 + (ix * 0.1), 1, 0.5]) ) end update do canvas.update end on :key_down do |event| close if event.key == 'escape' canvas.update end show
Fix file permissions; Version bump to 0.5.1
require 'guard' require 'guard/guard' require 'guard/watcher' module Guard class Shell < Guard VERSION = '0.5.0' # Calls #run_all if the :all_on_start option is present. def start run_all if options[:all_on_start] end # Call #run_on_change for all files which match this guard. def run_all run_on_changes(Watcher.match_files(self, Dir.glob('{,**/}*{,.*}').uniq)) end # Print the result of the command(s), if there are results to be printed. def run_on_changes(res) puts res if res end end class Dsl # Easy method to display a notification def n(msg, title='', image=nil) Notifier.notify(msg, :title => title, :image => image) end end end
require 'guard' require 'guard/guard' require 'guard/watcher' module Guard class Shell < Guard VERSION = '0.5.1' # Calls #run_all if the :all_on_start option is present. def start run_all if options[:all_on_start] end # Call #run_on_change for all files which match this guard. def run_all run_on_changes(Watcher.match_files(self, Dir.glob('{,**/}*{,.*}').uniq)) end # Print the result of the command(s), if there are results to be printed. def run_on_changes(res) puts res if res end end class Dsl # Easy method to display a notification def n(msg, title='', image=nil) Notifier.notify(msg, :title => title, :image => image) end end end
Fix typo reported by @LtCmdDudefellah
require 'socket' require 'debugger' module SpinalTap class Server def initialize(params = {}) @host = params[:host] || '127.0.0.1' @port = params[:port] || 9000 @run = false @workers = {} @workers_lock = Mutex.new end def start return false if @running @running = true @listener_thread = Thread.new do @server_sock = TCPServer.new(@host, @port) while true Thread.new(@server_sock.accept) do |client| begin register(Thread.current, client) client.extend(SpinalTap::ClientHelpers) client.setup(self) client.process_loop rescue Exception => e puts("WORKER DIED: #{e.message}\n#{e.backtrace.join("\n")}") end end end end true end def stop return false unless @running Thread.kill(@listener_thread) @server_sock.close true end def workers @workers_lock.synchronize do return @workers.clone end end def register(thread, client) @workers_lock.synchronize do @workers[thread] = client end end def unregister(thread) @workers_lock.synchronize do @workers.delete(thread) end end end end
require 'socket' require 'debugger' module SpinalTap class Server def initialize(params = {}) @host = params[:host] || '127.0.0.1' @port = params[:port] || 9000 @running = false @workers = {} @workers_lock = Mutex.new end def start return false if @running @running = true @listener_thread = Thread.new do @server_sock = TCPServer.new(@host, @port) while true Thread.new(@server_sock.accept) do |client| begin register(Thread.current, client) client.extend(SpinalTap::ClientHelpers) client.setup(self) client.process_loop rescue Exception => e puts("WORKER DIED: #{e.message}\n#{e.backtrace.join("\n")}") end end end end true end def stop return false unless @running Thread.kill(@listener_thread) @server_sock.close true end def workers @workers_lock.synchronize do return @workers.clone end end def register(thread, client) @workers_lock.synchronize do @workers[thread] = client end end def unregister(thread) @workers_lock.synchronize do @workers.delete(thread) end end end end
Make sure Sequel query is executed in spec
require 'spec_helper' describe "Sequel integration", if: sequel_present? do let(:db) { Sequel.sqlite } before do start_agent end context "with Sequel" do before { Appsignal::Transaction.create('uuid', Appsignal::Transaction::HTTP_REQUEST, 'test') } it "should instrument queries" do expect( Appsignal::Transaction.current ).to receive(:start_event) .at_least(:once) expect( Appsignal::Transaction.current ).to receive(:finish_event) .at_least(:once) .with("sql.sequel", nil, kind_of(String), 1) db['SELECT 1'].all end end end
require 'spec_helper' describe "Sequel integration", if: sequel_present? do let(:db) { Sequel.sqlite } before do start_agent end context "with Sequel" do before { Appsignal::Transaction.create('uuid', Appsignal::Transaction::HTTP_REQUEST, 'test') } it "should instrument queries" do expect( Appsignal::Transaction.current ).to receive(:start_event) .at_least(:once) expect( Appsignal::Transaction.current ).to receive(:finish_event) .at_least(:once) .with("sql.sequel", nil, kind_of(String), 1) db['SELECT 1'].all.to_a end end end
Add benchmark for proc vs call.
require 'benchmark' class ProcVsCall def initialize(&proc) @the_proc = proc end def the_proc @the_proc ||= Proc.new{ |*x| x } end def call(*x) @the_proc ? @the_proc.call(*x) : x end end c = ProcVsCall.new n = 50000 Benchmark.bmbm do |x| x.report('proc') { n.times { c.the_proc[:foo] } } x.report('call') { n.times { c.call(:foo) } } end c = ProcVsCall.new{ |x| x.class } Benchmark.bmbm do |x| x.report('proc') { n.times{ c.the_proc[:foo] } } x.report('call') { n.times{ c.call(:foo) } } end # The results would indicate that it is better to define a default proc rather then # using a call to check if it exists.
Fix bug in parent registration spec
module Features module ApplicationHelpers def log_in_as_student(student = nil) if student.nil? student = create(:student) student.user.update(phone_verified: true, email_verified: true) end visit login_path fill_in 'Username', with: student.username fill_in 'Password', with: student.user.password click_button 'Log in' sleep(1) end def register_as_student(student = nil) student = create(:student) if student.nil? visit register_path fill_in "Username", with: student.username fill_in "Email", with: student.user.email fill_in "Phone", with: student.user.phone select student.school.name, from: "student_school_id" fill_in "Password", with: student.user.password fill_in "Password confirmation", with: student.user.password_confirmation click_button "Submit" end def register_as_parent(parent = nil) parent = create(:parent) if parent.nil? visit register_path click_link "Parent" fill_in "Email", with: parent.user.email fill_in "Phone", with: parent.user.phone fill_in "Password", with: parent.user.password fill_in "Password confirmation", with: parent.user.password_confirmation click_button "Submit" end end end
module Features module ApplicationHelpers def log_in_as_student(student = nil) if student.nil? student = create(:student) student.user.update(phone_verified: true, email_verified: true) end visit login_path fill_in 'Username', with: student.username fill_in 'Password', with: student.user.password click_button 'Log in' sleep(1) end def register_as_student(student = nil) student = build(:student) if student.nil? visit register_path fill_in "Username", with: student.username fill_in "Email", with: student.user.email fill_in "Phone", with: student.user.phone select student.school.name, from: "student_school_id" fill_in "Password", with: student.user.password fill_in "Password confirmation", with: student.user.password_confirmation click_button "Submit" end def register_as_parent(parent = nil) parent = build(:parent) if parent.nil? visit register_path click_link "Parent" fill_in "Email", with: parent.user.email fill_in "Phone", with: parent.user.phone fill_in "Password", with: parent.user.password fill_in "Password confirmation", with: parent.user.password_confirmation click_button "Submit" end end end
Bump version of redcarpet to avoid memory leak
# -*- encoding: utf-8 -*- require File.expand_path('../lib/text_helpers/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Andrew Horner"] gem.email = ["andrew@tablexi.com"] gem.homepage = "https://github.com/ahorner/text-helpers" gem.description = %q{Easily fetch text and static content from your locales} gem.summary = %q{ TextHelpers is a gem which supplies some basic utilities for text localization in Rails projects. The library is intended to make it simple to keep your application's static and semi-static text content independent of the view structure. } gem.files = `git ls-files`.split($\) gem.test_files = gem.files.grep(%r{^test/}) gem.name = "text_helpers" gem.require_paths = ["lib"] gem.version = TextHelpers::VERSION gem.license = "MIT" gem.add_dependency("activesupport") gem.add_dependency("i18n", ">=0.6.8") gem.add_dependency("redcarpet") gem.add_development_dependency("rake") gem.add_development_dependency("railties") end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/text_helpers/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Andrew Horner"] gem.email = ["andrew@tablexi.com"] gem.homepage = "https://github.com/ahorner/text-helpers" gem.description = %q{Easily fetch text and static content from your locales} gem.summary = %q{ TextHelpers is a gem which supplies some basic utilities for text localization in Rails projects. The library is intended to make it simple to keep your application's static and semi-static text content independent of the view structure. } gem.files = `git ls-files`.split($\) gem.test_files = gem.files.grep(%r{^test/}) gem.name = "text_helpers" gem.require_paths = ["lib"] gem.version = TextHelpers::VERSION gem.license = "MIT" gem.add_dependency("activesupport") gem.add_dependency("i18n", ">=0.6.8") gem.add_dependency("redcarpet", ">=3.3.3") gem.add_development_dependency("rake") gem.add_development_dependency("railties") end
Print app name in stats
require 'heroku_log_streamer' require 'heroku_log_line' require 'dyno' class Monitor def initialize(app_name, heroku_api_key) @app_name = app_name @heroku_api_key = heroku_api_key @dynos = {} end def monitor streamer = HerokuLogStreamer.new(heroku_connection, @app_name, tail: '1', ps: 'router') streamer.stream do |line| log_line = HerokuLogLine.new(line) if dyno_name = log_line.dyno @dynos[dyno_name] ||= Dyno.new(heroku_connection, @app_name, dyno_name) if log_line.h12? @dynos[dyno_name].handle_h12 else @dynos[dyno_name].reset_error_count end else puts "malformed line: #{line}" end update_line_statistics end end private def heroku_connection @heroku_connection ||= Heroku::API.new(api_key: @heroku_api_key) end def update_line_statistics @line_counter ||= 0 @line_counter += 1 if @line_counter % 50 == 0 puts "monitored #{@line_counter} lines, #{@dynos.count} dynos reporting" end end end
require 'heroku_log_streamer' require 'heroku_log_line' require 'dyno' class Monitor def initialize(app_name, heroku_api_key) @app_name = app_name @heroku_api_key = heroku_api_key @dynos = {} end def monitor streamer = HerokuLogStreamer.new(heroku_connection, @app_name, tail: '1', ps: 'router') streamer.stream do |line| log_line = HerokuLogLine.new(line) if dyno_name = log_line.dyno @dynos[dyno_name] ||= Dyno.new(heroku_connection, @app_name, dyno_name) if log_line.h12? @dynos[dyno_name].handle_h12 else @dynos[dyno_name].reset_error_count end else puts "malformed line: #{line}" end update_line_statistics end end private def heroku_connection @heroku_connection ||= Heroku::API.new(api_key: @heroku_api_key) end def update_line_statistics @line_counter ||= 0 @line_counter += 1 if @line_counter % 50 == 0 puts "#{@app_name}: monitored #{@line_counter} lines, #{@dynos.count} dynos reporting" end end end
Add rubocop to development dependencies
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'deeplink/version' Gem::Specification.new do |spec| spec.name = 'deeplink' spec.version = Deeplink::VERSION spec.authors = ['Ricardo Otero'] spec.email = ['oterosantos@gmail.com'] spec.summary = 'Gem to manage deep links parsing.' spec.description = 'It mitigates the lack of support for mobile deep links on the URI module.' spec.homepage = 'https://github.com/rikas/deeplink' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(spec)/}) } spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '~> 1.10' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3.4.0', '>= 3.4.0' spec.add_development_dependency 'pry', '~> 0.10.3' end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'deeplink/version' Gem::Specification.new do |spec| spec.name = 'deeplink' spec.version = Deeplink::VERSION spec.authors = ['Ricardo Otero'] spec.email = ['oterosantos@gmail.com'] spec.summary = 'Gem to manage deep links parsing.' spec.description = 'It mitigates the lack of support for mobile deep links on the URI module.' spec.homepage = 'https://github.com/rikas/deeplink' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(spec)/}) } spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '~> 1.10' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3.4.0', '>= 3.4.0' spec.add_development_dependency 'pry', '~> 0.10.3' spec.add_development_dependency 'rubocop', '~> 0.35' spec.add_development_dependency 'rubocop-rspec', '~> 1.3' end
Tweak the "metadata" presentation for HMRC manuals
class NonEditionResult < SearchResult include ERB::Util def to_hash super.merge({ metadata: metadata, metadata_any?: metadata.any?, }) end def format result["document_type"] end def metadata data = [ formatted_public_timestamp, display_type, organisations, ] data.select(&:present?) end private def formatted_public_timestamp public_timestamp && public_timestamp.to_date.strftime("%e %B %Y") end def public_timestamp result["public_timestamp"] || result["last_update"] end def display_type overrides = { "aaib_report" => "AAIB report", "cma_case" => "CMA case", "maib_report" => "MAIB report", "raib_report" => "RAIB report", } overrides.fetch(format, format.humanize) end def organisations orgs = Array(result["organisations"]).reject(&:blank?) org_titles = orgs.map { |org| if org["acronym"] && org["acronym"] != org["title"] "<abbr title='#{h(org["title"])}'>#{h(org["acronym"])}</abbr>" else org["title"] || org["slug"] end } org_titles.join(", ") end end
class NonEditionResult < SearchResult include ERB::Util def to_hash super.merge({ metadata: metadata, metadata_any?: metadata.any?, }) end def format result["document_type"] end def metadata data = [ formatted_public_timestamp, display_type, organisations, ] data.select(&:present?) end private def formatted_public_timestamp public_timestamp && public_timestamp.to_date.strftime("%e %B %Y") end def public_timestamp result["public_timestamp"] || result["last_update"] end def display_type overrides = { "aaib_report" => "AAIB report", "cma_case" => "CMA case", "hmrc_manual" => "HMRC internal manual", "hmrc_manual_section" => "HMRC internal manual section", "maib_report" => "MAIB report", "raib_report" => "RAIB report", } overrides.fetch(format, format.humanize) end def organisations orgs = Array(result["organisations"]).reject(&:blank?) org_titles = orgs.map { |org| if org["acronym"] && org["acronym"] != org["title"] "<abbr title='#{h(org["title"])}'>#{h(org["acronym"])}</abbr>" else org["title"] || org["slug"] end } org_titles.join(", ") end end
Add placeholder for future Solr Rake tasks
#!/usr/bin/env ruby # The ASF licenses this file to You 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. # TODO: fill out Solr tasks: start, stop, ping, optimize, etc. require 'rake' require 'rake/tasklib' module Solr namespace :solr do desc "Start Solr" task :start do # TODO: actually start it up! puts "Starting..." end end end
Add association from answer table to response table
class CreateAnswers < ActiveRecord::Migration def change create_table :answers do |t| t.string :answer_text, null: false t.references :question, null: false t.timestamps end end end
class CreateAnswers < ActiveRecord::Migration def change create_table :answers do |t| t.string :answer_text, null: false t.references :question, null: false t.references :response t.timestamps end end end
Fix description for rake task `unused_views`
desc "Show all unused views" task :load_controllers => :environment do puts "# Loading code in search of controllers" Rails.application.eager_load! end task :unused_views, [ :path ] => :load_controllers do |task, args| base_path = Rails.root.join('app').join('views').join(args[:path] || "") puts "# Unused Views" unused_views = UnusedView.find_all(base_path) puts unused_views end
task :load_controllers => :environment do puts "# Loading code in search of controllers" Rails.application.eager_load! end desc "Show all unused views" task :unused_views, [ :path ] => :load_controllers do |task, args| base_path = Rails.root.join('app').join('views').join(args[:path] || "") puts "# Unused Views" unused_views = UnusedView.find_all(base_path) puts unused_views end
Add wiki message to instructions
module Rain class InstallGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) def copy_config_file copy_file "versions.yml", "config/versions.yml" end def show_capistrano_instructions say <<-TEXT Please add `require 'rain/capistrano'` to Capfile and define your :to_stage and :to_production tasks in config/deploy.rb. Then, all you have to do to deploy to all of your servers is rain on {environment} TEXT end end end
module Rain class InstallGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) def copy_config_file copy_file "versions.yml", "config/versions.yml" end def show_capistrano_instructions say <<-TEXT Please add `require 'rain/capistrano'` to Capfile and define your :to_stage and :to_production tasks in config/deploy.rb. Then, all you have to do to deploy to all of your servers is rain on {environment} Consult http://github.com/eLocal/rain/wiki for more information. TEXT end end end
Fix check for whether the container exists and is not running
module VagrantPlugins module DockerProvider module Action class CheckRunning def initialize(app, env) @app = app end def call(env) if env[:machine].state.id == :not_created raise Vagrant::Errors::VMNotCreatedError end if env[:machine].state.id == :created raise Vagrant::Errors::VMNotRunningError end # Call the next if we have one (but we shouldn't, since this # middleware is built to run with the Call-type middlewares) @app.call(env) end end end end end
module VagrantPlugins module DockerProvider module Action class CheckRunning def initialize(app, env) @app = app end def call(env) if env[:machine].state.id == :not_created raise Vagrant::Errors::VMNotCreatedError end if env[:machine].state.id == :stopped raise Vagrant::Errors::VMNotRunningError end # Call the next if we have one (but we shouldn't, since this # middleware is built to run with the Call-type middlewares) @app.call(env) end end end end end
Package version is increased from 0.4.5.3 to 0.5.0.0
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'schema' s.summary = "Primitives for schema and structure" s.version = '0.4.5.3' s.description = ' ' s.authors = ['The Eventide Project'] s.email = 'opensource@eventide-project.org' s.homepage = 'https://github.com/eventide-project/schema' 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 'attribute' s.add_runtime_dependency 'set_attributes' s.add_runtime_dependency 'virtual' s.add_development_dependency 'test_bench' end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'schema' s.summary = "Primitives for schema and structure" s.version = '0.5.0.0' s.description = ' ' s.authors = ['The Eventide Project'] s.email = 'opensource@eventide-project.org' s.homepage = 'https://github.com/eventide-project/schema' 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 'attribute' s.add_runtime_dependency 'set_attributes' s.add_runtime_dependency 'virtual' s.add_development_dependency 'test_bench' end
Disable reindexing while purging attachments
namespace :attachments do desc "Clean attachments older than 2 years" task :cleanup => :environment do delay = 2.years.ago invoices = Invoice.where("pdf_updated_at < ?", delay) bar = RakeProgressbar.new(invoices.count) invoices.each do |i| bar.inc begin i.pdf.clear; i.save rescue puts "Failed to save invoice #{i.id}" end end bar.finished subscriptions = Subscription.where("pdf_updated_at < ?", delay) bar = RakeProgressbar.new(subscriptions.count) subscriptions.each { |i| i.pdf.clear; i.save; bar.inc }; bar.finished cached_documents = CachedDocument.where("document_updated_at < ?", delay) bar = RakeProgressbar.new(cached_documents.count) cached_documents.each { |i| i.document.clear; i.save; bar.inc }; bar.finished salaries = Salaries::Salary.where("pdf_updated_at < ?", delay) bar = RakeProgressbar.new(salaries.count) salaries.each { |i| i.pdf.clear; i.save; bar.inc }; bar.finished puts "done" end end
namespace :attachments do desc "Clean attachments older than 2 years" task :cleanup => :environment do delay = 2.years.ago Rails.configuration.settings['elasticsearch']['enable_index'] = false invoices = Invoice.where("pdf_updated_at < ?", delay) bar = RakeProgressbar.new(invoices.count) invoices.in_batches(of: 100) do |i| bar.inc begin i.pdf.clear; i.save rescue puts "Failed to save invoice #{i.id}" end end bar.finished subscriptions = Subscription.where("pdf_updated_at < ?", delay) bar = RakeProgressbar.new(subscriptions.count) subscriptions.each { |i| i.pdf.clear; i.save; bar.inc }; bar.finished cached_documents = CachedDocument.where("document_updated_at < ?", delay) bar = RakeProgressbar.new(cached_documents.count) cached_documents.each { |i| i.document.clear; i.save; bar.inc }; bar.finished salaries = Salaries::Salary.where("pdf_updated_at < ?", delay) bar = RakeProgressbar.new(salaries.count) salaries.each { |i| i.pdf.clear; i.save; bar.inc }; bar.finished puts "done. Reindexing required." Rails.configuration.settings['elasticsearch']['enable_index'] = true end end
Test run of tesseract through rails
class TesseractPagesController < ApplicationController skip_before_filter :verify_authenticity_token def run puts "In Run Controller" puts params[:image] jpg = Base64.decode64(params[:image]) #File.open("ocr/sample.jpg",'wb') do |f| # f.write jpg #end #str = %x(./ocr/bin/tesseract ocr/sample.jpg ocr/out) #str = %x(./ocr/bin/tesseract --version) %x(mkdir test123) str = %x(ls) render text: str end end
class TesseractPagesController < ApplicationController skip_before_filter :verify_authenticity_token def run puts "In Run Controller" puts params[:image] jpg = Base64.decode64(params[:image]) File.open("tmp/sample.jpg",'wb') do |f| f.write jpg end #str = %x(./ocr/bin/tesseract ocr/sample.jpg ocr/out) str = %x(tesseract --version) render text: str end end
Add an example for ruby indenting
class Foo var.func1(:param => 'value') do var.func2(:param => 'value') do puts "test" end end var.func1(:param => 'value') { var.func2(:param => 'value') { foo({ bar => baz }) puts "test one" puts "test two" } } foo, bar = { :bar => { :one => 'two', :three => 'four', :five => 'six' } } var. func1(:param => 'value') { var.func2(:param => 'value') { puts "test" } } var. func1(:param => 'value') { func1_5(:param => 'value') var.func2(:param => 'value') { puts "test" } } foo, bar = { :bar => { :foo { 'bar' => 'baz' }, :one => 'two', :three => 'four' } } end
Fix failing test for RepoURL
module InchCI class RepoURL attr_reader :service, :url def initialize(url) @url = url [url, url + '.git'].each do |_url| @service ||= Repomen::Repo::Service.for(_url) end end def project_uid return if service.nil? "#{service.name}:#{service.user_name}/#{service.repo_name}" end def repo_url return if service.nil? if service.name == :github "https://github.com/#{service.user_name}/#{service.repo_name}.git" else url end end end end
module InchCI class RepoURL attr_reader :service, :url def initialize(url) @url = url.to_s [@url, @url + '.git'].each do |_url| @service ||= Repomen::Repo::Service.for(_url) end end def project_uid return if service.nil? "#{service.name}:#{service.user_name}/#{service.repo_name}" end def repo_url return if service.nil? if service.name == :github "https://github.com/#{service.user_name}/#{service.repo_name}.git" else url end end end end
Add comments to explain purpose of rescue block
require File.dirname(__FILE__) + '/support/setup' # A background job to update all child models with the correct access level # of the parent document, and update all assets on S3. class UpdateAccess < CloudCrowd::Action def process begin ActiveRecord::Base.establish_connection access = options['access'] document = Document.find(input) [Page, Entity, EntityDate].each{ |model_klass| model_klass.where(:document_id => document.id).update_all(:access=>access) } begin DC::Store::AssetStore.new.set_access(document, access) rescue AWS::S3::Errors::NoSuchKey end document.update_attributes(:access => access) rescue Exception => e LifecycleMailer.exception_notification(e,options).deliver document.update_attributes(:access => DC::Access::ERROR) if document raise e end true end end
require File.dirname(__FILE__) + '/support/setup' # A background job to update all child models with the correct access level # of the parent document, and update all assets on S3. class UpdateAccess < CloudCrowd::Action def process begin ActiveRecord::Base.establish_connection access = options['access'] document = Document.find(input) [Page, Entity, EntityDate].each{ |model_klass| model_klass.where(:document_id => document.id).update_all(:access=>access) } begin DC::Store::AssetStore.new.set_access(document, access) rescue AWS::S3::Errors::NoSuchKey # Quite a few docs are missing text assets # Even though they are incomplete, They should still # be able to have their access manipulated end document.update_attributes(:access => access) rescue Exception => e LifecycleMailer.exception_notification(e,options).deliver document.update_attributes(:access => DC::Access::ERROR) if document raise e end true end end
Set primary key on MagicBeans::Id model
module MagicBeans class Id < ActiveRecord::Base set_primary_key :id belongs_to :resource, polymorphic: true end end
module MagicBeans class Id < ActiveRecord::Base self.primary_key = "id" belongs_to :resource, polymorphic: true end end
Add sanity check for Rails 3 and after
unless $gems_rake_task if Rails::VERSION::MAJOR <= 2 && Rails::VERSION::MINOR <= 3 && Rails::VERSION::TINY <= 7 $stderr.puts "rails_xss requires Rails 2.3.8 or later. Please upgrade to enable automatic HTML safety." else require 'rails_xss' end end
unless $gems_rake_task if Rails::VERSION::MAJOR >= 3 $stderr.puts "You don't need to install rails_xss as a plugin for Rails 3 and after." elsif Rails::VERSION::MAJOR <= 2 && Rails::VERSION::MINOR <= 3 && Rails::VERSION::TINY <= 7 $stderr.puts "rails_xss requires Rails 2.3.8 or later. Please upgrade to enable automatic HTML safety." else require 'rails_xss' end end
Make TestMap a subclass of Poke::Test
require_relative 'test_helper' class TestMap < MiniTest::Unit::TestCase def setup @map = Poke::Map.new(map_file: 'media/grid_one/map.txt') end def test_extract_map_key_produces_a_hash @map_image_key = @map.instance_variable_get(:@map_image_key) assert_equal({'.'=>0, 'V'=>1, 'g'=>2}, @map_image_key) end end
require_relative 'test_helper' class TestMap < Poke::Test def setup @map = Poke::Map.new(map_file: 'media/grid_one/map.txt') end def test_extract_map_key_produces_a_hash @map_image_key = @map.instance_variable_get(:@map_image_key) assert_equal({'.'=>0, 'V'=>1, 'g'=>2}, @map_image_key) end end
Change no reply to new alias; Add CC to user submitting the request so they have a record of the request
class RegistrationMailer < ActionMailer::Base default from: "no-reply@library.nyu.edu" def registration_email(user) @user_data = user emails = registration_emails.collect { |email| email["email"] } mail(to: emails, subject: t('send_email.subject')) if emails.present? end private def registration_emails (Figs.env['REGISTRATION_EMAILS'] || []) end end
class RegistrationMailer < ActionMailer::Base default from: "lib-no-reply@nyu.edu" def registration_email(user) @user_data = user emails = registration_emails.collect { |email| email["email"] } mail(to: emails, cc: @user_data.email, subject: t('send_email.subject')) if emails.present? end private def registration_emails (Figs.env['REGISTRATION_EMAILS'] || []) end end
Add route to charity page.
Clapp::Application.routes.draw do get 'templates/:path.html' => 'templates#page', :constraints => { :path => /.+/ }, :as => 'templates_show' scope :templates do get '' => 'home#index', :as => 'templates' get 'causes' => 'home#index', :as => 'causes' get 'recommended' => 'home#index', :as => 'recommended' get 'settings' => 'home#index', :as => 'settings' end scope :api do scope :charity do get 'search' => 'api/charity#search', :as => 'api_charity_search' get ':bn' => 'api/charity#show', :as => 'api_charity_show' end end root 'home#index' end
Clapp::Application.routes.draw do get 'templates/:path.html' => 'templates#page', :constraints => { :path => /.+/ }, :as => 'templates_show' scope :templates do get '' => 'home#index', :as => 'templates' get 'causes' => 'home#index', :as => 'causes' get 'recommended' => 'home#index', :as => 'recommended' get 'settings' => 'home#index', :as => 'settings' get 'charity/:id' => 'home#index', :as => 'charity' end scope :api do scope :charity do get 'search' => 'api/charity#search', :as => 'api_charity_search' get ':bn' => 'api/charity#show', :as => 'api_charity_show' end end root 'home#index' end
Allow sentry to capture POST data
# frozen_string_literal: true require 'concurrent' Rails.application.tap do |app| pool = ::Concurrent::ThreadPoolExecutor.new(max_queue: 10) Raven.configure do |config| config.sanitize_fields = app.config.filter_parameters.map(&:to_s) config.async = lambda do |event| pool.post { ::Raven.send_event(event) } end # Do not sent full list of gems with each event config.send_modules = false end end
# frozen_string_literal: true require 'concurrent' Rails.application.tap do |app| pool = ::Concurrent::ThreadPoolExecutor.new(max_queue: 10) Raven.configure do |config| config.sanitize_fields = app.config.filter_parameters.map(&:to_s) config.processors -= [Raven::Processor::PostData] # Do this to send POST data config.async = lambda do |event| pool.post { ::Raven.send_event(event) } end # Do not sent full list of gems with each event config.send_modules = false end end
Handle the stack going away
module StackMaster module Commands class Delete include Command include StackMaster::Prompter def initialize(region, stack_name) @region = region @stack_name = stack_name @from_time = Time.now end def perform return unless check_exists unless ask?("Really delete stack (y/n)? ") StackMaster.stdout.puts "Stack update aborted" return end delete_stack tail_stack_events end private def delete_stack cf.delete_stack({stack_name: @stack_name}) end def check_exists cf.describe_stacks({stack_name: @stack_name}) true rescue Aws::CloudFormation::Errors::ValidationError StackMaster.stdout.puts "Stack does not exist" false end def cf StackMaster.cloud_formation_driver end def tail_stack_events StackEvents::Streamer.stream(@stack_name, @region, io: StackMaster.stdout, from: @from_time) end end end end
module StackMaster module Commands class Delete include Command include StackMaster::Prompter def initialize(region, stack_name) @region = region @stack_name = stack_name @from_time = Time.now end def perform return unless check_exists unless ask?("Really delete stack (y/n)? ") StackMaster.stdout.puts "Stack update aborted" return end delete_stack tail_stack_events end private def delete_stack cf.delete_stack({stack_name: @stack_name}) end def check_exists cf.describe_stacks({stack_name: @stack_name}) true rescue Aws::CloudFormation::Errors::ValidationError StackMaster.stdout.puts "Stack does not exist" false end def cf StackMaster.cloud_formation_driver end def tail_stack_events StackEvents::Streamer.stream(@stack_name, @region, io: StackMaster.stdout, from: @from_time) StackMaster.stdout.puts "Stack deleted" rescue Aws::CloudFormation::Errors::ValidationError # Unfortunately the stack as a tendency of going away before we get the final delete event. StackMaster.stdout.puts "Stack deleted" end end end end
Add an ActiveRecord model to test against.
class Block < ActiveRecord::Base def do_work(*args) block = Block.first block.name = "Charlie" block.color = "Black" block.save end end class CreateBlocks < ActiveRecord::Migration def change create_table :blocks do |t| t.string :name t.string :color t.timestamps end end end
Use old tagging system for podspec
Pod::Spec.new do |s| s.name = 'RNCryptor' s.version = '4.0.0-beta.1' s.summary = 'Cross-language AES Encryptor/Decryptor data format.' s.authors = {'Rob Napier' => 'robnapier@gmail.com'} s.social_media_url = 'https://twitter.com/cocoaphony' s.license = 'MIT' s.source = { :git => 'https://github.com/rnapier/RNCryptor.git', :tag => "v#{s.version.to_s}" } s.description = 'Implements a secure encryption format based on AES, PBKDF2, and HMAC.' s.homepage = 'https://github.com/rnapier/RNCryptor' s.source_files = 'RNCryptor.swift', 'RNCryptor.h' s.ios.deployment_target = '8.0' s.osx.deployment_target = '10.9' end
Pod::Spec.new do |s| s.name = 'RNCryptor' s.version = '4.0.0-beta.1' s.summary = 'Cross-language AES Encryptor/Decryptor data format.' s.authors = {'Rob Napier' => 'robnapier@gmail.com'} s.social_media_url = 'https://twitter.com/cocoaphony' s.license = 'MIT' s.source = { :git => 'https://github.com/rnapier/RNCryptor.git', :tag => "RNCryptor-#{s.version.to_s}" } s.description = 'Implements a secure encryption format based on AES, PBKDF2, and HMAC.' s.homepage = 'https://github.com/rnapier/RNCryptor' s.source_files = 'RNCryptor.swift', 'RNCryptor.h' s.ios.deployment_target = '8.0' s.osx.deployment_target = '10.9' end
Update to the latest dat-worker-pool
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'dat-tcp/version' Gem::Specification.new do |gem| gem.name = "dat-tcp" gem.version = DatTCP::VERSION gem.authors = ["Collin Redding", "Kelly Redding"] gem.email = ["collin.redding@me.com", "kelly@kellyredding.com"] gem.summary = "A generic threaded TCP server API" gem.description = "A generic threaded TCP server API." gem.homepage = "https://github.com/redding/dat-tcp" gem.license = 'MIT' gem.files = `git ls-files -- lib/* Gemfile Rakefile *.gemspec`.split($/) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.add_development_dependency("assert", ["~> 2.16.1"]) gem.add_development_dependency("scmd", ["~> 3.0.2"]) gem.add_dependency("dat-worker-pool", ["~> 0.6.1"]) end
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'dat-tcp/version' Gem::Specification.new do |gem| gem.name = "dat-tcp" gem.version = DatTCP::VERSION gem.authors = ["Collin Redding", "Kelly Redding"] gem.email = ["collin.redding@me.com", "kelly@kellyredding.com"] gem.summary = "A generic threaded TCP server API" gem.description = "A generic threaded TCP server API." gem.homepage = "https://github.com/redding/dat-tcp" gem.license = 'MIT' gem.files = `git ls-files -- lib/* Gemfile Rakefile *.gemspec`.split($/) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.add_development_dependency("assert", ["~> 2.16.1"]) gem.add_development_dependency("scmd", ["~> 3.0.2"]) gem.add_dependency("dat-worker-pool", ["~> 0.6.3"]) end
Add the ability to refresh the RSS feed.
require 'iconv' require 'rss/1.0' require 'rss/2.0' require 'open-uri' require 'sinatra' $: << File.join(File.dirname(__FILE__), 'vendor', 'ruby-oembed', 'lib') require 'oembed' @@rss_url = "http://feeds.pinboard.in/rss/u:evaryont/" ic = Iconv.new('UTF-8//IGNORE', 'UTF-8') valid_string = ic.iconv(open(@@rss_url).read << ' ')[0..-2] @@rss = RSS::Parser.parse valid_string, false set :public, File.dirname(__FILE__) + '/public' set :views, File.dirname(__FILE__) + '/templates' def rss @@rss end get '/' do erb :index end
require 'iconv' require 'rss/1.0' require 'rss/2.0' require 'open-uri' require 'sinatra' $: << File.join(File.dirname(__FILE__), 'vendor', 'ruby-oembed', 'lib') require 'oembed' def refresh_rss valid_string = @ic.iconv(open(@@rss_url).read << ' ')[0..-2] @@rss = RSS::Parser.parse valid_string, false end @@rss_url = "http://feeds.pinboard.in/rss/u:evaryont/" @ic = Iconv.new('UTF-8//IGNORE', 'UTF-8') refresh_rss() set :public, File.dirname(__FILE__) + '/public' set :views, File.dirname(__FILE__) + '/templates' def rss @@rss end get '/' do erb :index end get '/refresh' do refresh_rss() redirect :/ end
Move method up in the file
require 'kumade/deployer' class Kumade def self.load_tasks deployer.load_tasks end class << self attr_writer :staging, :production attr_accessor :staging_app, :production_app def reset! @staging = nil @production = nil @staging_app = nil @production_app = nil end def staging @staging ||= 'staging' end def production @production ||= 'production' end end def self.deployer @deployer ||= Deployer.new end end
require 'kumade/deployer' class Kumade def self.load_tasks deployer.load_tasks end def self.deployer @deployer ||= Deployer.new end class << self attr_writer :staging, :production attr_accessor :staging_app, :production_app def reset! @staging = nil @production = nil @staging_app = nil @production_app = nil end def staging @staging ||= 'staging' end def production @production ||= 'production' end end end
Refactor parser to emit blank lines
require 'strscan' module Syntax class Element attr_accessor :content, :children def initialize(content = nil) @content = content @children = [] end def empty? @children.empty? end end EOL = "\n".freeze class Parser def initialize(input) @input = clean_input(input) end def parse @scanner = StringScanner.new(@input) @root = Element.new parse_block_level(@root) @root end private def parse_block_level(element) text = @scanner.scan_until(/#{EOL}/) paragraph = Element.new(text.rstrip) element.children << paragraph parse_block_level(element) unless @scanner.eos? element end def parse_paragraph_level(element) end def clean_input(input) input.gsub(/\r\n?/, EOL).chomp + EOL end end end
require 'strscan' module Syntax class Element attr_accessor :content, :children def initialize(content = nil) @content = content @children = [] end def empty? @children.empty? end end EOL = "\n".freeze class Parser def initialize(input) @input = clean_input(input) end def parse @scanner = StringScanner.new(@input) @root = Element.new parse_block_level(@root) @root end private def parse_block_level(element) text = @scanner.scan_until(/#{EOL}/).rstrip if text.empty? element.children << Element.new else element.children << Element.new(text) end parse_block_level(element) unless @scanner.eos? element end def clean_input(input) input.gsub(/\r\n?/, EOL).chomp + EOL end end end
Revert "Setting the content value in the versions to be an empty string"
module Irwi::Extensions::Models::WikiPage module ClassMethods def find_by_path_or_new( path ) self.find_by_path( path ) || self.new( :path => path, :title => path ) end end module InstanceMethods # Retrieve number of last version def last_version_number last = versions.first last ? last.number : 0 end protected def create_new_version n = last_version_number v = versions.build v.attributes = attributes.slice( *v.attribute_names ) v.comment = comment v.content = '' v.number = n + 1 v.save! end end def self.included( base ) base.send :extend, Irwi::Extensions::Models::WikiPage::ClassMethods base.send :include, Irwi::Extensions::Models::WikiPage::InstanceMethods base.send :attr_accessor, :comment, :previous_version_number base.belongs_to :creator, :class_name => Irwi.config.user_class_name base.belongs_to :updator, :class_name => Irwi.config.user_class_name base.has_many :versions, :class_name => Irwi.config.page_version_class_name, :foreign_key => Irwi.config.page_version_foreign_key, :order => 'id DESC' base.after_save :create_new_version end end
module Irwi::Extensions::Models::WikiPage module ClassMethods def find_by_path_or_new( path ) self.find_by_path( path ) || self.new( :path => path, :title => path ) end end module InstanceMethods # Retrieve number of last version def last_version_number last = versions.first last ? last.number : 0 end protected def create_new_version n = last_version_number v = versions.build v.attributes = attributes.slice( *v.attribute_names ) v.comment = comment v.number = n + 1 v.save! end end def self.included( base ) base.send :extend, Irwi::Extensions::Models::WikiPage::ClassMethods base.send :include, Irwi::Extensions::Models::WikiPage::InstanceMethods base.send :attr_accessor, :comment, :previous_version_number base.belongs_to :creator, :class_name => Irwi.config.user_class_name base.belongs_to :updator, :class_name => Irwi.config.user_class_name base.has_many :versions, :class_name => Irwi.config.page_version_class_name, :foreign_key => Irwi.config.page_version_foreign_key, :order => 'id DESC' base.after_save :create_new_version end end
Simplify logic in update job verification
class UpdateJob < JuliaJob queue_as :default def perform(*args) Batch.current_marker += 1 set_batch_marker :current, Batch.current_marker system "#{@sys_run} db:migrate" system "#{@sys_run} metadata:digest" system "#{@sys_run} scour:devour" system "#{@sys_run} github:unpack" system "#{@sys_run} news:make" system "#{@sys_run} crawl:feed" system "#{@sys_run} decibans:digest" system "#{@sys_run} require:all" marker_list = [Batch.current_marker, Batch.active_marker] batch_counts = \ Batch.where(marker: marker_list).group(:marker).count return if batch_counts.empty? return unless batch_counts[Batch.current_marker].present? return unless batch_counts[Batch.current_marker] > 2500 Batch.active_marker = Batch.current_marker set_batch_marker :active, Batch.active_marker Batch.active_marker_date = Batch.current_marker_date set_batch_marker :active_date, Batch.active_marker_date system "rails restart" if Rails.env.production? system "#{@sys_run} downloads:packages" end end
class UpdateJob < JuliaJob queue_as :default def perform(*args) Batch.current_marker += 1 set_batch_marker :current, Batch.current_marker system "#{@sys_run} db:migrate" system "#{@sys_run} metadata:digest" system "#{@sys_run} scour:devour" system "#{@sys_run} github:unpack" system "#{@sys_run} news:make" system "#{@sys_run} crawl:feed" system "#{@sys_run} decibans:digest" system "#{@sys_run} require:all" batch_count = Batch.where(marker: Batch.current_marker).count return unless batch_count > 2500 Batch.active_marker = Batch.current_marker set_batch_marker :active, Batch.active_marker Batch.active_marker_date = Batch.current_marker_date set_batch_marker :active_date, Batch.active_marker_date system "rails restart" if Rails.env.production? system "#{@sys_run} downloads:packages" end end
Index the solr freshness boolean
class IndexRequestsWithSolr < ActiveRecord::Migration def self.up add_column :info_requests, :solr_up_to_date, :boolean, :default => false, :null => false end def self.down remove_column :info_requests, :solr_up_to_date end end
class IndexRequestsWithSolr < ActiveRecord::Migration def self.up add_column :info_requests, :solr_up_to_date, :boolean, :default => false, :null => false add_index :info_requests, :solr_up_to_date end def self.down remove_index :info_requests, :solr_up_to_date remove_column :info_requests, :solr_up_to_date end end
Remove nil values from the join
require 'cgi' require 'jwt' require 'securerandom' require 'uri' class ZendeskSSOURL attr_reader :user, :return_to, :settings def initialize(user, return_to, settings) @user = user @return_to = return_to @settings = settings end def to_s URI::HTTPS.build( host: host, path: path, query: query_hash.to_query, ).to_s end private def host "#{settings.subdomain}.zendesk.com" end def path '/access/jwt' end # From https://github.com/zendesk/zendesk_jwt_sso_examples/blob/master/ruby_on_rails_jwt.rb def payload iat = Time.now.to_i jti = "#{iat}/#{SecureRandom.hex(18)}" JWT.encode({ iat: iat, jti: jti, name: [user.first_name, user.last_name].join(' '), email: user.email, }, settings.shared_secret) end def query_hash q = { jwt: payload } q[:return_to] = CGI.escape(return_to) if return_to.present? q end end
require 'cgi' require 'jwt' require 'securerandom' require 'uri' class ZendeskSSOURL attr_reader :user, :return_to, :settings def initialize(user, return_to, settings) @user = user @return_to = return_to @settings = settings end def to_s URI::HTTPS.build( host: host, path: path, query: query_hash.to_query, ).to_s end private def host "#{settings.subdomain}.zendesk.com" end def path '/access/jwt' end # From https://github.com/zendesk/zendesk_jwt_sso_examples/blob/master/ruby_on_rails_jwt.rb def payload iat = Time.now.to_i jti = "#{iat}/#{SecureRandom.hex(18)}" JWT.encode({ iat: iat, jti: jti, name: [user.first_name, user.last_name].compact.join(' '), email: user.email, }, settings.shared_secret) end def query_hash q = { jwt: payload } q[:return_to] = CGI.escape(return_to) if return_to.present? q end end
Reduce sql calls on api divisions show
json.partial! "division", division: @division # Extra information that isn't in the summary json.summary @division.motion json.votes @division.votes.order(:vote), partial: "api/v1/votes/vote", as: :vote json.policy_divisions do json.array! @division.policy_divisions do |pd| json.policy do json.partial! "api/v1/policies/policy", policy: pd.policy end json.vote pd.vote_without_strong json.strong pd.strong_vote? end end json.bills @division.bills, partial: "api/v1/bills/bill", as: :bill
json.partial! "division", division: @division # Extra information that isn't in the summary json.summary @division.motion json.votes @division.votes.order(:vote).includes(:member), partial: "api/v1/votes/vote", as: :vote json.policy_divisions do json.array! @division.policy_divisions.includes(:policy) do |pd| json.policy do json.partial! "api/v1/policies/policy", policy: pd.policy end json.vote pd.vote_without_strong json.strong pd.strong_vote? end end json.bills @division.bills, partial: "api/v1/bills/bill", as: :bill
Add cask for VMware Fusion 7
cask :v1 => 'vmware-fusion7' do version '7.1.2-2779224' sha256 '93e809ece4f915fcb462affabfce2d7c85eb08314b548e2cde44cb2a67ad7d76' url "https://download3.vmware.com/software/fusion/file/VMware-Fusion-#{version}.dmg" name 'VMware Fusion' homepage 'https://www.vmware.com/products/fusion/' license :commercial tags :vendor => 'VMware' binary 'VMware Fusion.app/Contents/Library/vmnet-cfgcli' binary 'VMware Fusion.app/Contents/Library/vmnet-cli' binary 'VMware Fusion.app/Contents/Library/vmrun' binary 'VMware Fusion.app/Contents/Library/vmware-vdiskmanager' binary 'VMware Fusion.app/Contents/Library/VMware OVF Tool/ovftool' app 'VMware Fusion.app' uninstall_preflight do set_ownership "#{staged_path}/VMware Fusion.app" end zap :delete => [ # note: '~/Library/Application Support/VMware Fusion' is not safe # to delete. In older versions, VM images were located there. '~/Library/Caches/com.vmware.fusion', '~/Library/Logs/VMware', '~/Library/Logs/VMware Fusion', ] end
Update to a minimum of manageiq-appliance_console v3.3.1
# Add gems here, in Gemfile syntax, which are dependencies of the appliance itself rather than a part of the ManageIQ application gem "manageiq-appliance_console", "~>3.3", :require => false
# Add gems here, in Gemfile syntax, which are dependencies of the appliance itself rather than a part of the ManageIQ application gem "manageiq-appliance_console", "~>3.3", ">=3.3.1", :require => false
Allow retrieving `automatic` type values from nodes
module KnifeAttribute module Node class NodeAttributeGet < Chef::Knife include KnifeAttribute::Node::Helpers include KnifeAttribute::Get banner 'knife node attribute get NODE PERIOD.SEPARATED.ATTRIBUTE (options)' end end end
module KnifeAttribute module Node class NodeAttributeGet < Chef::Knife include KnifeAttribute::Node::Helpers include KnifeAttribute::Get def self.attribute_type_map { default: :default_attrs, normal: :normal_attrs, override: :override_attrs, automatic: :automatic_attrs, } end banner 'knife node attribute get NODE PERIOD.SEPARATED.ATTRIBUTE (options)' end end end
Add rdmm gem that is API Client for DMM and DMM.R18
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'dmm-crawler/version' Gem::Specification.new do |spec| spec.name = 'dmm-crawler' spec.version = DMMCrawler::VERSION spec.authors = ['Satoshi Ohmori'] spec.email = ['sachin21dev@gmail.com'] spec.summary = "Show DMM and DMM.R18's crawled data" spec.description = "Show DMM and DMM.R18's crawled data. e.g. ranking" spec.homepage = 'https://github.com/sachin21/dmm-crawler' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0") spec.require_paths = ['lib'] spec.add_runtime_dependency 'mechanize' spec.add_development_dependency 'bundler' spec.add_development_dependency 'rake' spec.add_development_dependency 'rubocop', '< 0.49.0' spec.add_development_dependency 'pry' spec.add_development_dependency 'rspec' end
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'dmm-crawler/version' Gem::Specification.new do |spec| spec.name = 'dmm-crawler' spec.version = DMMCrawler::VERSION spec.authors = ['Satoshi Ohmori'] spec.email = ['sachin21dev@gmail.com'] spec.summary = "Show DMM and DMM.R18's crawled data" spec.description = "Show DMM and DMM.R18's crawled data. e.g. ranking" spec.homepage = 'https://github.com/sachin21/dmm-crawler' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0") spec.require_paths = ['lib'] spec.add_runtime_dependency 'rdmm' spec.add_runtime_dependency 'mechanize' spec.add_development_dependency 'bundler' spec.add_development_dependency 'rake' spec.add_development_dependency 'rubocop', '< 0.49.0' spec.add_development_dependency 'pry' spec.add_development_dependency 'rspec' end
Add tests for executables in bin
#frozen_string_literal: true require "minitest/autorun" require "fileutils" class TestExecutables < Minitest::Test def test_bundler skip if RUBY_VERSION =~ /^2\.[345]\./ # bundler was added in ruby-2.6 assert_match(/Bundler version/, `bundle --version`) assert_match(/Bundler version/, `bundler --version`) end def test_gem assert_match(/\d+\.\d+\.\d+/, `gem --version`) end def test_erb res = IO.popen("erb", "w+") do |io| io.write "a<%=1+2%>b" io.close_write io.read end assert_match(/a3b/, res) end def test_irb res = IO.popen("irb", "w+") do |io| io.write "'ab'*3\n" io.close_write io.read end assert_match(/\"ababab\"/, res) end def test_rake assert_match(/rake, version/, `rake --version`) end def test_rdoc assert_match(/\d+\.\d+\.\d+/, `rdoc --version`) end def test_ri # We don't deliver ri files assert_match(/Nothing known about String/, `ri String 2>&1`) end def test_rubyw FileUtils.rm_f("test_rubyw.log") system(%q[rubyw -e "File.write('test_rubyw.log','xy')"]) assert_equal("xy", File.read("test_rubyw.log")) end end
Add pry-nav as a development dependency.
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'calvin/version' Gem::Specification.new do |gem| gem.name = "calvin" gem.version = Calvin::VERSION gem.authors = ["Utkarsh Kukreti"] gem.email = ["utkarshkukreti@gmail.com"] gem.description = %q{Very terse programming language, inspired by APL/J/K.} gem.summary = %q{Very terse programming language, inspired by APL/J/K.} gem.homepage = "https://github.com/utkarshkukreti/calvin" gem.files = `git ls-files`.split($/) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.add_dependency "docopt" gem.add_dependency "parslet" gem.add_development_dependency "rspec" gem.add_development_dependency "pry" end
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'calvin/version' Gem::Specification.new do |gem| gem.name = "calvin" gem.version = Calvin::VERSION gem.authors = ["Utkarsh Kukreti"] gem.email = ["utkarshkukreti@gmail.com"] gem.description = %q{Very terse programming language, inspired by APL/J/K.} gem.summary = %q{Very terse programming language, inspired by APL/J/K.} gem.homepage = "https://github.com/utkarshkukreti/calvin" gem.files = `git ls-files`.split($/) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.add_dependency "docopt" gem.add_dependency "parslet" gem.add_development_dependency "rspec" gem.add_development_dependency "pry" gem.add_development_dependency "pry-nav" end
Add \n to the end of lumos line return.
module Kernel def lumos(message = nil, *args) if message.nil? || message == :> lumos_divide args[0], args[1] else lumos_wrap message, args[0] end end private def lumos_divide(delimiter, iterations) delimiter ||= "#" iterations ||= 3 print delimiter * iterations.to_i end def lumos_wrap(message = nil, options) options ||= {} print Lumos::Wrapper.new(message, options).result end end
module Kernel def lumos(message = nil, *args) if message.nil? || message == :> lumos_divide args[0], args[1] else lumos_wrap message, args[0] end end private def lumos_divide(delimiter, iterations) delimiter ||= "#" iterations ||= 3 print (delimiter * iterations.to_i) + "\n" end def lumos_wrap(message = nil, options) options ||= {} print Lumos::Wrapper.new(message, options).result + "\n" end end
Remove the automatic engine require
# # Gems # # gems must load explicitly any gem declared in gemspec # @see https://github.com/bundler/bundler/issues/2018#issuecomment-6819359 # # require 'metasploit/concern' require 'metasploit_data_models' require 'metasploit/model' require 'zip' # # Project # require 'metasploit/credential/engine' # Shared namespace for metasploit gems; used in {https://github.com/rapid7/metasploit-credential metasploit-credential}, # {https://github.com/rapid7/metasploit-framework metasploit-framework}, and # {https://github.com/rapid7/metasploit-model metasploit-model} module Metasploit # The namespace for this gem. module Credential extend ActiveSupport::Autoload autoload :Creation autoload :EntityRelationshipDiagram autoload :Exporter autoload :Importer autoload :Migrator autoload :Origin autoload :Text # The prefix for all `ActiveRecord::Base#table_name`s for `ActiveRecord::Base` subclasses under this namespace. # # @return [String] `'metasploit_credential_'` def self.table_name_prefix 'metasploit_credential_' end end end
# # Gems # # gems must load explicitly any gem declared in gemspec # @see https://github.com/bundler/bundler/issues/2018#issuecomment-6819359 # # require 'metasploit/concern' require 'metasploit_data_models' require 'metasploit/model' require 'zip' # # Project # # Shared namespace for metasploit gems; used in {https://github.com/rapid7/metasploit-credential metasploit-credential}, # {https://github.com/rapid7/metasploit-framework metasploit-framework}, and # {https://github.com/rapid7/metasploit-model metasploit-model} module Metasploit # The namespace for this gem. module Credential extend ActiveSupport::Autoload autoload :Creation autoload :EntityRelationshipDiagram autoload :Exporter autoload :Importer autoload :Migrator autoload :Origin autoload :Text # The prefix for all `ActiveRecord::Base#table_name`s for `ActiveRecord::Base` subclasses under this namespace. # # @return [String] `'metasploit_credential_'` def self.table_name_prefix 'metasploit_credential_' end end end
Send is not needed to call the class method
module Schema module DataStructure def self.included(cls) cls.send :include, Schema cls.extend Virtual::Macro cls.send :virtual, :configure_dependencies cls.extend Build end module Build def build(data=nil) data ||= {} new.tap do |instance| set_attributes(instance, data) instance.configure_dependencies end end def set_attributes(instance, data) SetAttributes.(instance, data) end end end end
module Schema module DataStructure def self.included(cls) cls.send :include, Schema cls.extend Virtual::Macro cls.virtual :configure_dependencies cls.extend Build end module Build def build(data=nil) data ||= {} new.tap do |instance| set_attributes(instance, data) instance.configure_dependencies end end def set_attributes(instance, data) SetAttributes.(instance, data) end end end end
Add a description to the gemspec
require_relative "lib/disc/version" Gem::Specification.new do |s| s.name = 'disc' s.version = Disc::VERSION s.summary = 'A simple and powerful Disque job implementation' s.description = '' s.authors = ['pote'] s.email = ['pote@tardis.com.uy'] s.homepage = 'https://github.com/pote/disque-job' s.license = 'MIT' s.files = `git ls-files`.split("\n") s.executables.push('disc') s.add_dependency('disque', '~> 0.0.6') s.add_dependency('msgpack', '~> 0.6.1') end
require_relative "lib/disc/version" Gem::Specification.new do |s| s.name = 'disc' s.version = Disc::VERSION s.summary = 'A simple and powerful Disque job implementation' s.description = 'Easily define and run background jobs using Disque' s.authors = ['pote'] s.email = ['pote@tardis.com.uy'] s.homepage = 'https://github.com/pote/disque-job' s.license = 'MIT' s.files = `git ls-files`.split("\n") s.executables.push('disc') s.add_dependency('disque', '~> 0.0.6') s.add_dependency('msgpack', '~> 0.6.1') end
Fix sidekiq thread id of context
module ActiveCrew module Backends class SidekiqBackend include Sidekiq::Worker class << self def enqueue(name, invoker, context) Sidekiq::Client.push 'class' => self, 'queue' => queue_name(name), 'args' => [YAML.dump([name, invoker, normalize(context)])] end def queue_name(command_name) command_name[/^(.*)\/[^\/]*$/, 1].underscore.gsub(/\//, '_') end def queue(command_name) Sidekiq::Queue.new queue_name command_name end def context Sidekiq::Processor::WORKER_STATE[Thread.current.object_id.to_s(36)] end private def normalize(context) context.merge(options: context.fetch(:options, {}).to_hash).to_hash end end def perform(context) ActiveCrew::Backends.dequeue *YAML.load(context) end end end end
module ActiveCrew module Backends class SidekiqBackend include Sidekiq::Worker class << self def enqueue(name, invoker, context) Sidekiq::Client.push 'class' => self, 'queue' => queue_name(name), 'args' => [YAML.dump([name, invoker, normalize(context)])] end def queue_name(command_name) command_name[/^(.*)\/[^\/]*$/, 1].underscore.gsub(/\//, '_') end def queue(command_name) Sidekiq::Queue.new queue_name command_name end def context Sidekiq::Processor::WORKER_STATE[Sidekiq::Logging.tid] end private def normalize(context) context.merge(options: context.fetch(:options, {}).to_hash).to_hash end end def perform(context) ActiveCrew::Backends.dequeue *YAML.load(context) end end end end
Edit time zone issue on sign up
require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "active_model/railtie" require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module TipsonRails class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' I18n.enforce_available_locales = true # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif) config.assets.initialize_on_precompile = false end end
require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "active_model/railtie" require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module TipsonRails class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. config.time_zone = 'Eastern Time (US & Canada)' I18n.enforce_available_locales = true # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif) config.assets.initialize_on_precompile = false end end
Add script rundeck delete projects for tests
#!/usr/bin/env ruby #@author:: 'weezhard' #@usage:: 'Delete projects rundeck' #@licence:: 'GPL' #@version: 1.0.0 require 'uri' require 'time' require 'rubygems' require 'json' require 'net/http' require 'optparse' # default options options = {} options[:url] = "localhost" options[:port] = 4440 options[:token] = "kfC91qhEZBMNikzY5NFNEywqhOnBKtSC" options[:all] = false # parse options optparse = OptionParser.new do |opts| opts.banner = "Usage: #{$0} [options]" opts.on('-u', '--url URL', "URL for Rundeck server", String) { |val| options[:url] = val } opts.on('-p', '--port PORT', "PORT for Rundeck server", Integer) { |val| options[:port] = val } opts.on('-t', '--token TOKEN', "TOKEN for Rundeck server", String) { |val| options[:token] = val } opts.on('-p', '--project PROJECT', "PROJECT Rundeck delete", String) { |val| options[:project] = val } opts.on('-a', '--all', "DELETE All projects") { options[:all] = true } opts.on('-h', '--help') do puts opts exit end end optparse.parse! # if we have not found a projet raise OptionParser::MissingArgument if options[:project].nil? and options[:all] == false # Get Projects @headers = {"X-Rundeck-Auth-Token" => options[:token], "Accept" => "application/json"} def getProjects(url, port) uri = URI.parse("http://#{url}:#{port}/api/1/projects") http = Net::HTTP.new(uri.host, uri.port) resp = http.get(uri.path, @headers) projects = resp.body return JSON.parse(projects) end def deleteProject(project) uri = URI.parse("http://localhost:4440/api/11/project/#{project}") http = Net::HTTP.new(uri.host, uri.port) resp = http.delete(uri.path, @headers) puts resp.body end if __FILE__ == $0 if options[:all] == true projects = getProjects(options[:url], options[:port]) for project in projects deleteProject(project["name"]) end else deleteProject(options[:project]) end end
Fix user fixtures for development
Gitlab::Seeder.quiet do (2..20).each do |i| begin User.seed(:id, [{ id: i, username: Faker::Internet.user_name, name: Faker::Name.name, email: Faker::Internet.email, confirmed_at: DateTime.now }]) print '.' rescue ActiveRecord::RecordNotSaved print 'F' end end (1..5).each do |i| begin User.seed do |s| s.username = "user#{i}" s.name = "User #{i}" s.email = "user#{i}@example.com" s.confirmed_at = DateTime.now s.password = '12345678' end print '.' rescue ActiveRecord::RecordNotSaved print 'F' end end end
Gitlab::Seeder.quiet do (2..20).each do |i| begin User.create!( username: Faker::Internet.user_name, name: Faker::Name.name, email: Faker::Internet.email, confirmed_at: DateTime.now, password: '12345678' ) print '.' rescue ActiveRecord::RecordInvalid print 'F' end end (1..5).each do |i| begin User.create!( username: "user#{i}", name: "User #{i}", email: "user#{i}@example.com", confirmed_at: DateTime.now, password: '12345678' ) print '.' rescue ActiveRecord::RecordInvalid print 'F' end end end
Add Message for Display of Data and Route in Logs
require "feedback_router/version" require 'faraday' module FeedbackRouter def self.send(feedback_params, application_name) @base_url, @controller_route = set_up_destination @params = set_params(feedback_params, application_name) send_request end private def self.set_up_destination matches = ENV['FEEDBACK_LOCATION'].match(/(https?:\/\/[\w._:-]+)(.*)/) base_url = matches[1], controller_route = matches[2] end def self.set_params(feedback_params, application_name) feedback_params['app_name'] = application_name end def self.send_request conn = Faraday.new(:url => @base_url) conn.post @controller_route, @params end end
require "feedback_router/version" require 'faraday' module FeedbackRouter def self.send(feedback_params, application_name) @base_url, @controller_route = set_up_destination @params = set_params(feedback_params, application_name) send_request end private def self.set_up_destination matches = ENV['FEEDBACK_LOCATION'].match(/(https?:\/\/[\w._:-]+)(.*)/) base_url = matches[1], controller_route = matches[2] end def self.set_params(feedback_params, application_name) feedback_params['app_name'] = application_name end def self.send_request conn = Faraday.new(:url => @base_url) puts "Sending #{@params} to #{@base_url}#{controller_route}" conn.post @controller_route, @params end end
Remove include CanCan::Ability, since this should be in ::Ability now
require 'cancan' module Forem class Ability < ::Ability include CanCan::Ability def initialize(user) # Let other permissions run before this super user ||= User.new # anonymous user p user.can_read_forem_forums? p user.can_read_forem_forum? if user.can_read_forem_forums? can :read, Forem::Forum do |forum| user.can_read_forem_forum?(forum) end end can :read, Forem::Category do |category| user.can_read_forem_category?(category) end end end end
require 'cancan' module Forem class Ability < ::Ability def initialize(user) # Let other permissions run before this super user ||= User.new # anonymous user p user.can_read_forem_forums? p user.can_read_forem_forum? if user.can_read_forem_forums? can :read, Forem::Forum do |forum| user.can_read_forem_forum?(forum) end end can :read, Forem::Category do |category| user.can_read_forem_category?(category) end end end end
Build flat array with keys
module ROM class Schema class Definition class Relation include Equalizer.new(:header, :keys) def initialize(&block) @header = [] @keys = [] instance_eval(&block) if block end def header Axiom::Relation::Header.coerce(@header, :keys => @keys) end def attribute(name, type) @header << [name, type] self end def key(*attribute_names) @keys << attribute_names self end end # class Relation end # class Definition end # class Schema end # module ROM
module ROM class Schema class Definition class Relation include Equalizer.new(:header, :keys) def initialize(&block) @header = [] @keys = [] instance_eval(&block) if block end def header Axiom::Relation::Header.coerce(@header, :keys => @keys) end def attribute(name, type) @header << [name, type] self end def key(*attribute_names) @keys.concat(attribute_names) self end end # class Relation end # class Definition end # class Schema end # module ROM
Add shindo tests for server volume request methdos for block storage service.
Shindo.tests('Fog::Compute[:hp] | volume requests', ['hp', 'block_storage']) do @list_volume_attachments_format = { 'volumeAttachments' => [{ 'device' => String, 'serverId' => Integer, 'id' => Integer, 'volumeId' => Integer }] } @volume_attachment_format = { 'volumeAttachment' => { 'device' => String, 'volumeId' => Integer } } @base_image_id = ENV["BASE_IMAGE_ID"] || 1242 tests('success') do @server = Fog::Compute[:hp].servers.create(:name => 'fogservoltests', :flavor_id => 100, :image_id => @base_image_id) @server.wait_for { ready? } response = Fog::BlockStorage[:hp].create_volume('fogvoltest', 'fogvoltest desc', 1) @volume_id = response.body['volume']['id'] @device = "\/dev\/sdf" #Fog::BlockStorage[:hp].volumes.get(@volume_id).wait_for { ready? } tests("#attach_volume(#{@server.id}, #{@volume_id}, #{@device}").formats(@volume_attachment_format) do Fog::Compute[:hp].attach_volume(@server.id, @volume_id, @device).body end tests("#detach_volume(#{@server.id}, #{@volume_id}").succeeds do Fog::Compute[:hp].detach_volume(@server.id, @volume_id) end tests("#list_server_volumes(#{@server.id})").formats(@list_volume_attachments_format) do Fog::Compute[:hp].list_server_volumes(@server.id).body end Fog::BlockStorage[:hp].delete_volume(@volume_id) @server.destroy end tests('failure') do tests("#list_server_volumes(#{@server.id})").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].list_server_volumes(@server.id) end tests("#attach_volume(#{@server.id}, 0, #{@device})").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].attach_volume(@server.id, 0, @device) end tests("#attach_volume(0, #{@volume_id}, #{@device})").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].attach_volume(0, @volume_id, @device) end tests("#detach_volume(#{@server.id}, 0)").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].detach_volume(@server.id, 0) end tests("#detach_volume(0, #{@volume_id})").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].detach_volume(0, @volume_id) end end end
Add legal name to organization factories.
FactoryBot.define do factory :organization, :class => :organization do customer_id { 1 } address1 { '100 Main St' } city { 'Harrisburg' } state { 'PA' } zip { '17120' } url { 'http://www.example.com' } phone { '9999999999' } association :organization_type, :factory => :stub_organization_type sequence(:name) { |n| "Org#{n}" } short_name {name} license_holder { true } end factory :organization_basic, :class => :organization do #TODO change this to OrgOriginal customer_id { 1 } address1 { '100 Main St' } city { 'Harrisburg' } state { 'PA' } zip { '17120' } url { 'http://www.example.com' } phone { '9999999999' } association :organization_type, :factory => :organization_type sequence(:name) { |n| "Org Basic#{n+100}" } #TODO change this to OrgOriginal short_name {name} license_holder { true } end end
FactoryBot.define do factory :organization, :class => :organization do customer_id { 1 } address1 { '100 Main St' } city { 'Harrisburg' } state { 'PA' } zip { '17120' } url { 'http://www.example.com' } phone { '9999999999' } association :organization_type, :factory => :stub_organization_type sequence(:name) { |n| "Org#{n}" } short_name {name} legal_name {name} license_holder { true } end factory :organization_basic, :class => :organization do #TODO change this to OrgOriginal customer_id { 1 } address1 { '100 Main St' } city { 'Harrisburg' } state { 'PA' } zip { '17120' } url { 'http://www.example.com' } phone { '9999999999' } association :organization_type, :factory => :organization_type sequence(:name) { |n| "Org Basic#{n+100}" } #TODO change this to OrgOriginal short_name {name} legal_name {name} license_holder { true } end end
Fix typo in task name
namespace :"solidus-adyen" do namespace :factory_girl do desc "Verify that all FactoryGirl factories are valid" task lint: :environment do if Rails.env.test? begin DatabaseCleaner.start FactoryGirl.lint ensure DatabaseCleaner.clean end else system("bundle exec rake factory_girl:lint RAILS_ENV='test'") end end end end
namespace :"solidus-adyen" do namespace :factory_girl do desc "Verify that all FactoryGirl factories are valid" task lint: :environment do if Rails.env.test? begin DatabaseCleaner.start FactoryGirl.lint ensure DatabaseCleaner.clean end else system("bundle exec rake soldius-adyen:factory_girl:lint RAILS_ENV='test'") end end end end
Add tests for activity type duplication
require "test_helper" class ActivityTypeTest < ActiveSupport::TestCase def test_default_create activity_type = FactoryGirl.create(:activity_type) assert activity_type.valid? end def test_specific_create activity_type = FactoryGirl.create(:activity_type, name: 'Seminar', abbreviation: 'sem') assert_equal(activity_type.name, 'Seminar') assert_equal activity_type.abbreviation, 'sem' assert activity_type.valid? end def test_duplicate_activity_type_is_not_allowed activity_type = FactoryGirl.create(:activity_type, name: 'Seminar', abbreviation: 'sem') activity_type = FactoryGirl.build(:activity_type, name: 'Seminar', abbreviation: 'sem') assert activity_type.invalid? end def test_duplicate_activity_type_name_is_not_allowed activity_type = FactoryGirl.create(:activity_type, name: 'Seminar') activity_type = FactoryGirl.build(:activity_type, name: 'Seminar') assert activity_type.invalid? end def test_duplicate_activity_type_abbreviation_is_not_allowed activity_type = FactoryGirl.create(:activity_type, abbreviation: 'sem') activity_type = FactoryGirl.build(:activity_type, abbreviation: 'sem') assert activity_type.invalid? end end
Update to use plain version 3 api, no minor version. SDK-194
# Copyright (C) 2008-2011 AMEE UK Ltd. - http://www.amee.com # Released as Open Source Software under the BSD 3-Clause license. See LICENSE.txt for details. AMEE_API_VERSION = '3.3' require 'amee/v3/meta_helper' require 'amee/v3/collection' require 'amee/v3/connection' require 'amee/v3/item_definition' require 'amee/v3/item_value_definition' require 'amee/v3/item_value_definition_list' require 'amee/v3/return_value_definition'
# Copyright (C) 2008-2011 AMEE UK Ltd. - http://www.amee.com # Released as Open Source Software under the BSD 3-Clause license. See LICENSE.txt for details. AMEE_API_VERSION = '3' require 'amee/v3/meta_helper' require 'amee/v3/collection' require 'amee/v3/connection' require 'amee/v3/item_definition' require 'amee/v3/item_value_definition' require 'amee/v3/item_value_definition_list' require 'amee/v3/return_value_definition'
Configure rspec to randomize order
require 'active_record' require 'polymorpheus' require 'stringio' require 'support/active_record/connection_adapters/abstract_mysql_adapter' ActiveRecord::Base.establish_connection({ adapter: 'mysql2', username: 'travis', database: 'polymorpheus_test' }) Dir[File.dirname(__FILE__) + '/support/*.rb'].sort.each { |path| require path } Polymorpheus::Adapter.load! # This is normally done via a Railtie in non-testing situations. ActiveRecord::SchemaDumper.class_eval { include Polymorpheus::SchemaDumper } ActiveRecord::Migration.verbose = false RSpec.configure do |config| config.include ConnectionHelpers config.include SchemaHelpers config.include SqlTestHelpers config.after do ActiveRecord::Base.connection.tables.each do |table| ActiveRecord::Base.connection.drop_table(table) end end end
require 'active_record' require 'polymorpheus' require 'stringio' require 'support/active_record/connection_adapters/abstract_mysql_adapter' ActiveRecord::Base.establish_connection({ adapter: 'mysql2', username: 'travis', database: 'polymorpheus_test' }) Dir[File.dirname(__FILE__) + '/support/*.rb'].sort.each { |path| require path } Polymorpheus::Adapter.load! # This is normally done via a Railtie in non-testing situations. ActiveRecord::SchemaDumper.class_eval { include Polymorpheus::SchemaDumper } ActiveRecord::Migration.verbose = false RSpec.configure do |config| config.order = :random Kernel.srand config.seed config.include ConnectionHelpers config.include SchemaHelpers config.include SqlTestHelpers config.after do ActiveRecord::Base.connection.tables.each do |table| ActiveRecord::Base.connection.drop_table(table) end end end
Drop all collections except system collections
$LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib")) MODELS = File.join(File.dirname(__FILE__), "models") $LOAD_PATH.unshift(MODELS) require 'rubygems' gem "mocha", ">= 0.9.8" require "mongoid" require "mocha" require "rspec" Mongoid.configure do |config| name = "mongoid_test" host = "localhost" config.master = Mongo::Connection.new.db(name) # config.slaves = [ # Mongo::Connection.new(host, 27018, :slave_ok => true).db(name) # ] end Dir[ File.join(MODELS, "*.rb") ].sort.each { |file| require File.basename(file) } Rspec.configure do |config| config.mock_with :mocha config.after :suite do Mongoid.master.collections.each(&:drop) end end
$LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib")) MODELS = File.join(File.dirname(__FILE__), "models") $LOAD_PATH.unshift(MODELS) require 'rubygems' gem "mocha", ">= 0.9.8" require "mongoid" require "mocha" require "rspec" Mongoid.configure do |config| name = "mongoid_test" host = "localhost" config.master = Mongo::Connection.new.db(name) # config.slaves = [ # Mongo::Connection.new(host, 27018, :slave_ok => true).db(name) # ] end Dir[ File.join(MODELS, "*.rb") ].sort.each { |file| require File.basename(file) } Rspec.configure do |config| config.mock_with :mocha config.after :suite do Mongoid.master.collections.select {|c| c.name !~ /system/ }.each(&:drop) end end
Reset AppleDEPClient configuration for each test
require 'simplecov' SimpleCov.start require 'apple_dep_client'
require 'simplecov' SimpleCov.start require 'apple_dep_client' RSpec.configure do |config| config.before(:each) do AppleDEPClient.configure do |client| client.private_key = nil client.consumer_key = nil client.consumer_secret = nil client.access_token = nil client.access_secret = nil client.access_token_expiry = nil end end end
Simplify and clean up a bit buffer/content spec
require 'spec_helper' describe SQL::Generator::Buffer, '#content' do subject { object.content } let(:object) { described_class.new } shared_examples_for 'buffer content' do it 'should contain expected content' do should eql(expected_content) end its(:frozen?) { should be(true) } it 'should return fresh string copies' do first = object.content second = object.content expect(first).to eql(second) expect(first).to_not be(second) end end context 'with empty buffer' do let(:expected_content) { '' } it_should_behave_like 'buffer content' end context 'with filled buffer' do before do object.append('foo') end let(:expected_content) { 'foo' } it_should_behave_like 'buffer content' end end
require 'spec_helper' describe SQL::Generator::Buffer, '#content' do subject { object.content } let(:object) { described_class.new } shared_examples_for 'buffer content' do it 'should contain expected content' do should eql(expected_content) end it { should be_frozen } it 'should return fresh string copies' do first = object.content second = object.content expect(first).to eql(second) expect(first).to_not be(second) end end context 'with empty buffer' do let(:expected_content) { '' } it_should_behave_like 'buffer content' end context 'with filled buffer' do before do object.append('foo') end let(:expected_content) { 'foo' } it_should_behave_like 'buffer content' end end
Add a breadcrumb configuration for participant's pages
crumb :root do link "Press", root_url end crumb :category do |category| link category.name, category_url(category.slug) parent :category, category.parent if category.parent end crumb :serials do link "すべての連載", serials_url end crumb :serial do |serial| link serial.title, serial_url(serial) parent :serials end crumb :post do |post| link post.title, post_url(public_id: post.public_id) parent :category, post.category end crumb :participant do |participant| link participant.name, participant_url(participant) parent :participants end crumb :participants do link "すべての執筆関係者", participants_url end crumb :page_num do |page_num, options| link "#{page_num}ページ目" if options case when options[:category] parent :category, options[:category] when options[:serial] parent :serial, options[:serial] when options[:serials] parent :serials when options[:participants] parent :participants end else parent :root end end
crumb :root do link "Press", root_url end crumb :category do |category| link category.name, category_url(category.slug) parent :category, category.parent if category.parent end crumb :serials do link "すべての連載", serials_url end crumb :serial do |serial| link serial.title, serial_url(serial) parent :serials end crumb :post do |post| link post.title, post_url(public_id: post.public_id) parent :category, post.category end crumb :participant do |participant| link participant.name, participant_url(participant) parent :participants end crumb :participants do link "すべての執筆関係者", participants_url end crumb :page_num do |page_num, options| link "#{page_num}ページ目" if options case when options[:category] parent :category, options[:category] when options[:serial] parent :serial, options[:serial] when options[:serials] parent :serials when options[:participant] parent :participant, options[:participant] when options[:participants] parent :participants end else parent :root end end
Fix test for checklist value
# frozen_string_literal: true require 'rails_helper' RSpec.describe RepositoryChecklistValue, type: :model do let(:repository_checklist_value) { build :repository_checklist_value } it 'is valid' do expect(repository_checklist_value).to be_valid end it 'should be of class RepositoryChecklistValue' do expect(subject.class).to eq RepositoryChecklistValue end describe 'Database table' do it { should have_db_column :created_by_id } it { should have_db_column :last_modified_by_id } end describe 'Relations' do it { should belong_to(:created_by).class_name('User') } it { should belong_to(:last_modified_by).class_name('User') } it { should accept_nested_attributes_for(:repository_cell) } end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe RepositoryChecklistValue, type: :model do let(:repository_checklist_item) { build :repository_checklist_item } let(:repository_checklist_value) { build :repository_checklist_value } it 'is valid' do repository_checklist_value.repository_checklist_items << repository_checklist_item expect(repository_checklist_value).to be_valid end it 'should be of class RepositoryChecklistValue' do expect(subject.class).to eq RepositoryChecklistValue end describe 'Database table' do it { should have_db_column :created_by_id } it { should have_db_column :last_modified_by_id } end describe 'Relations' do it { should belong_to(:created_by).class_name('User') } it { should belong_to(:last_modified_by).class_name('User') } it { should accept_nested_attributes_for(:repository_cell) } end end
Improve method_missing usage in JIRA::JIRAService
module JIRA class JIRAService < Handsoap::Service include RemoteAPI attr_reader :auth_token, :user def self.instance_at_url(url, user, password) jira = JIRAService.new url jira.login user, password jira end def initialize(endpoint_url) super @endpoint_url = endpoint_url endpoint_data = { :uri => "#{endpoint_url}/rpc/soap/jirasoapservice-v2", :version => 2 } self.class.endpoint endpoint_data end #PONDER: a finalizer that will try to logout def method_missing(method, *args) $stderr.puts "#{method} is not a defined method in the API...yet" end protected def on_create_document(doc) doc.alias 'soap', 'http://soap.rpc.jira.atlassian.com' end def on_response_document(doc) doc.add_namespace 'jir', @endpoint_url end end end
module JIRA class JIRAService < Handsoap::Service include RemoteAPI attr_reader :auth_token, :user def self.instance_at_url(url, user, password) jira = JIRAService.new url jira.login user, password jira end def initialize(endpoint_url) super @endpoint_url = endpoint_url endpoint_data = { :uri => "#{endpoint_url}/rpc/soap/jirasoapservice-v2", :version => 2 } self.class.endpoint endpoint_data end #PONDER: a finalizer that will try to logout def method_missing(method, *args) message = 'Check the documentation; the method may not be implemented yet.' raise NoMethodError, message, caller end protected def on_create_document(doc) doc.alias 'soap', 'http://soap.rpc.jira.atlassian.com' end def on_response_document(doc) doc.add_namespace 'jir', @endpoint_url end end end
Add options hash argument to client method.
require 'savon' require 'inforouter/access_list' require 'inforouter/folder_rule' require 'inforouter/client' require 'inforouter/configuration' require 'inforouter/errors' require 'inforouter/version' module Inforouter class << self attr_accessor :configuration # Returns true if the gem has been configured. def configured? !!configured end # Configure the gem def configure self.configuration ||= Configuration.new yield configuration end def reset! self.configuration = nil @client = nil end def client check_configuration! @client ||= Inforouter::Client.new end private def check_configuration! fail Inforouter::Errors::MissingConfig.new unless self.configuration self.configuration.check! end end end
require 'savon' require 'inforouter/access_list' require 'inforouter/folder_rule' require 'inforouter/client' require 'inforouter/configuration' require 'inforouter/errors' require 'inforouter/version' module Inforouter class << self attr_accessor :configuration # Returns true if the gem has been configured. def configured? !!configured end # Configure the gem def configure self.configuration ||= Configuration.new yield configuration end def reset! self.configuration = nil @client = nil end def client(options = {}) check_configuration! @client ||= Inforouter::Client.new(options) end private def check_configuration! fail Inforouter::Errors::MissingConfig.new unless self.configuration self.configuration.check! end end end
Move to prepare out of initializer
module SuckerPunch class Railtie < ::Rails::Railtie initializer "sucker_punch.logger" do SuckerPunch.logger = Rails.logger ActionDispatch::Reloader.to_prepare do Celluloid::Actor.clear_registry end end end end
module SuckerPunch class Railtie < ::Rails::Railtie initializer "sucker_punch.logger" do SuckerPunch.logger = Rails.logger end config.to_prepare do Celluloid::Actor.clear_registry end end end