Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Return 404 status for non-published Budget access
class BudgetsController < ApplicationController include FeatureFlags feature_flag :budgets load_and_authorize_resource before_action :set_default_budget_filter, only: :show has_filters %w{not_unfeasible feasible unfeasible unselected selected}, only: :show respond_to :html, :js def show end def index @budgets = @budgets.order(:created_at) end end
class BudgetsController < ApplicationController include FeatureFlags include BudgetsHelper feature_flag :budgets load_and_authorize_resource before_action :set_default_budget_filter, only: :show has_filters %w{not_unfeasible feasible unfeasible unselected selected}, only: :show respond_to :html, :js def show raise ActionController::RoutingError, 'Not Found' unless budget_published?(@budget) end def index @budgets = @budgets.order(:created_at) end end
Return the new UI when reloaded from a UI instance
require "capybara" require "capybara/ui/session" require "capybara/ui/dsl" require "capybara/ui/reload" require "capybara/ui/drivers/rack_test" require "capybara/ui/drivers/poltergeist" module Capybara class UI class Error < StandardError; end class NoMatch < Error; end include Capybara::DSL attr_reader :page def self.inherited(subclass) Capybara::UI.subclasses << subclass end def self.subclasses @subclasses ||= [] end def self.for_page(page) subclass_for_page(page).new(page) end def self.subclass_for_page(page) subclasses.detect { |s| s.matches?(page) } || (raise NoMatch) end def self.find_session(&block) sessions.find(&block) end def self.sessions Capybara.send(:session_pool).values end def initialize(page) @page = page end def reload page.reload_ui end end end
require "capybara" require "capybara/ui/session" require "capybara/ui/dsl" require "capybara/ui/reload" require "capybara/ui/drivers/rack_test" require "capybara/ui/drivers/poltergeist" module Capybara class UI class Error < StandardError; end class NoMatch < Error; end include Capybara::DSL attr_reader :page def self.inherited(subclass) Capybara::UI.subclasses << subclass end def self.subclasses @subclasses ||= [] end def self.for_page(page) subclass_for_page(page).new(page) end def self.subclass_for_page(page) subclasses.detect { |s| s.matches?(page) } || (raise NoMatch) end def self.find_session(&block) sessions.find(&block) end def self.sessions Capybara.send(:session_pool).values end def initialize(page) @page = page end def reload page.reload_ui page.ui end end end
Store exception to local object for easier debugging.
# encoding: UTF-8 # Load the C-based binding. begin RUBY_VERSION =~ /(\d+.\d+)/ require "#{$1}/libxml_ruby" rescue LoadError require "libxml_ruby" end # Load Ruby supporting code. require 'libxml/error' require 'libxml/parser' require 'libxml/document' require 'libxml/namespaces' require 'libxml/namespace' require 'libxml/node' require 'libxml/attributes' require 'libxml/attr' require 'libxml/attr_decl' require 'libxml/tree' require 'libxml/html_parser' require 'libxml/sax_parser' require 'libxml/sax_callbacks' #Schema Interface require 'libxml/schema' require 'libxml/schema/type' require 'libxml/schema/element' require 'libxml/schema/attribute'
# encoding: UTF-8 # Load the C-based binding. begin RUBY_VERSION =~ /(\d+.\d+)/ require "#{$1}/libxml_ruby" rescue LoadError => e require "libxml_ruby" end # Load Ruby supporting code. require 'libxml/error' require 'libxml/parser' require 'libxml/document' require 'libxml/namespaces' require 'libxml/namespace' require 'libxml/node' require 'libxml/attributes' require 'libxml/attr' require 'libxml/attr_decl' require 'libxml/tree' require 'libxml/html_parser' require 'libxml/sax_parser' require 'libxml/sax_callbacks' #Schema Interface require 'libxml/schema' require 'libxml/schema/type' require 'libxml/schema/element' require 'libxml/schema/attribute'
Fix args not being passed to constructor
require 'prawn' require 'prawn/layout' require 'prawn/security' module Prawn module Rails module PrawnHelper def prawn_document(opts={}) pdf = (opts.delete(:renderer) || Prawn::Document).new yield pdf if block_given? pdf end end class TemplateHandler < ActionView::Template::Handler self.default_format = :pdf def self.call(template) "#{template.source.strip}.render" end end end end Mime::Type.register_alias "application/pdf", :pdf ActionView::Template.register_template_handler(:prawn, Prawn::Rails::TemplateHandler) ActionView::Base.send(:include, Prawn::Rails::PrawnHelper)
require 'prawn' require 'prawn/layout' require 'prawn/security' module Prawn module Rails module PrawnHelper def prawn_document(opts={}) pdf = (opts.delete(:renderer) || Prawn::Document).new(opts) yield pdf if block_given? pdf end end class TemplateHandler < ActionView::Template::Handler self.default_format = :pdf def self.call(template) "#{template.source.strip}.render" end end end end Mime::Type.register_alias "application/pdf", :pdf ActionView::Template.register_template_handler(:prawn, Prawn::Rails::TemplateHandler) ActionView::Base.send(:include, Prawn::Rails::PrawnHelper)
Add require of mattr_accessor since Compatibility relies on it.
module DateAndTime module Compatibility # If true, +to_time+ preserves the timezone offset of receiver. # # NOTE: With Ruby 2.4+ the default for +to_time+ changed from # converting to the local system time, to preserving the offset # of the receiver. For backwards compatibility we're overriding # this behavior, but new apps will have an initializer that sets # this to true, because the new behavior is preferred. mattr_accessor(:preserve_timezone, instance_writer: false) { false } def to_time preserve_timezone ? getlocal(utc_offset) : getlocal end end end
require 'active_support/core_ext/module/attribute_accessors' module DateAndTime module Compatibility # If true, +to_time+ preserves the timezone offset of receiver. # # NOTE: With Ruby 2.4+ the default for +to_time+ changed from # converting to the local system time, to preserving the offset # of the receiver. For backwards compatibility we're overriding # this behavior, but new apps will have an initializer that sets # this to true, because the new behavior is preferred. mattr_accessor(:preserve_timezone, instance_writer: false) { false } def to_time preserve_timezone ? getlocal(utc_offset) : getlocal end end end
Add autopoint to build server
%w{ant ant-contrib autoconf bison libtool libssl1.0.0 libssl-dev maven javacc python git-core mercurial subversion bzr git-svn make perlmagick pkg-config zip ruby rubygems librmagick-ruby}.each do |pkg| package pkg do action :install end end
%w{ant ant-contrib autoconf autopoint bison libtool libssl1.0.0 libssl-dev maven javacc python git-core mercurial subversion bzr git-svn make perlmagick pkg-config zip ruby rubygems librmagick-ruby}.each do |pkg| package pkg do action :install end end
Implement step raising an UndefinedParameterType error
class Flight attr_reader :from, :to def initialize(from, to) @from = from @to = to end end ParameterType( name: 'flight', regexp: /([A-Z]{3})-([A-Z]{3})/, transformer: -> (from, to) { Flight.new(from, to) } ) Given('{flight} has been delayed {int} minutes') do |flight, delay| expect(flight.from).to eq('LHR') expect(flight.to).to eq('CDG') expect(delay).to eq(45) end
class Flight attr_reader :from, :to def initialize(from, to) @from = from @to = to end end ParameterType( name: 'flight', regexp: /([A-Z]{3})-([A-Z]{3})/, transformer: -> (from, to) { Flight.new(from, to) } ) Given('{flight} has been delayed {int} minutes') do |flight, delay| expect(flight.from).to eq('LHR') expect(flight.to).to eq('CDG') expect(delay).to eq(45) end Given('{airport} is closed because of a strike') do |airport| raise StandardError, 'Should not be called because airport type not defined' end
Use cookie secret key from ENV
# Be sure to restart your server when you modify this file. # Your secret key is used for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. # You can use `rake secret` to generate a secure secret key. # Make sure your secret_key_base is kept private # if you're sharing your code publicly. SchemeFinderFrontend::Application.config.secret_key_base = 'f8a14991a276e1e8e70925031c5d13826838b8b7f7d4df47b36ca7f7c66d22a6be0e88cdf66f68e0c44931c7401bf301f1162066fb3d618f26eebb0ad854976c'
# Be sure to restart your server when you modify this file. # Your secret key is used for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. # You can use `rake secret` to generate a secure secret key. # Make sure your secret_key_base is kept private # if you're sharing your code publicly. SchemeFinderFrontend::Application.config.secret_key_base = ENV['COOKIE_SECRET_KEY'] || 'development'
Add test for a member with the expiration date.
require 'spec_helper' feature 'Projects > Members > Master adds member with expiration date', feature: true, js: true do include Select2Helper let!(:master) { create(:user) } let!(:project) { create(:project) } let!(:new_member) { create(:user) } background do project.team << [master, :master] login_as(master) visit namespace_project_project_members_path(project.namespace, project) end scenario 'expiration date is displayed in the members list' do page.within ".users-project-form" do select2(new_member.id, from: "#user_ids", multiple: true) fill_in "Access expiration date", with: "2016-08-02" click_on "Add users to project" end page.within ".project_member:first-child" do expect(page).to have_content("Access expires Aug 2, 2016") end end end
Apply a specific default rate to CB for container images
class Chargeback class RatesCache def get(perf) @rates ||= {} @rates[perf.hash_features_affecting_rate] ||= ChargebackRate.get_assigned_for_target(perf.resource, :tag_list => perf.tag_list_with_prefix, :parents => perf.parents_determining_rate) end end end
class Chargeback class RatesCache def get(perf) @rates ||= {} @rates[perf.hash_features_affecting_rate] ||= ChargebackRate.get_assigned_for_target(perf.resource, :tag_list => perf.tag_list_with_prefix, :parents => perf.parents_determining_rate) if perf.resource_type == Container.name && @rates[perf.hash_features_affecting_rate].empty? @rates[perf.hash_features_affecting_rate] = [ChargebackRate.find_by(:description => "Default", :rate_type => "Compute")] end @rates[perf.hash_features_affecting_rate] end end end
Set version number to 0.1.0 for initial public release.
Gem::Specification.new do |s| s.name = 'classy_hash' s.version = '0.0.1' s.license = 'MIT' s.files = ['lib/classy_hash.rb'] s.summary = 'Classy Hash: Keep your Hashes classy; a Hash schema validator' s.description = <<-DESC Classy Hash is a schema validator for Ruby Hashes. You provide a simple schema Hash, and Classy Hash will make sure your data matches, providing helpful error messages if it doesn't. DESC s.authors = ['Deseret Book', 'Mike Bourgeous'] s.email = 'mike@mikebourgeous.com' s.homepage = 'https://github.com/deseretbook/classy_hash' end
Gem::Specification.new do |s| s.name = 'classy_hash' s.version = '0.1.0' s.license = 'MIT' s.files = ['lib/classy_hash.rb'] s.summary = 'Classy Hash: Keep your Hashes classy; a Hash schema validator' s.description = <<-DESC Classy Hash is a schema validator for Ruby Hashes. You provide a simple schema Hash, and Classy Hash will make sure your data matches, providing helpful error messages if it doesn't. DESC s.authors = ['Deseret Book', 'Mike Bourgeous'] s.email = 'mike@mikebourgeous.com' s.homepage = 'https://github.com/deseretbook/classy_hash' end
Change bundle to exclude development and test
namespace :deploy do task :create_rails_directories do puts "creating log/ and tmp/ directories" Dir.chdir(Rails.root) system("mkdir -p log tmp") end task :bundle_gems => [:environment] do puts "bundling..." Dir.chdir(Rails.root) system("bundle") end task :db_migrate => [:environment] do Rake::Task['db:migrate'] end task :bounce_passenger do puts "restarting Passenger web server" Dir.chdir(Rails.root) system("touch tmp/restart.txt") end task :post_setup => [ :create_rails_directories ] task :post_deploy => [ :bundle_gems, :db_migrate, :bounce_passenger ] end
namespace :deploy do task :create_rails_directories do puts "creating log/ and tmp/ directories" Dir.chdir(Rails.root) system("mkdir -p log tmp") end task :bundle_gems => [:environment] do puts "bundling..." Dir.chdir(Rails.root) system("sudo bundle --without=development --without=test") end task :db_migrate => [:environment] do Rake::Task['db:migrate'] end task :bounce_passenger do puts "restarting Passenger web server" Dir.chdir(Rails.root) system("touch tmp/restart.txt") end task :post_setup => [ :create_rails_directories ] task :post_deploy => [ :bundle_gems, :db_migrate, :bounce_passenger ] end
Remove put that slipped into matcher
module RSpec module Sidekiq module Matchers def have_enqueued_job *expected HaveEnqueuedJob.new expected end class HaveEnqueuedJob def initialize expected @expected = expected end def description "have an enqueued #{@klass} job with arguments #{@expected}" end def failure_message "expected to have an enqueued #{@klass} job with arguments #{@expected} but none found\n\n" + "found: #{@actual}" end def matches? klass @klass = klass @actual = klass.jobs.map { |job| job["args"] } puts @actual @actual.include? @expected end def negative_failure_message "expected to not have an enqueued #{@klass} job with arguments #{@expected}" end end end end end
module RSpec module Sidekiq module Matchers def have_enqueued_job *expected HaveEnqueuedJob.new expected end class HaveEnqueuedJob def initialize expected @expected = expected end def description "have an enqueued #{@klass} job with arguments #{@expected}" end def failure_message "expected to have an enqueued #{@klass} job with arguments #{@expected} but none found\n\n" + "found: #{@actual}" end def matches? klass @klass = klass @actual = klass.jobs.map { |job| job["args"] } @actual.include? @expected end def negative_failure_message "expected to not have an enqueued #{@klass} job with arguments #{@expected}" end end end end end
Update domain_option_id primary key to bigint
class ChangeDomainOptionIdToBigint < ActiveRecord::Migration[6.0] def up change_column :domain_options, :id, :bigint end def down change_column :domain_options, :id, :integer end end
Clear IdentityMap before continue this test, we can do this here because store_full_sti_class is not supposed to change during "runtime".
require 'cases/helper' require 'models/post' require 'models/tagging' module Namespaced class Post < ActiveRecord::Base set_table_name 'posts' has_one :tagging, :as => :taggable, :class_name => 'Tagging' end end class EagerLoadIncludeFullStiClassNamesTest < ActiveRecord::TestCase def setup generate_test_objects end def generate_test_objects post = Namespaced::Post.create( :title => 'Great stuff', :body => 'This is not', :author_id => 1 ) Tagging.create( :taggable => post ) end def test_class_names old = ActiveRecord::Base.store_full_sti_class ActiveRecord::Base.store_full_sti_class = false post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging ) assert_nil post.tagging ActiveRecord::Base.store_full_sti_class = true post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging ) assert_instance_of Tagging, post.tagging ensure ActiveRecord::Base.store_full_sti_class = old end end
require 'cases/helper' require 'models/post' require 'models/tagging' module Namespaced class Post < ActiveRecord::Base set_table_name 'posts' has_one :tagging, :as => :taggable, :class_name => 'Tagging' end end class EagerLoadIncludeFullStiClassNamesTest < ActiveRecord::TestCase def setup generate_test_objects end def generate_test_objects post = Namespaced::Post.create( :title => 'Great stuff', :body => 'This is not', :author_id => 1 ) Tagging.create( :taggable => post ) end def test_class_names old = ActiveRecord::Base.store_full_sti_class ActiveRecord::Base.store_full_sti_class = false post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging ) assert_nil post.tagging ActiveRecord::IdentityMap.clear ActiveRecord::Base.store_full_sti_class = true post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging ) assert_instance_of Tagging, post.tagging ensure ActiveRecord::Base.store_full_sti_class = old end end
Set minimal Ruby version to 2.4.0
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'ra10ke/version' Gem::Specification.new do |spec| spec.name = "ra10ke" spec.version = Ra10ke::VERSION spec.authors = ["Theo Chatzimichos", "Vox Pupuli"] spec.email = ["voxpupuli@groups.io"] spec.description = %q{R10K and Puppetfile rake tasks} spec.summary = %q{Syntax check for the Puppetfile, check for outdated installed puppet modules} spec.homepage = "https://github.com/voxpupuli/ra10ke" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.require_paths = ["lib"] spec.required_ruby_version = '>= 2.1.0' spec.add_dependency "rake" spec.add_dependency "puppet_forge" spec.add_dependency "r10k" spec.add_dependency "git" spec.add_dependency "solve" spec.add_dependency 'semverse', '>= 2.0' spec.add_dependency 'table_print', '~> 1.5.6' spec.add_development_dependency 'rspec', '~> 3.6' spec.add_development_dependency 'pry' spec.add_development_dependency 'simplecov' end
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'ra10ke/version' Gem::Specification.new do |spec| spec.name = "ra10ke" spec.version = Ra10ke::VERSION spec.authors = ["Theo Chatzimichos", "Vox Pupuli"] spec.email = ["voxpupuli@groups.io"] spec.description = %q{R10K and Puppetfile rake tasks} spec.summary = %q{Syntax check for the Puppetfile, check for outdated installed puppet modules} spec.homepage = "https://github.com/voxpupuli/ra10ke" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.require_paths = ["lib"] spec.required_ruby_version = '>= 2.4.0' spec.add_dependency "rake" spec.add_dependency "puppet_forge" spec.add_dependency "r10k" spec.add_dependency "git" spec.add_dependency "solve" spec.add_dependency 'semverse', '>= 2.0' spec.add_dependency 'table_print', '~> 1.5.6' spec.add_development_dependency 'rspec', '~> 3.6' spec.add_development_dependency 'pry' spec.add_development_dependency 'simplecov' end
Add support for not Active Record based factories
require 'spec_helper' FactoryGirl.factories.map(&:name).each do |factory_name| describe "#{factory_name} factory" do it 'should be valid' do expect(build(factory_name)).to be_valid end end end
require 'spec_helper' describe 'factories' do FactoryGirl.factories.each do |factory| describe "#{factory.name} factory" do let(:entity) { build(factory.name) } it 'does not raise error when created 'do expect { entity }.to_not raise_error end it 'should be valid', if: factory.build_class < ActiveRecord::Base do expect(entity).to be_valid end end end end
Refactor version specs to suit RSpec 3 syntax.
require 'spec_helper' describe 'RDF::Sesame::VERSION' do it "should match the VERSION file" do version_file_path = File.join(File.dirname(__FILE__), '..', '..', '..', '..', 'VERSION') RDF::Sesame::VERSION.to_s.should == File.read(version_file_path).chomp end end
require 'spec_helper' describe 'RDF::Sesame::VERSION' do let(:version_file_path) do File.join(File.dirname(__FILE__), '..', '..', '..', '..', 'VERSION') end let(:version) do File.read(version_file_path).chomp end it "should match the VERSION file" do expect(RDF::Sesame::VERSION.to_s).to eq version end end
Add migration to fix column_names attribute when is not already an array
class TradeValidationRuleColumnNamesToBeArray < ActiveRecord::Migration def change unless Trade::ValidationRule.columns_hash["column_names"].array change_column :trade_validation_rules, :column_names, "varchar[] USING (string_to_array(column_names, ','))" end end end
Add explanatory comment to CloudVolumeType definition
class CloudVolumeType < ApplicationRecord include NewWithTypeStiMixin include ProviderObjectMixin acts_as_miq_taggable belongs_to :ext_management_system, :foreign_key => :ems_id, :class_name => "ExtManagementSystem" def self.class_by_ems(ext_management_system) ext_management_system && ext_management_system.class::CloudVolumeType end end
class CloudVolumeType < ApplicationRecord # CloudVolumeTypes represent various "flavors" of # volume that are available to create within a given # Storage service. include NewWithTypeStiMixin include ProviderObjectMixin acts_as_miq_taggable belongs_to :ext_management_system, :foreign_key => :ems_id, :class_name => "ExtManagementSystem" def self.class_by_ems(ext_management_system) ext_management_system && ext_management_system.class::CloudVolumeType end end
Change user for test show_other_services...
require "test_helper" require_relative 'support/ui_test_helper' class ShowOtherServicesFromServicePageTest < Capybara::Rails::TestCase include UITestHelper include Warden::Test::Helpers after { Warden.test_reset! } before do login_as users(:perico), scope: :user @service_v = Service.create!( name: "PetsServiceName", organization: organizations(:sii), spec_file: File.open(Rails.root / "test/files/sample-services/petsfull.yaml") ).create_first_version(users(:perico)) @another_service_v = Service.create!( name: "EchoService", organization: organizations(:sii), spec_file: File.open(Rails.root / "test/files/sample-services/echo.yaml") ).create_first_version(users(:perico)) end test "Switch to another service of the same organization" do visit organization_service_service_version_path( @service_v.organization, @service_v.service, @service_v ) select 'EchoService', from: 'switch_service_select' assert_content "Echos back every URL, method, parameter and header" end end
require "test_helper" require_relative 'support/ui_test_helper' class ShowOtherServicesFromServicePageTest < Capybara::Rails::TestCase include UITestHelper include Warden::Test::Helpers after { Warden.test_reset! } before do login_as users(:pedro), scope: :user @service_v = Service.create!( name: "PetsServiceName", organization: organizations(:sii), spec_file: File.open(Rails.root / "test/files/sample-services/petsfull.yaml") ).create_first_version(users(:pedro)) @another_service_v = Service.create!( name: "EchoService", organization: organizations(:sii), spec_file: File.open(Rails.root / "test/files/sample-services/echo.yaml") ).create_first_version(users(:pedro)) end test "Switch to another service of the same organization" do visit organization_service_service_version_path( @service_v.organization, @service_v.service, @service_v ) select 'EchoService', from: 'switch_service_select' assert_content "Echos back every URL, method, parameter and header" end end
Add empty line at first
require 'nokogiri' require 'open-uri' require 'terminal-table' require 'kconv' module Ruboty module Handlers class Azurjp < Base on( /(az|azur|azurlane)\s+?(?<keyword>.*?)\z/i, name: 'search', description: 'Azurlane helper' ) def search(message) headings = [] rows = [] keyword = Kconv.toutf8(message[:keyword]) uri = 'http://azurlane.wikiru.jp/index.php?%A5%AD%A5%E3%A5%E9%A5%AF%A5%BF%A1%BC%A5%EA%A5%B9%A5%C8' open(uri, 'r:EUC-JP') do |data| doc = Nokogiri::HTML(data) table = doc.xpath('//table[@id="sortabletable1"]') table_header = table.children.take(1).first table_body = table.children.drop(1) headings = table_header.children.map(&:children).map(&:children).flatten.map(&:text) table_body.each do |row| row.children.each do |tr| tmp = tr.children.map(&:text) rows << tmp if tmp.join.include?(keyword) end end end table = Terminal::Table.new(headings: headings, rows: rows) message.reply(table) end end end end
require 'nokogiri' require 'open-uri' require 'terminal-table' require 'kconv' module Ruboty module Handlers class Azurjp < Base on( /(az|azur|azurlane)\s+?(?<keyword>.*?)\z/i, name: 'search', description: 'Azurlane helper' ) def search(message) headings = [] rows = [] keyword = Kconv.toutf8(message[:keyword]) uri = 'http://azurlane.wikiru.jp/index.php?%A5%AD%A5%E3%A5%E9%A5%AF%A5%BF%A1%BC%A5%EA%A5%B9%A5%C8' open(uri, 'r:EUC-JP') do |data| doc = Nokogiri::HTML(data) table = doc.xpath('//table[@id="sortabletable1"]') table_header = table.children.take(1).first table_body = table.children.drop(1) headings = table_header.children.map(&:children).map(&:children).flatten.map(&:text) table_body.each do |row| row.children.each do |tr| tmp = tr.children.map(&:text) rows << tmp if tmp.join.include?(keyword) end end end table = Terminal::Table.new(headings: headings, rows: rows) message.reply('\n' + table) end end end end
Fix comparison of jobs for reload with hash args
module Sidekiq module Dejavu class Manager include Helper attr_reader :schedules def initialize(schedules) @schedules = schedules end def reload_schedule! clear_changed_schedules add_new_schedules end private def clear_changed_schedules scheduled_jobs.each do |job| item = job.item name = item['schedule'] schedule_options = schedules[name] item_options = item.select { |k,v| schedule_options.keys.include? k } if item_options != schedule_options Sidekiq.logger.info "Clearing schedule #{name} (config changed)." job.delete else schedules.delete(name) end end end def add_new_schedules schedules.each do |name, options| args = Array(options['args']) interval = options['interval'] first_run = next_randomized_timestamp(interval) job = options.merge('args' => args, 'schedule' => name, 'at' => first_run) Sidekiq.logger.info "Scheduling #{name} for first run at #{Time.at first_run}." Sidekiq::Client.push(job) end end def scheduled_jobs Sidekiq::ScheduledSet.new.select { |job| schedules.keys.include? job.item['schedule'] } end end end end
module Sidekiq module Dejavu class Manager include Helper attr_reader :schedules def initialize(schedules) @schedules = schedules end def reload_schedule! clear_changed_schedules add_new_schedules end private def clear_changed_schedules scheduled_jobs.each do |job| item = job.item name = item['schedule'] schedule_options = schedules[name] schedule_options['args'] = Array(schedule_options['args']) item_options = item.select { |k,v| schedule_options.keys.include? k } if item_options != schedule_options Sidekiq.logger.info "Clearing schedule #{name} (config changed)." job.delete else schedules.delete(name) end end end def add_new_schedules schedules.each do |name, options| args = Array(options['args']) interval = options['interval'] first_run = next_randomized_timestamp(interval) job = options.merge('args' => args, 'schedule' => name, 'at' => first_run) Sidekiq.logger.info "Scheduling #{name} for first run at #{Time.at first_run}." Sidekiq::Client.push(job) end end def scheduled_jobs Sidekiq::ScheduledSet.new.select { |job| schedules.keys.include? job.item['schedule'] } end end end end
Add basic integration test for plan categories tab
# frozen_string_literal: true require "test_helper" module GobiertoAdmin module GobiertoPlans module Categories class CategoriesIndexTest < ActionDispatch::IntegrationTest include Integration::AdminGroupsConcern def setup super @path = admin_plans_plan_categories_path(plan) end def admin @admin ||= gobierto_admin_admins(:nick) end def site @site ||= sites(:madrid) end def plan @plan ||= gobierto_plans_plans(:strategic_plan) end def test_admin_categories_index with_signed_in_admin(admin) do with_current_site(site) do visit @path within "div.pure-u-md-1-3", text: "Global progress" do within "div.metric_value" do assert has_content? "25%" end end end end end end end end end
Fix regex in version number pattern.
#!/usr/bin/env ruby require_relative 'shell.rb' # see http://stackoverflow.com/a/3545363 mvn_command = 'mvn org.apache.maven.plugins:maven-help-plugin:evaluate -Dexpression=project.version' mvn_stdout = shell(mvn_command) version_pattern = /^(\d+.*-)(\d)$/ if mvn_stdout !~ version_pattern puts mvn_stdout raise "version number #{version_pattern} not found" end puts "found version #{$1}#{$2}" version = $1 build = $2.to_i new_build = (build + 1).to_s new_version = version + new_build puts "will set new version #{new_version}" mvn_command = "mvn versions:set -DnewVersion=#{new_version}" shell(mvn_command)
#!/usr/bin/env ruby require_relative 'shell.rb' # requires Ruby 1.9 # see http://stackoverflow.com/a/3545363 mvn_command = 'mvn org.apache.maven.plugins:maven-help-plugin:evaluate -Dexpression=project.version' mvn_stdout = shell(mvn_command) version_pattern = /^(\d+.*-)(\d+)$/ if mvn_stdout !~ version_pattern puts mvn_stdout raise "version number #{version_pattern} not found" end puts "found version #{$1}#{$2}" version = $1 build = $2.to_i new_build = (build + 1).to_s new_version = version + new_build puts "will set new version #{new_version}" mvn_command = "mvn versions:set -DnewVersion=#{new_version}" shell(mvn_command)
Remove git command from gemspec
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'klarna/checkout/version' Gem::Specification.new do |spec| spec.name = "klarna-checkout" spec.version = Klarna::Checkout::VERSION spec.authors = ["Theodor Tonum"] spec.email = ["theodor@tonum.no"] spec.description = %q{Ruby Wrapper for Klarna Checkout Rest API} spec.summary = %q{...} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency "faraday" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" spec.add_development_dependency "guard" spec.add_development_dependency "guard-rspec" spec.add_development_dependency "webmock" spec.add_development_dependency "vcr" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'klarna/checkout/version' Gem::Specification.new do |spec| spec.name = "klarna-checkout" spec.version = Klarna::Checkout::VERSION spec.authors = ["Theodor Tonum"] spec.email = ["theodor@tonum.no"] spec.description = %q{Ruby Wrapper for Klarna Checkout Rest API} spec.summary = %q{...} spec.homepage = "" spec.license = "MIT" spec.files = Dir['LICENSE.txt', 'README.md', 'lib/**/*'] spec.test_files = Dir['spec/**/*'] spec.require_paths = ["lib"] spec.add_dependency "faraday" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" spec.add_development_dependency "guard" spec.add_development_dependency "guard-rspec" spec.add_development_dependency "webmock" spec.add_development_dependency "vcr" end
Update pod spec to 0.1.6
Pod::Spec.new do |s| s.name = 'SSPPullToRefresh' s.version = '0.1.5' s.summary = 'General classes for "Pull-To-Refresh" concept customisation' s.description = <<-DESC This general classes provide for client the possbility to make own derived implementations DESC s.homepage = 'https://github.com/Sergey-Lomov/SSPPullToRefresh' s.author = { 'Sergey Lomov' => 'SSpirit10000@gmail.com' } s.license = { :type => 'MIT', :file => 'LICENSE' } s.source = { :git => 'https://github.com/Sergey-Lomov/SSPPullToRefresh.git', :tag => s.version.to_s } s.ios.deployment_target = '10.1' s.source_files = 'SSPPullToRefresh/*.swift' end
Pod::Spec.new do |s| s.name = 'SSPPullToRefresh' s.version = '0.1.6' s.summary = 'General classes for "Pull-To-Refresh" concept customisation' s.description = <<-DESC This general classes provide for client the possbility to make own derived implementations DESC s.homepage = 'https://github.com/Sergey-Lomov/SSPPullToRefresh' s.author = { 'Sergey Lomov' => 'SSpirit10000@gmail.com' } s.license = { :type => 'MIT', :file => 'LICENSE' } s.source = { :git => 'https://github.com/Sergey-Lomov/SSPPullToRefresh.git', :tag => s.version.to_s } s.ios.deployment_target = '10.1' s.source_files = 'SSPPullToRefresh/*.swift' end
Fix broken test case for plan fetcher
require 'test_helper' require 'locker_room/plan_fetcher' class PlanFetcherTest < ActionDispatch::IntegrationTest def setup @plan = mock('Plan', :id => 'foo1', :name => 'Starter', :price => '9.95') end def test_creation_by_store_plans_locally @plan.expects(:id).returns('foo1').once Braintree::Plan.expects(:all).returns([@plan]) LockerRoom::Plan.expects(:find_by) .with(:braintree_id => 'foo1').returns(nil) LockerRoom::Plan.expects(:create).with( :braintree_id => 'foo1', :name => 'Starter', :price => '9.95' ) LockerRoom::PlanFetcher.store_plans_locally end def test_update_by_store_plans_locally @plan.expects(:update_attributes).with( :name => 'Starter', :price => '9.95' ).once Braintree::Plan.expects(:all).returns([@plan]) LockerRoom::Plan.expects(:find_by) .with(:braintree_id => 'foo1').returns(@plan) LockerRoom::Plan.expects(:create).never LockerRoom::PlanFetcher.store_plans_locally end end
require 'test_helper' require 'locker_room/plan_fetcher' class PlanFetcherTest < ActionDispatch::IntegrationTest def setup @plan = mock('Plan', :id => 'foo1', :name => 'Starter', :price => '9.95') end def test_creation_by_store_plans_locally @plan.expects(:id).returns('foo1').once Braintree::Plan.expects(:all).returns([@plan]) LockerRoom::Plan.expects(:find_by) .with(:braintree_id => 'foo1').returns(nil) LockerRoom::Plan.expects(:create!).with( :braintree_id => 'foo1', :name => 'Starter', :price => '9.95' ) LockerRoom::PlanFetcher.store_plans_locally end def test_update_by_store_plans_locally @plan.expects(:update_attributes!).with( :name => 'Starter', :price => '9.95' ).once Braintree::Plan.expects(:all).returns([@plan]) LockerRoom::Plan.expects(:find_by) .with(:braintree_id => 'foo1').returns(@plan) LockerRoom::Plan.expects(:create!).never LockerRoom::PlanFetcher.store_plans_locally end end
Add "vim" directory to gemspec
require File.expand_path('../lib/vimrunner/version', __FILE__) Gem::Specification.new do |s| s.name = 'vimrunner' s.version = Vimrunner::VERSION s.platform = Gem::Platform::RUBY s.authors = ['Andrew Radev'] s.email = ['andrey.radev@gmail.com'] s.homepage = 'http://github.com/AndrewRadev/vimrunner' s.summary = 'Lets you control a vim instance through ruby' s.description = <<-D Using vim's client/server functionality, this library exposes a way to spawn a vim instance and control it programatically. Apart from being a fun party trick, this could be used to do integration testing on vimscript. D s.add_development_dependency 'pry' s.add_development_dependency 'rake' s.add_development_dependency 'rdoc' s.add_development_dependency 'rspec', '>= 2.0.0' s.required_rubygems_version = '>= 1.3.6' s.rubyforge_project = 'vimrunner' s.files = Dir['{lib}/**/*.rb', 'bin/*', 'LICENSE', '*.md'] s.require_path = 'lib' s.executables = ['vimrunner'] end
require File.expand_path('../lib/vimrunner/version', __FILE__) Gem::Specification.new do |s| s.name = 'vimrunner' s.version = Vimrunner::VERSION s.platform = Gem::Platform::RUBY s.authors = ['Andrew Radev'] s.email = ['andrey.radev@gmail.com'] s.homepage = 'http://github.com/AndrewRadev/vimrunner' s.summary = 'Lets you control a vim instance through ruby' s.description = <<-D Using vim's client/server functionality, this library exposes a way to spawn a vim instance and control it programatically. Apart from being a fun party trick, this could be used to do integration testing on vimscript. D s.add_development_dependency 'pry' s.add_development_dependency 'rake' s.add_development_dependency 'rdoc' s.add_development_dependency 'rspec', '>= 2.0.0' s.required_rubygems_version = '>= 1.3.6' s.rubyforge_project = 'vimrunner' s.files = Dir['lib/**/*.rb', 'vim/*', 'bin/*', 'LICENSE', '*.md'] s.require_path = 'lib' s.executables = ['vimrunner'] end
Fix nil.object_id (which is incredibly 4!)
class NilClass def &(other) false end def |(other) `other !== false && other != null` end def ^(other) `other !== false && other != null` end def ==(other) `other == null` end def as_json self end def dup raise TypeError end def inspect 'nil' end def nil? true end def singleton_class NilClass end def to_a [] end def to_h `__opal.hash()` end def to_i 0 end alias to_f to_i def to_json 'null' end def to_n `null` end def to_s '' end end
class NilClass def &(other) false end def |(other) `other !== false && other != null` end def ^(other) `other !== false && other != null` end def ==(other) `other == null` end def as_json self end def dup raise TypeError end def inspect 'nil' end def nil? true end def singleton_class NilClass end def to_a [] end def to_h `__opal.hash()` end def to_i 0 end alias to_f to_i def to_json 'null' end def to_n `null` end def to_s '' end def object_id `#{NilClass}._id || (#{NilClass}._id = Opal.uid())` end end
Use node['users'] to get master list of users in data_bag_acccounts.
# # Cookbook Name:: user # Recipe:: data_bag_accounts # # Copyright 2011, Fletcher Nichol # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # users = begin data_bag('users') rescue => ex Chef::Log.warn "Data bag users was not loaded due to: #{ex.inspect}, so skipping" [] end users.each do |i| u = data_bag_item('users', i) user_account u['id'] do %w{comment uid gid home shell password system_user manage_home create_group ssh_keys ssh_keygen}.each do |attr| send(attr, u[attr]) if u[attr] end action u['action'].to_sym if u['action'] end end
# # Cookbook Name:: user # Recipe:: data_bag_accounts # # Copyright 2011, Fletcher Nichol # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # users = begin data_bag('users') rescue => ex Chef::Log.warn "Data bag users was not loaded due to: #{ex.inspect}, so skipping" [] end Array(node['users']).each do |i| u = data_bag_item('users', i) user_account u['id'] do %w{comment uid gid home shell password system_user manage_home create_group ssh_keys ssh_keygen}.each do |attr| send(attr, u[attr]) if u[attr] end action u['action'].to_sym if u['action'] end end
Revert "Reverting "Data migration to add mainstream categories for DCMS""
[ ['Development of the arts, sport and heritage for local communities', 'Guidance and relevant data for local authorities, private investors and grant-making bodies.', 'housing/local-councils', 'Local councils and services'], ['Understanding and asserting your statutory rights', 'Duties of government and local authorities to uphold equality and provide services to citizens.', 'citizenship/government', 'Living in the UK, government and democracy'] ].each do |row| title, description, parent_tag, parent_title = row category = MainstreamCategory.create( title: title, slug: title.parameterize, parent_tag: parent_tag, parent_title: parent_title, description: description ) if category puts "Mainstream category '#{category.title}' created" end end
Clear session before each scenario
Before('@smoke-tests') do @SMOKE_TESTS = true end
Before('@smoke-tests') do @SMOKE_TESTS = true end Before do Capybara.reset_sessions! end
Update conditional display of three partials: * if logged out, display squeeze partial. * if logged in and no active project, display new project form. * if logged in and active project, display current project partial.
class GlobalController < ApplicationController def index if current_user render "projects/_current_project" else render "_squeeze" end end private def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end def active_project if current_user projects = current_user.projects if projects.empty? false else projects.last.active end end end end
class GlobalController < ApplicationController def index if current_user && active_project render "projects/_current_project" elsif current_user && (active_project == false) @user = current_user @project = Project.new render "projects/_new" else render "_squeeze" end end private def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end def active_project if current_user projects = current_user.projects if projects.empty? false else projects.last.active end end end end
Fix typo and make class explicit
# Operator for `inet` columns in a PostgreSQL database, which operates on formatted values using # {MetasploitDataModels::Search::Operation::IPAddress}. class MetasploitDataModels::Search::Operator::IPAddress < Metasploit::Model::Search::Operator::Single # # Attributes # # @!attribute [r] attribute # The attribute on `Metasploit::Model::Search::Operator::Base#klass` that is searchable. # # @return [Symbol] the attribute name attr_accessor :attribute # # Validations # validates :attribute, presence: true # # Instance Methods # alias_method :name, :attribute # The class used for `#operte_on`. # # @return [String] `'MetasploitDataModels::Search::Operation::IPAddress'` def operation_class_name @operation_class_name ||= 'MetasploitDataModels::Search::Operation::IPAddress' end # @return [Symbol] `:ip_address` def type :ip_address end end
# Operator for `inet` columns in a PostgreSQL database, which operates on formatted values using # {MetasploitDataModels::Search::Operation::IPAddress}. class MetasploitDataModels::Search::Operator::IPAddress < Metasploit::Model::Search::Operator::Single # # Attributes # # @!attribute [r] attribute # The attribute on `Metasploit::Model::Search::Operator::Base#klass` that is searchable. # # @return [Symbol] the attribute name attr_accessor :attribute # # Validations # validates :attribute, presence: true # # Instance Methods # alias_method :name, :attribute # The class used for `Metasploit::Model::Search::Operator::Single#operate_on`. # # @return [String] `'MetasploitDataModels::Search::Operation::IPAddress'` def operation_class_name @operation_class_name ||= 'MetasploitDataModels::Search::Operation::IPAddress' end # @return [Symbol] `:ip_address` def type :ip_address end end
Implement delegate action to services
# frozen_string_literal: true module Course::Assessment::SubmissionControllerServiceConcern extend ActiveSupport::Concern private # Get the service class based on the assessment display mode. # # @return [Class] The class of the service. def service_class case @assessment.display_mode when 'guided' Course::Assessment::Submission::GuidedService when 'worksheet' Course::Assessment::Submission::WorksheetService end end # Instantiate a service based on the assessment display mode. # # @return [Course::Assessment::SubmissionService] The service instance. def service service_class.new(self, assessment: @assessment, submission: @submission) end # Extract the defined instance variables from the service, so that views can access them. # Call this method at the end of the action if there are any instance variables defined in the # action. # @param [Course::Assessment::SubmissionService] service the service instance. def extract_instance_variables(service) service.instance_variables.each do |name| value = service.instance_variable_get(name) instance_variable_set(name, value) end end module ClassMethods # Delegate the action to the service and extract the instance variables from the service after # the action is done. # @param [Symbol] action the name of the action to delegate. def delegate_to_service(action) define_method(action) do service.public_send(action) extract_instance_variables(service) end end end end
Add extra framework dependacies added in the new version
Pod::Spec.new do |s| s.name = "Ubertesters" s.version = "3.0.4" s.summary = "Mobile beta testing solution" s.homepage = "https://github.com/sciutand/UbertestersSDK" s.description = "Pod to use Ubertesters via CocoaPods. Currently using the latest version 2.0.4" s.license = {:type => 'MIT', :file => 'LICENSE'} s.author = {"Andrea Sciutto" => "sciutand@gmail.com"} s.platform = :ios, "6.0" s.source = {:git => "https://github.com/sciutand/UbertestersSDK.git", :tag => s.version.to_s } s.source_files = "UbertestersSDK.framework/Versions/A/Headers/*.h" s.vendored_frameworks = "UbertestersSDK.framework" s.preserve_paths = "*.framework" s.frameworks = "AdSupport", "QuartzCore", "CoreImage", "SystemConfiguration", "CoreTelephony", "CoreLocation", "AudioToolbox", "OpenGLES", "CoreMotion" s.requires_arc = true end
Pod::Spec.new do |s| s.name = "Ubertesters" s.version = "3.0.4" s.summary = "Mobile beta testing solution" s.homepage = "https://github.com/sciutand/UbertestersSDK" s.description = "Pod to use Ubertesters via CocoaPods. Currently using the latest version 2.0.4" s.license = {:type => 'MIT', :file => 'LICENSE'} s.author = {"Andrea Sciutto" => "sciutand@gmail.com"} s.platform = :ios, "6.0" s.source = {:git => "https://github.com/sciutand/UbertestersSDK.git", :tag => s.version.to_s } s.source_files = "UbertestersSDK.framework/Versions/A/Headers/*.h" s.vendored_frameworks = "UbertestersSDK.framework" s.preserve_paths = "*.framework" s.frameworks = "AdSupport", "QuartzCore", "CoreImage", "SystemConfiguration", "CoreTelephony", "CoreLocation", "AudioToolbox", "OpenGLES", "CoreMotion", "MediaPlayer", "CoreMedia" s.requires_arc = true end
Update professor spec to use safe deletion
require 'rails_helper' RSpec.describe Professor, type: :model do describe '::TBA', slow: true do it 'creates a TBA record when called the first time' do Professor.where(name: 'TBA').destroy_all expect { Professor.TBA }.to change { Professor.count }.by(1) end it 'does not create a new record when it has already been called' do Professor.TBA expect { Professor.TBA }.to_not change { Professor.count } end end end
require 'rails_helper' RSpec.describe Professor, type: :model do describe '::TBA', slow: true do it 'creates a TBA record when called the first time' do safe_delete_professors('TBA') expect { Professor.TBA }.to change { Professor.count }.by(1) end it 'does not create a new record when it has already been called' do Professor.TBA expect { Professor.TBA }.to_not change { Professor.count } end end end
Fix shopping cart to not use strong params
class Api::V2::CartItemsController < Api::BaseController include Api::V2::CartItemsHelper before_action :require_cart def create # If person logged in, make them the default item owner if current_user params[:owner_id] = current_user.id params[:owner_type] = current_user.class.name end item = @cart.item_from_attributes(params.to_unsafe_h) authorize!(:add_proposal_to_cart, item) if item.is_a?(Proposal) @item = @cart.add_item(params.to_unsafe_h) @owner = @item.try(:owner) render 'api/v2/cart_items/show' end def update index = params[:id].to_i item = @cart.item_from_attributes(@cart.items[index]) raise CanCan::AccessDenied if item.is_a?(Proposal) # authorize!(:modify_proposal, item) if item.is_a?(Proposal) @item = @cart.update_item(index, params) render 'api/v2/cart_items/show' end def destroy index = params[:id].to_i @cart.remove_item(index) head :no_content end private def require_cart @cart = ::ShoppingCart.find_by!(uid: params[:uid]) end end
class Api::V2::CartItemsController < Api::BaseController include Api::V2::CartItemsHelper before_action :require_cart def create # If person logged in, make them the default item owner if current_user params[:owner_id] = current_user.id params[:owner_type] = current_user.class.name end item = @cart.item_from_attributes(params.to_unsafe_h) authorize!(:add_proposal_to_cart, item) if item.is_a?(Proposal) @item = @cart.add_item(params.to_unsafe_h) @owner = @item.try(:owner) render 'api/v2/cart_items/show' end def update index = params[:id].to_i item = @cart.item_from_attributes(@cart.items[index]) raise CanCan::AccessDenied if item.is_a?(Proposal) # authorize!(:modify_proposal, item) if item.is_a?(Proposal) @item = @cart.update_item(index, params.to_unsafe_h) render 'api/v2/cart_items/show' end def destroy index = params[:id].to_i @cart.remove_item(index) head :no_content end private def require_cart @cart = ::ShoppingCart.find_by!(uid: params[:uid]) end end
Revert "add debug for action mailer"
# Set SMTP settings if given. p Errbit::Config.email_delivery_method if Errbit::Config.email_delivery_method == :smtp ActionMailer::Base.delivery_method = :smtp p "In base settings" ActionMailer::Base.smtp_settings = { :address => Errbit::Config.smtp_address, :port => Errbit::Config.smtp_port, :authentication => Errbit::Config.smtp_authentication, :user_name => Errbit::Config.smtp_user_name, :password => Errbit::Config.smtp_password, :domain => Errbit::Config.smtp_domain, } end if Errbit::Config.email_delivery_method == :sendmail sendmail_settings = {} sendmail_settings[:location] = Errbit::Config.sendmail_location if Errbit::Config.sendmail_location sendmail_settings[:arguments] = Errbit::Config.sendmail_arguments if Errbit::Config.sendmail_arguments ActionMailer::Base.delivery_method = :sendmail ActionMailer::Base.sendmail_settings = sendmail_settings end # Set config specific values (ActionMailer::Base.default_url_options ||= {}).tap do |default| options_from_config = { host: Errbit::Config.host, port: Errbit::Config.port, protocol: Errbit::Config.protocol }.select { |k, v| v } p "default values" p default_values p "merging with" p options_from_config default.reverse_merge!(options_from_config) end
# Set SMTP settings if given. if Errbit::Config.email_delivery_method == :smtp ActionMailer::Base.delivery_method = :smtp ActionMailer::Base.smtp_settings = { :address => Errbit::Config.smtp_address, :port => Errbit::Config.smtp_port, :authentication => Errbit::Config.smtp_authentication, :user_name => Errbit::Config.smtp_user_name, :password => Errbit::Config.smtp_password, :domain => Errbit::Config.smtp_domain, } end if Errbit::Config.email_delivery_method == :sendmail sendmail_settings = {} sendmail_settings[:location] = Errbit::Config.sendmail_location if Errbit::Config.sendmail_location sendmail_settings[:arguments] = Errbit::Config.sendmail_arguments if Errbit::Config.sendmail_arguments ActionMailer::Base.delivery_method = :sendmail ActionMailer::Base.sendmail_settings = sendmail_settings end # Set config specific values (ActionMailer::Base.default_url_options ||= {}).tap do |default| options_from_config = { host: Errbit::Config.host, port: Errbit::Config.port, protocol: Errbit::Config.protocol }.select { |k, v| v } default.reverse_merge!(options_from_config) end
Build comment off of resource in new comments action.
class CommentsController < ApplicationController def new @comment = Comment.new end end
class CommentsController < ApplicationController def new @resource = Resource.find_by(id: params[:resource_id]) @comment = @resource.comments.build end end
Improve way to respond action if Ajax or not
# # == ContactsController # class ContactsController < ApplicationController before_action :set_mapbox_options, only: [:new, :create], if: proc { @setting.show_map } skip_before_action :allow_cors def index redirect_to new_contact_path end def new @contact_form = ContactForm.new seo_tag_index category end def create if params[:contact_form][:nickname].blank? @contact_form = ContactForm.new(params[:contact_form]) @contact_form.request = request if @contact_form.deliver respond_action 'create' else render :new end else respond_action 'create' end end private def respond_action(template) flash.now[:success] = I18n.t('contact.success') respond_to do |format| format.html { redirect_to new_contact_path, notice: I18n.t('contact.success') } format.js { render template } end end def set_mapbox_options gon_params end end
# # == ContactsController # class ContactsController < ApplicationController before_action :set_mapbox_options, only: [:new, :create], if: proc { @setting.show_map } skip_before_action :allow_cors def index redirect_to new_contact_path end def new @contact_form = ContactForm.new seo_tag_index category end def create if params[:contact_form][:nickname].blank? @contact_form = ContactForm.new(params[:contact_form]) @contact_form.request = request if @contact_form.deliver respond_action :create else render :new end else respond_action :create end end private def respond_action(template) flash.now[:success] = I18n.t('contact.success') respond_to do |format| format.html { redirect_to new_contact_path, notice: I18n.t('contact.success') } format.js { render template } end end def set_mapbox_options gon_params end end
Allow Identity to function without HEROKU_COOKIE_DOMAIN
module Identity Main = Rack::Builder.new do use Rack::Instruments use Rack::SSL if Config.production? # general cookie storing information of the logged in user; should be # scoped to the app's specific domain use Rack::Session::Cookie, domain: Config.cookie_domain, path: '/', expire_after: 2592000, secret: Config.secure_key # cookie with a domain scoped to all heroku domains, used to set a session # nonce value so that consumers can recognize when the logged in user has # changed use Rack::Session::Cookie, domain: Config.heroku_cookie_domain, expire_after: 2592000, key: 'rack.session.heroku', secret: Config.secure_key use Rack::Csrf, skip: ["POST:/oauth/.*"] use Rack::Flash run Sinatra::Router.new { mount Identity::Account mount Identity::Assets mount Identity::Auth run Sinatra.new { get "/" do redirect to("/sessions/new") end not_found do "fml" end } } end end
module Identity Main = Rack::Builder.new do use Rack::Instruments use Rack::SSL if Config.production? # general cookie storing information of the logged in user; should be # scoped to the app's specific domain use Rack::Session::Cookie, domain: Config.cookie_domain, path: '/', expire_after: 2592000, secret: Config.secure_key # cookie with a domain scoped to all heroku domains, used to set a session # nonce value so that consumers can recognize when the logged in user has # changed if Config.heroku_cookie_domain use Rack::Session::Cookie, domain: Config.heroku_cookie_domain, expire_after: 2592000, key: 'rack.session.heroku', secret: Config.secure_key end use Rack::Csrf, skip: ["POST:/oauth/.*"] use Rack::Flash run Sinatra::Router.new { mount Identity::Account mount Identity::Assets mount Identity::Auth run Sinatra.new { get "/" do redirect to("/sessions/new") end not_found do "fml" end } } end end
Make sure multi_json is used to encode/decode json
require 'snappy' module Ripple module SnappySerializer extend self def dump(obj) Snappy.deflate obj.to_json(Riak.json_options) end def load(binary) Riak::JSON.parse(Snappy.inflate binary) end end end Riak::Serializers['application/x-snappy'] = Ripple::SnappySerializer
require 'snappy' module Ripple module SnappySerializer extend self def dump(obj) Snappy.deflate Riak::JSON.encode(obj) end def load(binary) Riak::JSON.parse(Snappy.inflate binary) end end end Riak::Serializers['application/x-snappy'] = Ripple::SnappySerializer
Delete unused step definition for multiple feature flags
And(/^I submit an opportunity with title "(.*?)" and description "(.*?)"$/) do |title, description| fill_in 'Title', :with => title fill_in 'Description', :with => description click_on 'Create a Volunteer Opportunity' end Given(/^that the (.+) flag is (enabled|disabled)$/) do |feature, state| if f = Feature.find_by_name(feature) then f.update_attributes(active: (state == 'enabled')) else Feature.create!(name: feature, active: (state == 'enabled')) end end # Given /the following feature flags exist/ do |feature_flags_table| # feature_flags_table.hashes.each do |feature_flag| # Feature.create! feature_flag # end # end
And(/^I submit an opportunity with title "(.*?)" and description "(.*?)"$/) do |title, description| fill_in 'Title', :with => title fill_in 'Description', :with => description click_on 'Create a Volunteer Opportunity' end Given(/^that the (.+) flag is (enabled|disabled)$/) do |feature, state| if f = Feature.find_by_name(feature) then f.update_attributes(active: (state == 'enabled')) else Feature.create!(name: feature, active: (state == 'enabled')) end end
Fix a typo in the wt_cam attributes file
# # Author:: Kendrick Martin(<kendrick.martin@webtrends.com>) # Cookbook Name:: wt_cam # Attribute:: default # # Copyright 2012, Webtrends Inc. # default['wt_cam']['app_pool'] = "CAM" default['wt_cam'][['cam']'download_url'] = "" default['wt_cam']['cam_plugins']['download_url'] = "" default['wt_cam']['db_server'] = "(local)" default['wt_cam']['db_name'] = "Cam" default['wt_cam']['tokenExpirationMinutes'] = 60 default['wt_cam']['port'] = 80 default['wt_cam']['log_level'] = "INFO"
# # Author:: Kendrick Martin(<kendrick.martin@webtrends.com>) # Cookbook Name:: wt_cam # Attribute:: default # # Copyright 2012, Webtrends Inc. # default['wt_cam']['app_pool'] = "CAM" default['wt_cam']['download_url'] = "" default['wt_cam']['cam_plugins']['download_url'] = "" default['wt_cam']['db_server'] = "(local)" default['wt_cam']['db_name'] = "Cam" default['wt_cam']['tokenExpirationMinutes'] = 60 default['wt_cam']['port'] = 80 default['wt_cam']['log_level'] = "INFO"
Add devise default modules to User
class User < ApplicationRecord end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable end
Fix failing logger middleware specs
require 'spec_helper' describe Protobuf::Rpc::Middleware::Logger do let(:app) { Proc.new { |env| env } } let(:env) { Protobuf::Rpc::Env.new } subject { described_class.new(app) } describe "#call" do it "calls the stack" do app.should_receive(:call).with(env) subject.call(env) end it "returns the env" do subject.call(env).should eq env end end end
require 'spec_helper' describe Protobuf::Rpc::Middleware::Logger do let(:app) { Proc.new { |env| env } } let(:env) { Protobuf::Rpc::Env.new( 'caller' => 'caller.test.co', 'encoded_request' => request_wrapper.encode, 'encoded_response' => response_wrapper.encode, 'method_name' => method_name, 'request' => request, 'request_type' => rpc_method.request_type, 'response' => response, 'response_type' => rpc_method.response_type, 'rpc_method' => rpc_method, 'rpc_service' => service_class, 'service_name' => service_name, ) } let(:method_name) { :find } let(:request) { request_type.new(:name => 'required') } let(:request_type) { rpc_method.request_type } let(:request_wrapper) { Protobuf::Socketrpc::Request.new( :service_name => service_name, :method_name => method_name.to_s, :request_proto => request ) } let(:response_wrapper) { Protobuf::Socketrpc::Response.new(:response_proto => response) } let(:response) { rpc_method.response_type.new(:name => 'required') } let(:rpc_method) { service_class.rpcs[method_name] } let(:rpc_service) { service_class.new(env) } let(:service_class) { Test::ResourceService } let(:service_name) { service_class.to_s } subject { described_class.new(app) } describe "#call" do it "calls the stack" do app.should_receive(:call).with(env) subject.call(env) end it "returns the env" do subject.call(env).should eq env end end end
Fix bug uploading files for patents
class PatentsController < MyplaceonlineController def may_upload true end protected def insecure true end def sorts ["patents.publication_date DESC NULLS LAST", "lower(patents.patent_name) ASC"] end def obj_params params.require(:patent).permit( :patent_name, :patent_number, :authors, :region, :filed_date, :publication_date, :patent_abstract, :patent_text, :notes, test_object_files_attributes: FilesController.multi_param_names ) end end
class PatentsController < MyplaceonlineController def may_upload true end protected def insecure true end def sorts ["patents.publication_date DESC NULLS LAST", "lower(patents.patent_name) ASC"] end def obj_params params.require(:patent).permit( :patent_name, :patent_number, :authors, :region, :filed_date, :publication_date, :patent_abstract, :patent_text, :notes, patent_files_attributes: FilesController.multi_param_names ) end end
Make sure we don't re-use test classes
# Generators register themself on the CLI module require "test_helper" require "roger/testing/mock_project" class RogerfileLoadedError < StandardError end module Roger # Test Roger Release class ReleaseTest < ::Test::Unit::TestCase def setup @project = Testing::MockProject.new end def teardown @project.destroy end def test_load_rogerfile @project.construct.file "Rogerfile", "raise RogerfileLoadedError" rogerfile = Roger::Rogerfile.new(@project) assert_raise(RogerfileLoadedError) do rogerfile.load end end def test_loaded_rogerfile @project.construct.file "Rogerfile", "" rogerfile = Roger::Rogerfile.new(@project) rogerfile.load assert rogerfile.loaded? end end end
# Generators register themself on the CLI module require "test_helper" require "roger/testing/mock_project" class RogerfileLoadedError < StandardError end module Roger # Test Roger Release class MockupFileTest < ::Test::Unit::TestCase def setup @project = Testing::MockProject.new end def teardown @project.destroy end def test_load_rogerfile @project.construct.file "Rogerfile", "raise RogerfileLoadedError" rogerfile = Roger::Rogerfile.new(@project) assert_raise(RogerfileLoadedError) do rogerfile.load end end def test_loaded_rogerfile @project.construct.file "Rogerfile", "" rogerfile = Roger::Rogerfile.new(@project) rogerfile.load assert rogerfile.loaded? end end end
Allow usage of :focus=> true to speedup TDD
require File.expand_path('../../lib/active_pdftk', __FILE__) require 'rspec' Dir[File.expand_path(File.join(File.dirname(__FILE__),'support','**','*.rb'))].each {|f| require f} RSpec.configure do |config| config.before(:each) do if ENV['embeded_pdftk'] == "true" ActivePdftk::Call.stub(:locate_pdftk).and_return(File.dirname(__FILE__) + '/support/pdftk') end end end
require File.expand_path('../../lib/active_pdftk', __FILE__) require 'rspec' Dir[File.expand_path(File.join(File.dirname(__FILE__),'support','**','*.rb'))].each {|f| require f} RSpec.configure do |config| config.before(:each) do if ENV['embeded_pdftk'] == "true" ActivePdftk::Call.stub(:locate_pdftk).and_return(File.dirname(__FILE__) + '/support/pdftk') end end config.filter_run :focus => true config.run_all_when_everything_filtered = true end
Use `if_not_exists` instead of `table_exists?`
class CreateActiveStorageVariantRecords < ActiveRecord::Migration[6.0] def change unless table_exists?(:active_storage_variant_records) # Use Active Record's configured type for primary key create_table :active_storage_variant_records, id: primary_key_type do |t| t.belongs_to :blob, null: false, index: false, type: blobs_primary_key_type t.string :variation_digest, null: false t.index %i[ blob_id variation_digest ], name: "index_active_storage_variant_records_uniqueness", unique: true t.foreign_key :active_storage_blobs, column: :blob_id end end end private def primary_key_type config = Rails.configuration.generators config.options[config.orm][:primary_key_type] || :primary_key end def blobs_primary_key_type pkey_name = connection.primary_key(:active_storage_blobs) pkey_column = connection.columns(:active_storage_blobs).find { |c| c.name == pkey_name } pkey_column.bigint? ? :bigint : pkey_column.type end end
class CreateActiveStorageVariantRecords < ActiveRecord::Migration[6.0] def change # Use Active Record's configured type for primary key create_table :active_storage_variant_records, id: primary_key_type, if_not_exists: true do |t| t.belongs_to :blob, null: false, index: false, type: blobs_primary_key_type t.string :variation_digest, null: false t.index %i[ blob_id variation_digest ], name: "index_active_storage_variant_records_uniqueness", unique: true t.foreign_key :active_storage_blobs, column: :blob_id end end private def primary_key_type config = Rails.configuration.generators config.options[config.orm][:primary_key_type] || :primary_key end def blobs_primary_key_type pkey_name = connection.primary_key(:active_storage_blobs) pkey_column = connection.columns(:active_storage_blobs).find { |c| c.name == pkey_name } pkey_column.bigint? ? :bigint : pkey_column.type end end
Fix rubocop warnings in NumberOfVmsVisibilityService
class NumberOfVmsVisibilityService def determine_visibility(number_of_vms, platform) field_names_to_hide = [] field_names_to_edit = [] if number_of_vms > 1 field_names_to_hide += [:sysprep_computer_name, :linux_host_name, :floating_ip_address] field_names_to_edit += [:ip_addr] else field_names_to_hide += [:ip_addr] field_names_to_edit += [:floating_ip_address] if platform == "linux" field_names_to_edit += [:linux_host_name] field_names_to_hide += [:sysprep_computer_name] else field_names_to_edit += [:sysprep_computer_name] field_names_to_hide += [:linux_host_name] end end {:hide => field_names_to_hide, :edit => field_names_to_edit} end end
class NumberOfVmsVisibilityService def determine_visibility(number_of_vms, platform) field_names_to_hide = [] field_names_to_edit = [] if number_of_vms > 1 field_names_to_hide += %i(sysprep_computer_name linux_host_name floating_ip_address) field_names_to_edit += [:ip_addr] else field_names_to_hide += [:ip_addr] field_names_to_edit += [:floating_ip_address] if platform == "linux" field_names_to_edit += [:linux_host_name] field_names_to_hide += [:sysprep_computer_name] else field_names_to_edit += [:sysprep_computer_name] field_names_to_hide += [:linux_host_name] end end {:hide => field_names_to_hide, :edit => field_names_to_edit} end end
Fix a deprecation warning from rspec.
require 'spec_helper' describe 'openconnect' do context 'supported operating systems' do ['Debian'].each do |osfamily| describe "osfamily is #{osfamily}" do let(:facts) {{ :osfamily => osfamily, }} describe 'with mandatory params' do let(:params) {{ :url => 'https://vpn.example.com/profile', :user => 'janesmith', :pass => 'mekmitasdigoat', }} it { should include_class('openconnect::params') } it { should contain_class('openconnect::install') } it { should contain_class('openconnect::config') } it { should contain_class('openconnect::service') } end describe 'without any params' do let(:params) {{ }} it 'should require mandatory params' do expect { should }.to raise_error(Puppet::Error, /Must pass/) end end end end end context 'unsupported operating system' do describe 'openconnect class without any parameters on CentOS/RedHat' do let(:facts) {{ :osfamily => 'RedHat', :operatingsystem => 'CentOS', }} it { expect { should }.to raise_error(Puppet::Error, /CentOS not supported/) } end end end
require 'spec_helper' describe 'openconnect' do context 'supported operating systems' do ['Debian'].each do |osfamily| describe "osfamily is #{osfamily}" do let(:facts) {{ :osfamily => osfamily, }} describe 'with mandatory params' do let(:params) {{ :url => 'https://vpn.example.com/profile', :user => 'janesmith', :pass => 'mekmitasdigoat', }} it { should contain_class('openconnect::params') } it { should contain_class('openconnect::install') } it { should contain_class('openconnect::config') } it { should contain_class('openconnect::service') } end describe 'without any params' do let(:params) {{ }} it 'should require mandatory params' do expect { should }.to raise_error(Puppet::Error, /Must pass/) end end end end end context 'unsupported operating system' do describe 'openconnect class without any parameters on CentOS/RedHat' do let(:facts) {{ :osfamily => 'RedHat', :operatingsystem => 'CentOS', }} it { expect { should }.to raise_error(Puppet::Error, /CentOS not supported/) } end end end
Update exercise model relationship tests
require 'rails_helper' RSpec.describe Question, type: :model do describe "Validations -->" do let(:question) { build(:question) } it "is valid with valid attributes" do expect(question).to be_valid end end describe "Relationships -->" do it "belongs to exercise" do expect(relationship_type(Question, :exercise)) end end end
require 'rails_helper' RSpec.describe Question, type: :model do describe "Validations -->" do let(:question) { build(:question) } it "is valid with valid attributes" do expect(question).to be_valid end end describe "Relationships -->" do it "belongs to exercise" do expect(relationship_type(Question, :exercise)).to eq(:belongs_to) end it "has many test cases" do expect(relationship_type(Question, :test_cases)).to eq(:has_many) end end end
Fix gemspec file for forward compatibility.
Gem::Specification.new do |s| s.name = 'Toribash Protocol Watcher' s.version = '0.0.1' s.summary = "Exposes Toribash protocol connections." s.description = "Sniffs Toribash packets and logs protocol." s.authors = ["Anthony Clever"] s.email = 'anthonyclever@gmail.com' s.files = ["lib/passthrough.rb"] s.homepage = 'http://toribash-dev.leel.me/' end
Gem::Specification.new do |s| s.name = 'Toribash Protocol Watcher' s.version = '0.0.1' s.summary = "Exposes Toribash protocol connections." s.description = "Sniffs Toribash packets and logs protocol." s.authors = ["Anthony Clever"] s.email = 'anthonyclever@gmail.com' s.files = ["lib/**/*.rb"] s.homepage = 'http://toribash-dev.leel.me/' end
Make http requests concurrently with db connections
class Stresser def self.random_letters 2.times.map { SecureRandom.random_number(2**64).to_s(32) }.join('') end def self.random_url "postgres://#{random_letters}:#{random_letters}@example.com/#{random_letters}" end def self.run_batch rand = Random.new [ ByteaThing, NineOneByteaThing ].map do |klazz| Thread.new do 1000.times do klazz.create(data: Sequel.blob(rand.bytes(176)), stuff: random_url) end end end.each(&:join) [ ByteaThing, NineOneByteaThing ].map do |klazz| Thread.new do all_things = klazz.all 1000.times do thing = all_things.sample thing.update(data: Sequel.blob(rand.bytes(176)), stuff: random_url) end end end.each(&:join) [ ByteaThing, NineOneByteaThing ].map do |klazz| klazz.dataset.delete end end end
require 'net/http' class Stresser APP_NAME = 'secret-plains-3232' def self.random_letters 2.times.map { SecureRandom.random_number(2**64).to_s(32) }.join('') end def self.random_url "postgres://#{random_letters}:#{random_letters}@example.com/#{random_letters}" end def self.run_batch http_thread = Thread.new do loop do Net::HTTP.get('https://#{APP_NAME}.herokuapp.com/') rescue nil sleep 0.05 end end rand = Random.new [ ByteaThing, NineOneByteaThing ].map do |klazz| Thread.new do 1000.times do klazz.create(data: Sequel.blob(rand.bytes(176)), stuff: random_url) end end end.each(&:join) [ ByteaThing, NineOneByteaThing ].map do |klazz| Thread.new do all_things = klazz.all 1000.times do thing = all_things.sample thing.update(data: Sequel.blob(rand.bytes(176)), stuff: random_url) end end end.each(&:join) [ ByteaThing, NineOneByteaThing ].map do |klazz| klazz.dataset.delete end http_thread.join end end
Add check to ensure that migrations have been applied.
# Lifted from Advanced Rails Recipes #38: Fail Early -- # Check to make sure we've got the right database version; # skip when run from tasks like rake db:migrate, or from Capistrano rules # that need to run before the migration rule current_version = ActiveRecord::Migrator.current_version rescue 0 highest_version = Dir.glob("#{RAILS_ROOT}/db/migrate/*.rb" ).map { |f| f.match(/(\d+)_.*\.rb$/) ? $1.to_i : 0 }.max abort "Database isn't the current migration version: " \ "expected #{highest_version}, got #{current_version}\n" \ "You must either run 'rake db:migrate' or set environmental variable NO_MIGRATION_CHECK" \ unless current_version == highest_version or \ defined?(Rake) or ENV['NO_MIGRATION_CHECK']
Add pry to development dependency
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'takumi/server_list_ping/version' Gem::Specification.new do |spec| spec.name = "takumi-server_list_ping" spec.version = Takumi::ServerListPing::VERSION spec.authors = ["block_given?"] spec.email = ["block_given@outlook.com"] spec.summary = %q{minecraft server list ping packet and tools.} spec.homepage = "https://github.com/blockgiven/takumi-server_list_ping" 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.executables << 'takumi-server_list_ping' spec.add_runtime_dependency "takumi-packet" spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'takumi/server_list_ping/version' Gem::Specification.new do |spec| spec.name = "takumi-server_list_ping" spec.version = Takumi::ServerListPing::VERSION spec.authors = ["block_given?"] spec.email = ["block_given@outlook.com"] spec.summary = %q{minecraft server list ping packet and tools.} spec.homepage = "https://github.com/blockgiven/takumi-server_list_ping" 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.executables << 'takumi-server_list_ping' spec.add_runtime_dependency "takumi-packet" spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "pry" spec.add_development_dependency "rake", "~> 10.0" end
Fix bug with rpc response validation
class AmfSocket::RpcResponse attr_reader :connection attr_reader :message_id attr_reader :command attr_reader :params attr_reader :result def initialize(request_object, response_object, connection) raise AmfSocket::InvalidObject unless validate_object(response_object) req = request_object[:request] res = response_object[:response] @connection = connection @message_id = req[:messageId] @command = req[:command] @params = req[:params] @result = res[:result] end private def validate_object(object) return false unless object.is_a?(Hash) return false unless object[:type] == 'rpcResponse' return false unless object[:response].is_a?(Hash) return false unless object[:response][:messageId].is_a?(String) return false unless object[:response][:result].is_a?(String) return true end end
class AmfSocket::RpcResponse attr_reader :connection attr_reader :message_id attr_reader :command attr_reader :params attr_reader :result def initialize(request_object, response_object, connection) raise AmfSocket::InvalidObject unless validate_object(response_object) req = request_object[:request] res = response_object[:response] @connection = connection @message_id = req[:messageId] @command = req[:command] @params = req[:params] @result = res[:result] end private def validate_object(object) return false unless object.is_a?(Hash) return false unless object[:type] == 'rpcResponse' return false unless object[:response].is_a?(Hash) return false unless object[:response][:messageId].is_a?(String) return false unless object[:response].has_key?(:result) return true end end
Remove associated magic_attributes when destroying a MagicColumn
class MagicColumn < ActiveRecord::Base has_many :magic_column_relationships has_many :owners, :through => :magic_column_relationships, :as => :owner has_many :magic_options validates_presence_of :name, :datatype validates_format_of :name, :with => /^[a-z][a-z0-9_]+$/ def type_cast(value) begin case datatype.to_sym when :check_box_boolean (value.to_int == 1) ? true : false when :date Date.parse(value) when :datetime Time.parse(value) when :integer value.to_int else value end rescue value end end # Display a nicer (possibly user-defined) name for the column or use a fancified default. def pretty_name super || name.humanize end end
class MagicColumn < ActiveRecord::Base has_many :magic_column_relationships has_many :owners, :through => :magic_column_relationships, :as => :owner has_many :magic_options has_many :magic_attributes, :dependent => :destroy validates_presence_of :name, :datatype validates_format_of :name, :with => /^[a-z][a-z0-9_]+$/ def type_cast(value) begin case datatype.to_sym when :check_box_boolean (value.to_int == 1) ? true : false when :date Date.parse(value) when :datetime Time.parse(value) when :integer value.to_int else value end rescue value end end # Display a nicer (possibly user-defined) name for the column or use a fancified default. def pretty_name super || name.humanize end end
Add v to version tag
Pod::Spec.new do |s| s.name = 'DVR' s.version = '0.3.0' s.summary = 'Network testing for Swift' s.description = <<-DESC DVR is a simple Swift framework for making fake NSURLSession requests for iOS, watchOS, and OS X based on VCR. Easy dependency injection is the main design goal. The API is the same as NSURLSession. DVR.Session is a subclass of NSURLSession so you can use it as a drop in replacement anywhere. (Currently only data tasks are supported.) DESC s.homepage = 'https://github.com/venmo/DVR' s.license = { type: 'MIT', file: 'LICENSE' } s.author = { 'Venmo' => 'ios@venmo.com' } s.source = { git: 'https://github.com/venmo/DVR.git', tag: s.version.to_s } s.ios.deployment_target = '8.0' s.osx.deployment_target = '10.10' s.source_files = 'DVR/*.{swift}' end
Pod::Spec.new do |s| s.name = 'DVR' s.version = '0.3.0' s.summary = 'Network testing for Swift' s.description = <<-DESC DVR is a simple Swift framework for making fake NSURLSession requests for iOS, watchOS, and OS X based on VCR. Easy dependency injection is the main design goal. The API is the same as NSURLSession. DVR.Session is a subclass of NSURLSession so you can use it as a drop in replacement anywhere. (Currently only data tasks are supported.) DESC s.homepage = 'https://github.com/venmo/DVR' s.license = { type: 'MIT', file: 'LICENSE' } s.author = { 'Venmo' => 'ios@venmo.com' } s.source = { git: 'https://github.com/venmo/DVR.git', tag: "v#{s.version}" } s.ios.deployment_target = '8.0' s.osx.deployment_target = '10.10' s.source_files = 'DVR/*.{swift}' end
Fix pixiv badge on WebUI
# frozen_string_literal: true class REST::AccountSerializer < ActiveModel::Serializer include RoutingHelper attributes :id, :username, :acct, :display_name, :locked, :created_at, :note, :url, :avatar, :avatar_static, :header, :header_static, :followers_count, :following_count, :statuses_count def note Formatter.instance.simplified_format(object) end def url TagManager.instance.url_for(object) end def avatar full_asset_url(object.avatar_original_url) end def avatar_static full_asset_url(object.avatar_static_url) end def header full_asset_url(object.header_original_url) end def header_static full_asset_url(object.header_static_url) end end
# frozen_string_literal: true class REST::AccountSerializer < ActiveModel::Serializer include RoutingHelper attributes :id, :username, :acct, :display_name, :locked, :created_at, :note, :url, :avatar, :avatar_static, :header, :header_static, :followers_count, :following_count, :statuses_count belongs_to :oauth_authentications def note Formatter.instance.simplified_format(object) end def url TagManager.instance.url_for(object) end def avatar full_asset_url(object.avatar_original_url) end def avatar_static full_asset_url(object.avatar_static_url) end def header full_asset_url(object.header_original_url) end def header_static full_asset_url(object.header_static_url) end class OauthAuthenticationSerializer < ActiveModel::Serializer attributes :uid, :provider end end
Fix style issues based on brew style guide
module Cask class DSL class ConflictsWith VALID_KEYS = Set.new [ :formula, :cask, :macos, :arch, :x11, :java, ] attr_reader *VALID_KEYS def initialize(pairs = {}) @pairs = pairs VALID_KEYS.each do |key| instance_variable_set("@#{key}", Set.new) end pairs.each do |key, value| raise "invalid conflicts_with key: '#{key.inspect}'" unless VALID_KEYS.include?(key) instance_variable_set("@#{key}", instance_variable_get("@#{key}").merge([*value])) end end def to_a (@pairs.values) end end end end
module Cask class DSL class ConflictsWith VALID_KEYS = Set.new [ :formula, :cask, :macos, :arch, :x11, :java, ] attr_reader *VALID_KEYS def initialize(pairs = {}) @pairs = pairs VALID_KEYS.each do |key| instance_variable_set("@#{key}", Set.new) end pairs.each do |key, value| raise "invalid conflicts_with key: '#{key.inspect}'" unless VALID_KEYS.include?(key) instance_variable_set("@#{key}", instance_variable_get("@#{key}").merge([*value])) end end def to_a @pairs.values end end end end
Add a dummy page for cron hits.
#!/usr/bin/env ruby require 'sinatra' require 'nokogiri' require './tml_code_tokenizer' require './tml_token_parser' get '/' do erb :index end get '/contact' do erb :contact end get '/convert' do "You must access this page via the form on the front page" end post '/convert' do line = params[:tml_code] builder = Nokogiri::XML::Builder.new do |xml| tokenizer = TmlCodeTokenizer.new(xml) parser = TmlTokenParser::Parser.new(xml, tokenizer.tokenize(line)) xml.example { xml.comment(" #{line} ") parser.parse() } end builder.to_xml end
#!/usr/bin/env ruby require 'sinatra' require 'nokogiri' require './tml_code_tokenizer' require './tml_token_parser' get '/' do erb :index end get '/contact' do erb :contact end get '/convert' do "You must access this page via the form on the front page" end post '/convert' do line = params[:tml_code] builder = Nokogiri::XML::Builder.new do |xml| tokenizer = TmlCodeTokenizer.new(xml) parser = TmlTokenParser::Parser.new(xml, tokenizer.tokenize(line)) xml.example { xml.comment(" #{line} ") parser.parse() } end builder.to_xml end # this is just so that a cron job can hit this site so that the heroku # dynos don't spin down after 30 minutes of inactivity get '/cron.txt' do 'ok' end
Change version. Same gem version can't be pushed to RubyGems.
# coding: utf-8 Gem::Specification.new do |spec| spec.name = "pry-globs" spec.version = "0.1.0" spec.authors = ["dariodaic"] spec.email = ["dariodaic5.1@gmail.com"] spec.homepage = "https://github.com/dariodaic/pry-globs" spec.summary = "Pry plugin for describing global variables." spec.license = "MIT" spec.files = Dir["lib/pry-globs.rb"] spec.files += Dir["lib/pry-globs/*"] spec.require_paths = ["lib"] spec.required_ruby_version = ">= 2.2.0" end
# coding: utf-8 Gem::Specification.new do |spec| spec.name = "pry-globs" spec.version = "0.1.1" spec.authors = ["dariodaic"] spec.email = ["dariodaic5.1@gmail.com"] spec.homepage = "https://github.com/dariodaic/pry-globs" spec.summary = "Pry plugin for describing global variables." spec.license = "MIT" spec.files = Dir["lib/pry-globs.rb"] spec.files += Dir["lib/pry-globs/*"] spec.require_paths = ["lib"] spec.required_ruby_version = ">= 2.2.0" end
Update - Update help script
module Line::Scripts module HelpScript def assign super # --- parse info case event when Line::Bot::Event::Message message_id = event.message['id'] case event.type when Line::Bot::Event::MessageType::Text message = event.message['text'] if message =~ /^(help|HELP|Help)/ reply_messages = [ { type: 'text', text: "show - 檢視對話紀錄" }, { type: 'sticker', packageId: '2', stickerId: '144', } ] response = client.reply_message(event['replyToken'], reply_messages) end end end end end end
module Line::Scripts module HelpScript def assign super # --- parse info case event when Line::Bot::Event::Message message_id = event.message['id'] case event.type when Line::Bot::Event::MessageType::Text message = event.message['text'] if message =~ /^(help|HELP|Help)/ role = '' role += "show - 檢視對話紀錄\n" role += "start_record - 開始紀錄\n" role += "end_record - 結束紀錄" reply_messages = [ { type: 'text', text: role }, { type: 'sticker', packageId: '2', stickerId: '144', } ] response = client.reply_message(event['replyToken'], reply_messages) end end end end end end
Fix undesired delivering of private toot to remote accounts that follow author
# frozen_string_literal: true class ProcessMentionsService < BaseService # Scan status for mentions and fetch remote mentioned users, create # local mention pointers, send Salmon notifications to mentioned # remote users # @param [Status] status def call(status) return unless status.local? status.text.scan(Account::MENTION_RE).each do |match| username, domain = match.first.split('@') mentioned_account = Account.find_remote(username, domain) if mentioned_account.nil? && !domain.nil? begin mentioned_account = follow_remote_account_service.call(match.first.to_s) rescue Goldfinger::Error, HTTP::Error mentioned_account = nil end end next if mentioned_account.nil? mentioned_account.mentions.where(status: status).first_or_create(status: status) end status.mentions.each do |mention| mentioned_account = mention.account next if status.private_visibility? && !mentioned_account.following?(status.account) if mentioned_account.local? NotifyService.new.call(mentioned_account, mention) else NotificationWorker.perform_async(status.stream_entry.id, mentioned_account.id) end end end private def follow_remote_account_service @follow_remote_account_service ||= FollowRemoteAccountService.new end end
# frozen_string_literal: true class ProcessMentionsService < BaseService # Scan status for mentions and fetch remote mentioned users, create # local mention pointers, send Salmon notifications to mentioned # remote users # @param [Status] status def call(status) return unless status.local? status.text.scan(Account::MENTION_RE).each do |match| username, domain = match.first.split('@') mentioned_account = Account.find_remote(username, domain) if mentioned_account.nil? && !domain.nil? begin mentioned_account = follow_remote_account_service.call(match.first.to_s) rescue Goldfinger::Error, HTTP::Error mentioned_account = nil end end next if mentioned_account.nil? mentioned_account.mentions.where(status: status).first_or_create(status: status) end status.mentions.each do |mention| mentioned_account = mention.account next if status.private_visibility? && (!mentioned_account.following?(status.account) || !mentioned_account.local?) if mentioned_account.local? NotifyService.new.call(mentioned_account, mention) else NotificationWorker.perform_async(status.stream_entry.id, mentioned_account.id) end end end private def follow_remote_account_service @follow_remote_account_service ||= FollowRemoteAccountService.new end end
Allow Rails 3.2.22 to be used too.
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'calculated_attributes/version' Gem::Specification.new do |spec| spec.name = 'calculated_attributes' spec.version = CalculatedAttributes::VERSION spec.authors = ['Zach Schneider'] spec.email = ['zach@aha.io'] spec.summary = 'Automatically add calculated attributes to ActiveRecord models.' spec.homepage = 'https://github.com/aha-app/calculated_attributes' 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.7' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3.1' spec.add_development_dependency 'rubocop' spec.add_development_dependency 'sqlite3' spec.add_dependency 'activerecord', '3.2.21' end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'calculated_attributes/version' Gem::Specification.new do |spec| spec.name = 'calculated_attributes' spec.version = CalculatedAttributes::VERSION spec.authors = ['Zach Schneider'] spec.email = ['zach@aha.io'] spec.summary = 'Automatically add calculated attributes to ActiveRecord models.' spec.homepage = 'https://github.com/aha-app/calculated_attributes' 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.7' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3.1' spec.add_development_dependency 'rubocop' spec.add_development_dependency 'sqlite3' spec.add_dependency 'activerecord', '~> 3.2.21' end
Fix core ext argument error.
class Hash def slice(*keys) hash = {} keep_keys.each do |key| hash[key] = fetch(key) if key?(key) end hash end end
class Hash def slice(*keep_keys) hash = {} keep_keys.each do |key| hash[key] = fetch(key) if key?(key) end hash end end
Add redis gem missing warning
require 'plezi/websockets/message_dispatch' unless defined?(::Plezi::Base::MessageDispatch) module Plezi protected @plezi_finalize = nil def plezi_finalize if @plezi_finalize.nil? @plezi_finalize = true @plezi_finalize = 1 end end @plezi_initialize = nil def self.plezi_initialize if @plezi_initialize.nil? @plezi_initialize = true @plezi_autostart = true if @plezi_autostart.nil? at_exit do next if @plezi_autostart == false ::Iodine::Rack.app = ::Plezi.app ::Iodine.start end end true end end ::Iodine.threads ||= 16 ::Iodine.processes ||= 1 unless ENV['PL_REDIS_URL'.freeze] ::Iodine.run { ::Plezi::Base::MessageDispatch._init }
require 'plezi/websockets/message_dispatch' unless defined?(::Plezi::Base::MessageDispatch) module Plezi protected @plezi_finalize = nil def plezi_finalize if @plezi_finalize.nil? @plezi_finalize = true @plezi_finalize = 1 end end @plezi_initialize = nil def self.plezi_initialize if @plezi_initialize.nil? @plezi_initialize = true @plezi_autostart = true if @plezi_autostart.nil? puts "WARNNING: auto-scaling with redis is set using ENV['PL_REDIS_URL'.freeze]\r\n but the Redis gem isn't included! - SCALING IS IGNORED!" if ENV['PL_REDIS_URL'.freeze] && !defined?(::Redis) at_exit do next if @plezi_autostart == false ::Iodine::Rack.app = ::Plezi.app ::Iodine.start end end true end end ::Iodine.threads ||= 16 ::Iodine.processes ||= 1 unless ENV['PL_REDIS_URL'.freeze] ::Iodine.run { ::Plezi::Base::MessageDispatch._init }
Add incredibly basic AdminUser spec
require 'spec_helper' describe AdminUser do pending "add some examples to (or delete) #{__FILE__}" end
require 'spec_helper' describe AdminUser do [:email, :password].each do |attr| it { should validate_presence_of(attr) } end end
Allow anonymous users to view /redaction
# encoding: utf-8 class RedactionController < ApplicationController before_action :authenticate_account! append_view_path NoNamespaceResolver.new def index @boards = Board.all(Board.writing) @board = @boards.build @drafts = News.draft.sorted @news = News.candidate.sorted @stats = Statistics::Redaction.new end end
# encoding: utf-8 class RedactionController < ApplicationController append_view_path NoNamespaceResolver.new def index @boards = Board.all(Board.writing) @board = @boards.build @drafts = News.draft.sorted @news = News.candidate.sorted @stats = Statistics::Redaction.new end end
Update podspec version to 0.0.5
Pod::Spec.new do |s| s.name = 'CacheIsKing' s.version = '0.0.4' s.license = 'MIT' s.summary = 'A simple cache that can hold anything, including Swift items' s.homepage = 'https://github.com/nuudles/CacheIsKing' s.authors = { 'Christopher Luu' => 'nuudles@gmail.com' } s.source = { :git => 'https://github.com/nuudles/CacheIsKing.git', :tag => s.version } s.ios.deployment_target = '8.0' s.tvos.deployment_target = '9.0' s.source_files = 'Source/*.swift' s.requires_arc = true end
Pod::Spec.new do |s| s.name = 'CacheIsKing' s.version = '0.0.5' s.license = 'MIT' s.summary = 'A simple cache that can hold anything, including Swift items' s.homepage = 'https://github.com/nuudles/CacheIsKing' s.authors = { 'Christopher Luu' => 'nuudles@gmail.com' } s.source = { :git => 'https://github.com/nuudles/CacheIsKing.git', :tag => s.version } s.ios.deployment_target = '8.0' s.tvos.deployment_target = '9.0' s.source_files = 'Source/*.swift' s.requires_arc = true end
Migrate Aquamacs 2.5 cask from homebrew-cask.
class Aquamacs25 < Cask url 'http://braeburn.aquamacs.org/releases/Aquamacs-Emacs-2.5.dmg' homepage 'http://aquamacs.org/' version '2.5' sha1 '2d9052b94751b0454e109700ff8d0204d80310f4' link 'Aquamacs.app' end
Fix `url` stanza comment for SuperDuper!.
cask 'superduper' do version :latest sha256 :no_check url 'https://s3.amazonaws.com/shirtpocket/SuperDuper/SuperDuper!.dmg' name 'SuperDuper!' homepage 'http://www.shirt-pocket.com/SuperDuper/SuperDuperDescription.html' license :freemium app 'SuperDuper!.app' zap delete: '~/Library/Application Support/SuperDuper!' end
cask 'superduper' do version :latest sha256 :no_check # amazonaws.com/shirtpocket/SuperDuper was verified as official when first introduced to the cask url 'https://s3.amazonaws.com/shirtpocket/SuperDuper/SuperDuper!.dmg' name 'SuperDuper!' homepage 'http://www.shirt-pocket.com/SuperDuper/SuperDuperDescription.html' license :freemium app 'SuperDuper!.app' zap delete: '~/Library/Application Support/SuperDuper!' end
Add a cask-file for TestFlight 1.0_beta306
class Testflight < Cask url 'https://d193ln56du8muy.cloudfront.net/desktop_app/1370377714/TestFlight-Desktop-1.0-Beta(306).zip' homepage 'http://testflightapp.com' version '1.0_beta306' sha1 '86180feb6e48c30501ec2a0428bb45f7b4fc3396' link 'TestFlight.app' end
Remove pry call from controller
require "pry" class ContentController < ApplicationController before_filter :track_user def home binding.pry end end
class ContentController < ApplicationController before_filter :track_user def home end end
Update YNAB to version 4.3.73
class YouNeedABudget < Cask url 'http://www.youneedabudget.com/CDNOrigin/download/ynab4/liveCaptive/Mac/YNAB4_LiveCaptive_4.1.553.dmg' homepage 'http://www.youneedabudget.com/' version '4.1.553' sha1 'bf10b82ecf741d4655ab864717e307eb1858e385' link 'YNAB 4.app' end
class YouNeedABudget < Cask url 'http://www.youneedabudget.com/CDNOrigin/download/ynab4/liveCaptive/Mac/YNAB4_LiveCaptive_4.3.73.dmg' homepage 'http://www.youneedabudget.com/' version '4.3.73' sha1 'c8e8a2f5f73d39fb5282bec552772daeec60c3bb' link 'YNAB 4.app' end
Add a DSL method for changing logins
class Roda module RodaPlugins module Rodauth ChangeLogin = Feature.define(:change_login) do route 'change-login' notice_flash 'Your login has been changed' error_flash 'There was an error changing your login' view 'change-login', 'Change Login' after additional_form_tags redirect require_login get_block do |r, auth| auth.view('change-login', 'Change Login') end post_block do |r, auth| if r[auth.login_param] == r[auth.login_confirm_param] if auth._account_from_session if auth.change_login(r[auth.login_param].to_s) auth.after_change_login auth.set_notice_flash auth.change_login_notice_flash r.redirect(auth.change_login_redirect) else @login_error = auth.login_errors_message end end else @login_error = auth.logins_do_not_match_message end auth.set_error_flash auth.change_login_error_flash auth.change_login_view end def change_login(login) account.set(login_column=>login).save(:raise_on_failure=>false) end end end end end
class Roda module RodaPlugins module Rodauth ChangeLogin = Feature.define(:change_login) do route 'change-login' notice_flash 'Your login has been changed' error_flash 'There was an error changing your login' view 'change-login', 'Change Login' after additional_form_tags redirect require_login auth_methods :change_login get_block do |r, auth| auth.view('change-login', 'Change Login') end post_block do |r, auth| if r[auth.login_param] == r[auth.login_confirm_param] if auth._account_from_session if auth.change_login(r[auth.login_param].to_s) auth.after_change_login auth.set_notice_flash auth.change_login_notice_flash r.redirect(auth.change_login_redirect) else @login_error = auth.login_errors_message end end else @login_error = auth.logins_do_not_match_message end auth.set_error_flash auth.change_login_error_flash auth.change_login_view end def change_login(login) account.set(login_column=>login).save(:raise_on_failure=>false) end end end end end
Include currently assigned invoice in suggestions for booking form.
module InvoiceHelper def invoice_states_as_collection states = Invoice::STATES states.inject({}) do |result, state| result[t(state, :scope => 'invoice.state')] = state result end end def suggested_invoices_for_booking(booking) invoices = Invoice.open_balance.where(:amount => booking.amount) invoices.collect{|invoice| [invoice.to_s(:long), invoice.id]} end def invoice_label(invoice) invoice_state_label(invoice.state) end def t_invoice_filter(state) t(state, :scope => 'invoice.state') end def invoice_state_label(state, active = true) type = case state.to_s when 'canceled', 'reactivated' nil when 'paid' 'success' when 'reminded', '2xreminded', '3xreminded', 'encashment' 'important' when 'booked', 'written_off' 'info' end type = 'disabled' unless active boot_label(t(state, :scope => 'invoice.state'), type) end end
module InvoiceHelper def invoice_states_as_collection states = Invoice::STATES states.inject({}) do |result, state| result[t(state, :scope => 'invoice.state')] = state result end end def suggested_invoices_for_booking(booking) invoices = Invoice.open_balance.where(:amount => booking.amount) invoices << booking.reference if booking.reference invoices.collect{|invoice| [invoice.to_s(:long), invoice.id]} end def invoice_label(invoice) invoice_state_label(invoice.state) end def t_invoice_filter(state) t(state, :scope => 'invoice.state') end def invoice_state_label(state, active = true) type = case state.to_s when 'canceled', 'reactivated' nil when 'paid' 'success' when 'reminded', '2xreminded', '3xreminded', 'encashment' 'important' when 'booked', 'written_off' 'info' end type = 'disabled' unless active boot_label(t(state, :scope => 'invoice.state'), type) end end
Use raise instead of fail
require 'active_support/all' require 'poms/media' require 'poms/errors/authentication_error' require 'json' # Main interface for the POMS gem module Poms extend self attr_reader :config def configure @config ||= OpenStruct.new yield @config end def fetch(arg) assert_credentials if arg.is_a?(Array) request = Poms::Media.multiple(arg, config) elsif arg.is_a?(String) request = Poms::Media.from_mid(arg, config) else fail 'Invalid argument passed to Poms.fetch. '\ 'Please make sure to provide either a mid or an array of mid' end JSON.parse(request.get.body) end private def assert_credentials fail Errors::AuthenticationError, 'API key not supplied' if config.key.blank? fail Errors::AuthenticationError, 'API secret not supplied' if config.secret.blank? fail Errors::AuthenticationError, 'Origin not supplied' if config.origin.blank? end end
require 'active_support/all' require 'poms/media' require 'poms/errors/authentication_error' require 'json' # Main interface for the POMS gem module Poms extend self attr_reader :config def configure @config ||= OpenStruct.new yield @config end def fetch(arg) assert_credentials if arg.is_a?(Array) request = Poms::Media.multiple(arg, config) elsif arg.is_a?(String) request = Poms::Media.from_mid(arg, config) else raise 'Invalid argument passed to Poms.fetch. '\ 'Please make sure to provide either a mid or an array of mid' end JSON.parse(request.get.body) end private def assert_credentials raise Errors::AuthenticationError, 'API key not supplied' if config.key.blank? raise Errors::AuthenticationError, 'API secret not supplied' if config.secret.blank? raise Errors::AuthenticationError, 'Origin not supplied' if config.origin.blank? end end
Add uninstall stanza to Garmin Training Center
class GarminTrainingCenter < Cask url 'http://www8.garmin.com/software/TrainingCenterforMac_321.dmg' homepage 'http://www.garmin.com/garmin/cms/intosports/training_center' version '3.2.1' sha256 '82bda2f40b3ad8402f1e88fd7750b2827dc8f8f17ea45165e0c85fe6dbd7dfb6' install 'Garmin Training Center.pkg' end
class GarminTrainingCenter < Cask url 'http://www8.garmin.com/software/TrainingCenterforMac_321.dmg' homepage 'http://www.garmin.com/garmin/cms/intosports/training_center' version '3.2.1' sha256 '82bda2f40b3ad8402f1e88fd7750b2827dc8f8f17ea45165e0c85fe6dbd7dfb6' install 'Garmin Training Center.pkg' uninstall :pkgutil => 'com.garmin.garminTrainingCenter.*pkg' end
Update the memory leak test
#!/usr/bin/env ruby $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "lib")) require "dryer" class Target include ::Dryer::Construct construct def call 1 + 1 end end class Caster include Dryer::Cast include ::Dryer::Construct construct cast_group do cast :cast_a, to: Target end end 1000.times do Caster.new.cast_a end GC.start puts "Leaked Caster Objects: #{ObjectSpace.each_object(Caster).count}"
#!/usr/bin/env ruby $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "lib")) require "dryer" class Target include ::Dryer::Construct construct def call 1 + 1 end end class Caster include Dryer::Cast include ::Dryer::Construct construct cast_group do cast :cast_a, to: Target end end class Base include ::Dryer::Construct construct(:one, two: 2) end class Construct < Base construct(:three, four: 4) end class Construct2 < Base construct(:five, six: 6) end 1000.times do Caster.new.cast_a Construct.new(one: 1, three: 3) Construct2.new(one: 1, five: 5) end GC.start puts "Leaked Caster Objects: #{ObjectSpace.each_object(Caster).count}" puts "Leaked Constructer Base Objects: #{ObjectSpace.each_object(Base).count}" puts "Leaked Constructer Construct Objects: #{ObjectSpace.each_object(Construct).count}" puts "Leaked Constructer Construct2 Objects: #{ObjectSpace.each_object(Construct2).count}"
Update factory to not have date attribute, which is no longer present on the model
FactoryGirl.define do factory :talk do date "2015-10-29" title "MyString" description "MyString" end end
FactoryGirl.define do factory :talk do title "MyString" end end
Fix compatibility btw codacy and vcr
# frozen_string_literal: true require 'vcr' require 'codacy-coverage' Codacy::Reporter.start RSpec.configure do |config| config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.filter_run :focus config.run_all_when_everything_filtered = true config.disable_monkey_patching! config.warnings = true if config.files_to_run.one? config.default_formatter = 'doc' end config.profile_examples = 10 config.order = :random Kernel.srand config.seed end VCR.configure do |config| config.cassette_library_dir = 'fixtures/vcr_cassettes' config.hook_into :webmock end
# frozen_string_literal: true require 'vcr' require 'codacy-coverage' Codacy::Reporter.start RSpec.configure do |config| config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.filter_run :focus config.run_all_when_everything_filtered = true config.disable_monkey_patching! config.warnings = true if config.files_to_run.one? config.default_formatter = 'doc' end config.profile_examples = 10 config.order = :random Kernel.srand config.seed end VCR.configure do |config| config.cassette_library_dir = 'fixtures/vcr_cassettes' config.hook_into :webmock config.ignore_hosts 'api.codacy.com' config.allow_http_connections_when_no_cassette = false end
Use truncation database cleaner strategy for js tests
# Configure Rails Envinronment ENV["RAILS_ENV"] = "test" require File.expand_path("../dummy/config/environment.rb", __FILE__) require 'rspec/rails' require 'factory_girl' require 'database_cleaner' ENGINE_RAILS_ROOT=File.join(File.dirname(__FILE__), '../') # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[File.join(ENGINE_RAILS_ROOT, "spec/support/**/*.rb")].each {|f| require f } RSpec.configure do |config| config.use_transactional_fixtures = false config.include(MailerMacros) config.before(:each) { reset_email } config.include Devise::TestHelpers, :type => :controller config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end
# Configure Rails Envinronment ENV["RAILS_ENV"] = "test" require File.expand_path("../dummy/config/environment.rb", __FILE__) require 'rspec/rails' require 'factory_girl' require 'database_cleaner' ENGINE_RAILS_ROOT=File.join(File.dirname(__FILE__), '../') # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[File.join(ENGINE_RAILS_ROOT, "spec/support/**/*.rb")].each {|f| require f } RSpec.configure do |config| config.use_transactional_fixtures = false config.include(MailerMacros) config.before(:each) { reset_email } config.include Devise::TestHelpers, :type => :controller config.before(:each) do if example.metadata[:js] DatabaseCleaner.strategy = :truncation else DatabaseCleaner.strategy = :transaction end end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end
Update gemspec to avoid warnings / errors
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "angular-gem/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "angular-gem" s.version = AngularGem::VERSION s.authors = ["Christian Vuerings", "Haroon Rasheed", "Yu-Hung Lin"] s.email = ["vueringschristian@gmail.com", "haroonrasheed@berkeley.edu", "yuhung@yuhunglin.com"] s.homepage = "http://github.com/ets-berkeley-edu/angular-gem" s.summary = "Bootstrap angularjs in a rails project" s.description = "Include Angularjs in rails and nothing more (ripped from angular-rails)" s.files = Dir["{app,config,db,lib,vendor}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md", "CHANGELOG.md"] s.test_files = Dir["test/**/*"] s.add_dependency "railties", [">= 3.1"] s.add_dependency "coffee-script", '~> 2.2.0' s.add_development_dependency "bundler", [">= 1.2.2"] s.add_development_dependency "tzinfo" s.add_development_dependency "nokogiri" s.add_development_dependency "coveralls" end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "angular-gem/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "angular-gem" s.version = AngularGem::VERSION s.licenses = ['MIT'] s.authors = ["Christian Vuerings", "Yu-Hung Lin"] s.email = ["vueringschristian@gmail.com", "yuhung@yuhunglin.com"] s.homepage = "http://github.com/ets-berkeley-edu/angular-gem" s.summary = "Bootstrap angularjs in a rails project" s.description = "Include Angularjs in rails and nothing more (ripped from angular-rails)" s.files = Dir["{app,config,db,lib,vendor}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md", "CHANGELOG.md"] s.test_files = Dir["test/**/*"] s.add_dependency "railties", ["~> 3.1"] s.add_dependency "coffee-script", '~> 2.2' s.add_development_dependency "bundler", ["~> 1.2"] s.add_development_dependency "tzinfo", ["~> 0.3"] s.add_development_dependency "nokogiri", ["~> 1.5"] s.add_development_dependency "coveralls", ["~> 0.6"] end
Create spec for Activities search page
feature "Activity Search Page" do scenario "should be displayed" do visit "/" click_link "Find Activities" expect(current_path).to eq(activities_path) expect(page).to have_content("Find Activities") end Capybara.javascript_driver = :selenium scenario "should have search navigation", js: :true do visit "/" click_link "Find Activities" expect(page).to have_link("Stay In") expect(page).to have_link("Go Out") expect(page).to have_link("Television") expect(page).to_not have_link("Sports") end scenario "should show hidden search items", js: :true do visit "/" click_link "Find Activities" click_link "Go Out" expect(page).to have_link("Sports") expect(page).to_not have_link("Television") end end
Copy of the current SDK from the utils project
require "json" require "openssl" require "net/http" module Color class SDK def initialize ( queue ) @queue = queue @buffer = ""; end def write ( entry ) @buffer += entry.to_json + "\n" if @buffer.size >= 60000 flush() # auto-flush end return self end def flush buffer = @buffer @buffer = "" uri = URI.parse( @queue ) http = Net::HTTP.new( uri.host, uri.port ) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE req = Net::HTTP::Post.new( uri.path ) req.body = "Action=SendMessage&MessageBody=" + buffer Thread.new do http.request( req ) end return self end end end
Enforce the assigned user limitations from the frontend in the backend
class Comment def before_create self.target ||= project set_status_and_assigned if self.target.is_a?(Task) end def after_create self.target.reload @activity = project && project.log_activity(self, 'create') target.after_comment(self) if target.respond_to?(:after_comment) target.add_watchers(@mentioned) if target.respond_to?(:add_watchers) target.notify_new_comment(self) if target.respond_to?(:notify_new_comment) end def after_destroy Activity.destroy_all :target_type => self.class.to_s, :target_id => self.id end protected def set_status_and_assigned self.previous_status = target.previous_status self.assigned = target.assigned self.previous_assigned_id = target.previous_assigned_id if status == Task::STATUSES[:open] && !assigned self.assigned = Person.find(:first, :conditions => { :user_id => user.id, :project_id => project.id }) end end end
class Comment def before_create self.target ||= project set_status_and_assigned if self.target.is_a?(Task) end def after_create self.target.reload @activity = project && project.log_activity(self, 'create') target.after_comment(self) if target.respond_to?(:after_comment) target.add_watchers(@mentioned) if target.respond_to?(:add_watchers) target.notify_new_comment(self) if target.respond_to?(:notify_new_comment) end def after_destroy Activity.destroy_all :target_type => self.class.to_s, :target_id => self.id end protected def set_status_and_assigned self.previous_status = target.previous_status self.assigned = target.assigned self.previous_assigned_id = target.previous_assigned_id if status == Task::STATUSES[:open] && !assigned self.assigned = Person.find(:first, :conditions => { :user_id => user.id, :project_id => project.id }) elsif status != Task::STATUSES[:open] self.assigned = nil end end end
Build image should use Go 1.13 for now
# We will grab the Go compiler from the latest Go image. FROM golang as go # Otherwise we base on the snapcraft container as that is by far the # most complex and tricky thing to get installed and working... FROM snapcore/snapcraft # Go COPY --from=go /usr/local/go /usr/local/go ENV PATH="/usr/local/go/bin:$PATH" # FPM to build Debian packages RUN apt-get update && apt-get install -y --no-install-recommends \ locales rubygems ruby-dev build-essential git \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* \ && gem install --no-ri --no-rdoc fpm
# We will grab the Go compiler from the latest Go image. FROM golang:1.13 as go # Otherwise we base on the snapcraft container as that is by far the # most complex and tricky thing to get installed and working... FROM snapcore/snapcraft # Go COPY --from=go /usr/local/go /usr/local/go ENV PATH="/usr/local/go/bin:$PATH" # FPM to build Debian packages RUN apt-get update && apt-get install -y --no-install-recommends \ locales rubygems ruby-dev build-essential git \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* \ && gem install --no-ri --no-rdoc fpm
Remove extraneous flash upon signing in
class SessionsController < ApplicationController def create user = User.from_omniauth(env["omniauth.auth"]) session[:user_id] = user.id redirect_to root_url, notice: 'Signed in!' end def destroy reset_session redirect_url root_url, notice: 'Signed out!' end end
class SessionsController < ApplicationController def create user = User.from_omniauth(env["omniauth.auth"]) session[:user_id] = user.id redirect_to root_url end def destroy reset_session redirect_url root_url, notice: 'Signed out!' end end
Refactor to reduce method complexity.
#coding: utf-8 module Wombat module DSL class PropertyGroup < Hash attr_accessor :wombat_property_name def initialize(name = nil) @wombat_property_name = name end def method_missing(method, *args, &block) property_name = method.to_s if args.empty? && block # TODO: Verify if another property with same name already exists # before overwriting property_group = self[property_name] || PropertyGroup.new(property_name) self[property_name] = property_group property_group.instance_eval(&block) else if args[1] == :iterator it = Iterator.new(property_name, args.first) self[property_name] = it it.instance_eval(&block) if block elsif args[1] == :follow it = Follower.new(property_name, args.first) self[property_name] = it it.instance_eval(&block) if block else self[property_name] = Property.new(property_name, *args, &block) end end end def to_ary end def wombat_property_format :container end def wombat_property_namespaces nil end end end end
#coding: utf-8 module Wombat module DSL class PropertyGroup < Hash attr_accessor :wombat_property_name def initialize(name = nil) @wombat_property_name = name end def method_missing(method, *args, &block) property_name = method.to_s if args.empty? && block # TODO: Verify if another property with same name already exists # before overwriting property_group = self[property_name] || PropertyGroup.new(property_name) self[property_name] = property_group property_group.instance_eval(&block) else it = build_property(property_name, *args, &block) self[property_name] = it it.instance_eval(&block) unless not block_given? or it.instance_of?(Property) end end def to_ary end def wombat_property_format :container end def wombat_property_namespaces nil end protected def build_property(name, *args, &block) if args[1] == :iterator Iterator.new(name, args.first) elsif args[1] == :follow Follower.new(name, args.first) else Property.new(name, *args, &block) end end end end end
Fix SSL on Windows (for Pulse summary).
require 'how_is/version' require 'contracts' C = Contracts module HowIs include Contracts::Core require 'how_is/fetcher' require 'how_is/analyzer' require 'how_is/report' def self.generate_report_file(report_file:, **kw_args) analysis = self.generate_analysis(**kw_args) Report.export!(analysis, report_file) end def self.generate_report(format:, **kw_args) analysis = self.generate_analysis(**kw_args) Report.export(analysis, format) end private Contract C::KeywordArgs[repository: String, from_file: C::Optional[C::Or[String, nil]], fetcher: C::Optional[Class], analyzer: C::Optional[Class], github: C::Optional[C::Any]] => C::Any def self.generate_analysis(repository:, from_file: nil, fetcher: Fetcher.new, analyzer: Analyzer.new, github: nil) if from_file analysis = analyzer.from_file(from_file) else raw_data = fetcher.call(repository, github) analysis = analyzer.call(raw_data) end analysis end end
require 'how_is/version' require 'contracts' require 'cacert' Cacert.set_in_env C = Contracts module HowIs include Contracts::Core require 'how_is/fetcher' require 'how_is/analyzer' require 'how_is/report' def self.generate_report_file(report_file:, **kw_args) analysis = self.generate_analysis(**kw_args) Report.export!(analysis, report_file) end def self.generate_report(format:, **kw_args) analysis = self.generate_analysis(**kw_args) Report.export(analysis, format) end private Contract C::KeywordArgs[repository: String, from_file: C::Optional[C::Or[String, nil]], fetcher: C::Optional[Class], analyzer: C::Optional[Class], github: C::Optional[C::Any]] => C::Any def self.generate_analysis(repository:, from_file: nil, fetcher: Fetcher.new, analyzer: Analyzer.new, github: nil) if from_file analysis = analyzer.from_file(from_file) else raw_data = fetcher.call(repository, github) analysis = analyzer.call(raw_data) end analysis end end
Exclude ruby-vips 2.1.0 and 2.1.1 as buggy
Gem::Specification.new do |spec| spec.name = "dhash-vips" spec.version = "0.1.1.3" spec.author = "Victor Maslov" spec.email = "nakilon@gmail.com" spec.summary = "dHash and IDHash perceptual image hashing/fingerprinting" spec.homepage = "https://github.com/nakilon/dhash-vips" spec.license = "MIT" spec.require_path = "lib" spec.test_files = %w{ test.rb } spec.extensions = %w{ extconf.rb } spec.files = %w{ extconf.rb Gemfile LICENSE.txt common.rb dhash-vips.gemspec idhash.c lib/dhash-vips-post-install-test.rb lib/dhash-vips.rb } spec.add_dependency "ruby-vips", "~>2.0" spec.add_development_dependency "rake" spec.add_development_dependency "minitest" spec.add_development_dependency "rmagick", "~>2.16" spec.add_development_dependency "phamilie" spec.add_development_dependency "dhash" spec.add_development_dependency "get_process_mem" spec.add_development_dependency "mll" end
Gem::Specification.new do |spec| spec.name = "dhash-vips" spec.version = "0.1.1.3" spec.author = "Victor Maslov" spec.email = "nakilon@gmail.com" spec.summary = "dHash and IDHash perceptual image hashing/fingerprinting" spec.homepage = "https://github.com/nakilon/dhash-vips" spec.license = "MIT" spec.require_path = "lib" spec.test_files = %w{ test.rb } spec.extensions = %w{ extconf.rb } spec.files = %w{ extconf.rb Gemfile LICENSE.txt common.rb dhash-vips.gemspec idhash.c lib/dhash-vips-post-install-test.rb lib/dhash-vips.rb } spec.add_dependency "ruby-vips", "~> 2.0", "!= 2.1.0", "!= 2.1.1" spec.add_development_dependency "rake" spec.add_development_dependency "minitest" spec.add_development_dependency "rmagick", "~>2.16" spec.add_development_dependency "phamilie" spec.add_development_dependency "dhash" spec.add_development_dependency "get_process_mem" spec.add_development_dependency "mll" end
Put versions back to 0.0.1, bumping the tag instead
Pod::Spec.new do |spec| spec.name = 'DogeKit' spec.version = '0.0.2' spec.platform = 'ios' spec.license = 'MIT' spec.homepage = 'https://github.com/samjarman/DogeKit' spec.authors = 'Sam Jarman' spec.summary = 'DogeKit for iOS adds much wow to your such application' spec.source = {:git => 'https://github.com/samjarman/DogeKit.git', :tag => 'v0.0.2', } spec.source_files = 'DogeKit.?' spec.requires_arc = true end
Pod::Spec.new do |spec| spec.name = 'DogeKit' spec.version = '0.0.1' spec.platform = 'ios' spec.license = 'MIT' spec.homepage = 'https://github.com/samjarman/DogeKit' spec.authors = 'Sam Jarman' spec.summary = 'DogeKit for iOS adds much wow to your such application' spec.source = {:git => 'https://github.com/samjarman/DogeKit.git', :tag => 'v0.0.1', } spec.source_files = 'DogeKit.?' spec.requires_arc = true end
Implement the 'Calculate All' instruction
require 'yubioath' require 'bindata' module YubiOATH class CalculateAll def self.send(timestamp:, to:) data = Request::Data.new(timestamp: timestamp.to_i / 30) request = Request.new(data: data.to_binary_s) response = ::YubiOATH::Response.read(to.transmit(request.to_binary_s)) throw unless response.success? Response.read(response.data) end class Request < BinData::Record uint8 :cla, value: CLA uint8 :ins, value: 0xA4 uint8 :p1, value: 0x00 uint8 :p2, value: 0x01 uint8 :data_length, value: -> { data.length } string :data class Data < BinData::Record uint8 :challenge_tag, value: 0x74 uint8 :challenge_length, value: 8 uint64be :timestamp end end class Response < BinData::Record class Code < BinData::Record uint8 :digits uint32be :response def to_s (response % 10**digits).to_s.rjust(digits, '0') end end array :codes, read_until: :eof do uint8 :name_tag uint8 :name_length string :name, read_length: :name_length uint8 :response_tag uint8 :response_length code :code, read_length: :response_length end end end end
Add status code to Models::Unparseable
require 'spec_helper' require 'models' describe Models::Unparseable do subject { described_class.new } it { should respond_to :data } end describe Models::Elevator do subject { described_class.new } it { should respond_to :name } it { should respond_to :station } it { should respond_to :systems } end describe Models::Station do subject { described_class.new } it { should respond_to :name } it { should respond_to :systems } it { should respond_to :elevators } end describe Models::System do subject { described_class.new } it { should respond_to :name } it { should respond_to :stations } it { should respond_to :elevators } end
require 'spec_helper' require 'models' describe Models::Unparseable do subject { described_class.new } it { should respond_to :data } it { should respond_to :status_code } end describe Models::Elevator do subject { described_class.new } it { should respond_to :name } it { should respond_to :station } it { should respond_to :systems } end describe Models::Station do subject { described_class.new } it { should respond_to :name } it { should respond_to :systems } it { should respond_to :elevators } end describe Models::System do subject { described_class.new } it { should respond_to :name } it { should respond_to :stations } it { should respond_to :elevators } end
Fix trouble compiling on ruby 1.9.3.
require 'mkmf' if have_library("mbus","mbus_parse") then create_makefile("mbus") else puts "No libmbus support available" end
require 'mkmf' if have_library("mbus","main") then create_makefile("mbus") else puts "No libmbus support available" end