Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add '!' to validate method in pub entity
module Quotes module Entities class Publication < Entity attr_accessor :author, :title, :publisher, :year attr_reader :added_by, :uid def initialize(added_by, author, title, publisher, year, uid = nil) validate(added_by, author, title, publisher, year) @uid = uid @added_by = added_by @author = author @title = title @publisher = publisher @year = year end def update(updates) update_publication_values(updates) self end private def update_publication_values(updates) updates.each do |attribute, updated_value| self.instance_variable_set "@#{attribute}", updated_value end end def validate(added_by, author, title, publisher, year) ['added_by', 'author', 'title', 'publisher', 'year'].each do |param_name| value = eval(param_name) reason = "#{param_name.capitalize} missing" raise_argument_error(reason, value) if value.nil? || value.to_s.empty? end end end end end
module Quotes module Entities class Publication < Entity attr_accessor :author, :title, :publisher, :year attr_reader :added_by, :uid def initialize(added_by, author, title, publisher, year, uid = nil) validate!(added_by, author, title, publisher, year) @uid = uid @added_by = added_by @author = author @title = title @publisher = publisher @year = year end def update(updates) update_publication_values(updates) self end private def update_publication_values(updates) updates.each do |attribute, updated_value| self.instance_variable_set "@#{attribute}", updated_value end end def validate!(added_by, author, title, publisher, year) ['added_by', 'author', 'title', 'publisher', 'year'].each do |param_name| value = eval(param_name) reason = "#{param_name.capitalize} missing" raise_argument_error(reason, value) if value.nil? || value.to_s.empty? end end end end end
Change for our custom repo
Pod::Spec.new do |s| s.name = 'IOSLinkedInAPI' s.version = '1.0.1' s.license = 'MIT' s.summary = 'IOS LinkedIn API capable of accessing LinkedIn using oauth2. Using a UIWebView to fetch the authorization code.' s.homepage = 'https://github.com/jeyben/IOSLinkedInAPI' s.authors = { 'Jacob von Eyben' => 'jacobvoneyben@gmail.com', 'Eduardo Fonseca' => 'hello@eduardo-fonseca.com' } s.source = { :git => 'https://github.com/jeyben/IOSLinkedInAPI.git', :tag => '1.0.0' } s.source_files = 'IOSLinkedInAPI' s.requires_arc = true s.platform = :ios, '6.0' s.dependency 'AFNetworking', '>= 2.0.0' end
Pod::Spec.new do |s| s.name = 'IOSLinkedInAPI' s.version = '1.0.1' s.license = 'MIT' s.summary = 'IOS LinkedIn API capable of accessing LinkedIn using oauth2. Using a UIWebView to fetch the authorization code.' s.homepage = 'https://github.com/jeyben/IOSLinkedInAPI' s.authors = { 'Jacob von Eyben' => 'jacobvoneyben@gmail.com', 'Eduardo Fonseca' => 'hello@eduardo-fonseca.com' } s.source = { :git => 'https://github.com/ebfaed/IOSLinkedInAPI.git', :tag => '1.0.0' } s.source_files = 'IOSLinkedInAPI' s.requires_arc = true s.platform = :ios, '6.0' s.dependency 'AFNetworking', '>= 2.0.0' end
Switch service URL based on Rails environment.
if %(development test).include?(Rails.env) # Require the :client group from the Gemfile Bundler.require :client # Set up +Her+ with the default middleware, and point it # at `http://testables.dev`. Her::API.setup :url => "http://testables.dev" do |faraday| faraday.request :url_encoded faraday.use Her::Middleware::DefaultParseJSON faraday.adapter Faraday.default_adapter end require 'client/worker' namespace :task do desc "Start worker process that runs tasks as available" task :run => :environment do Client::Worker.new.run end end end
if %(development test).include?(Rails.env) # Require the :client group from the Gemfile Bundler.require :client # Point to local host in development mode, # or heroku otherwise. url = Rails.env.development? ? "http://testables.dev" : "http://testabl.es" # Set up +Her+ with the default middleware, and point it # at `http://testables.dev`. Her::API.setup :url => url do |faraday| faraday.request :url_encoded faraday.use Her::Middleware::DefaultParseJSON faraday.adapter Faraday.default_adapter end require 'client/worker' namespace :task do desc "Start worker process that runs tasks as available" task :run => :environment do Client::Worker.new.run end end end
Update gem dependent versions in gemspec.
# coding: utf-8 lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "active_decorator/graphql/version" Gem::Specification.new do |spec| spec.name = "active_decorator-graphql" spec.version = ActiveDecorator::GraphQL::VERSION spec.authors = ["Shimoyama, Hiroyasu"] spec.email = ["h.shimoyama@gmail.com"] spec.summary = %q{A toolkit for decorating GraphQL field objects.} spec.description = %q{A toolkit for decorating GraphQL field objects using ActiveDecorator.} spec.homepage = "https://github.com/hshimoyama/active_decorator-graphql" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.15" spec.add_development_dependency "pry-byebug", "~> 3.0" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.0" spec.add_dependency "active_decorator" spec.add_dependency "graphql" spec.add_dependency "rails" end
# coding: utf-8 lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "active_decorator/graphql/version" Gem::Specification.new do |spec| spec.name = "active_decorator-graphql" spec.version = ActiveDecorator::GraphQL::VERSION spec.authors = ["Shimoyama, Hiroyasu"] spec.email = ["h.shimoyama@gmail.com"] spec.summary = %q{A toolkit for decorating GraphQL field objects.} spec.description = %q{A toolkit for decorating GraphQL field objects using ActiveDecorator.} spec.homepage = "https://github.com/hshimoyama/active_decorator-graphql" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler" spec.add_development_dependency "pry-byebug" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" spec.add_runtime_dependency "active_decorator" spec.add_runtime_dependency "graphql" spec.add_runtime_dependency "rails" end
Remove option that caused exception
class User include Mongoid::Document field :login field :email field :role referenced_in :site, :inverse_of => :users references_many :articles, :foreign_key => :author_id references_many :comments, :dependent => :destroy, :autosave => true, :index => true references_and_referenced_in_many :children, :class_name => "User" references_one :record embeds_one :profile validates :login, :presence => true, :uniqueness => { :scope => :site }, :format => { :with => /^[\w\-]+$/ } validates :email, :uniqueness => { :case_sensitive => false, :scope => :site, :message => "is already taken" }, :confirmation => true validates :role, :presence => true, :inclusion => { :in => ["admin", "moderator", "member"]} validates :profile, :presence => true, :associated => true def admin? false end end
class User include Mongoid::Document field :login field :email field :role referenced_in :site, :inverse_of => :users references_many :articles, :foreign_key => :author_id references_many :comments, :dependent => :destroy, :autosave => true references_and_referenced_in_many :children, :class_name => "User" references_one :record embeds_one :profile validates :login, :presence => true, :uniqueness => { :scope => :site }, :format => { :with => /^[\w\-]+$/ } validates :email, :uniqueness => { :case_sensitive => false, :scope => :site, :message => "is already taken" }, :confirmation => true validates :role, :presence => true, :inclusion => { :in => ["admin", "moderator", "member"]} validates :profile, :presence => true, :associated => true def admin? false end end
Add the local lib file to the LOAD_PATH
ENV["RAILS_ENV"] ||= 'test' gem 'minitest' require 'minitest/autorun' require 'minitest/spec' require 'action_dispatch/railtie' require 'biceps' # Load support files Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
ENV["RAILS_ENV"] ||= 'test' gem 'minitest' require 'minitest/autorun' require 'minitest/spec' require 'action_dispatch/railtie' $:<< 'lib' require 'biceps' # Load support files Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
Remove duplication at the deprecated methods
module SimpleForm module Components module LabelInput extend ActiveSupport::Concern included do include SimpleForm::Components::Labels end def label_input(context=nil) options[:label] == false ? deprecated_input(context) : (deprecated_label(context) + deprecated_input(context)) end private def deprecated_input(context) method = method(:input) if method.arity == 0 ActiveSupport::Deprecation.warn(SimpleForm::CUSTOM_INPUT_DEPRECATION_WARN % { name: 'input' }) method.call else method.call(context) end end def deprecated_label(context) method = method(:label) if method.arity == 0 ActiveSupport::Deprecation.warn(SimpleForm::CUSTOM_INPUT_DEPRECATION_WARN % { name: 'label' }) method.call else method.call(context) end end end end end
module SimpleForm module Components module LabelInput extend ActiveSupport::Concern included do include SimpleForm::Components::Labels end def label_input(context=nil) if options[:label] == false deprecated_component(:input ,context) else deprecated_component(:label, context) + deprecated_component(:input, context) end end private def deprecated_component(namespace ,context) method = method(namespace) if method.arity == 0 ActiveSupport::Deprecation.warn(SimpleForm::CUSTOM_INPUT_DEPRECATION_WARN % { name: namespace }) method.call else method.call(context) end end end end end
Add and use more random generation stuff and better spec for testing
require 'rubygems' require 'bundler' begin Bundler.setup(:default, :development) rescue Bundler::BundlerError => e $stderr.puts e.message $stderr.puts "Run `bundle install` to install missing gems" exit e.status_code end require 'simplecov' require 'minitest' require 'minitest/unit' require 'minitest/autorun' require 'minitest/reporters' $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'nodus' class Reporter < Minitest::Reporters::BaseReporter def start super puts "# AWESOME!" puts end end Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new module SimpleCov::Configuration def clean_filters @filters = [] end end SimpleCov.configure do clean_filters load_adapter 'test_frameworks' end ENV["COVERAGE"] && SimpleCov.start do add_filter "/.rvm/" end class MiniTest::Unit::TestCase end
require 'rubygems' require 'bundler' begin Bundler.setup(:default, :development) rescue Bundler::BundlerError => e $stderr.puts e.message $stderr.puts "Run `bundle install` to install missing gems" exit e.status_code end require 'simplecov' require 'faker' require 'randexp' require 'minitest' require 'minitest/reporters' require 'minitest/spec' require 'minitest/autorun' $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'nodus' Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new module SimpleCov::Configuration def clean_filters @filters = [] end end SimpleCov.configure do clean_filters load_adapter 'test_frameworks' end ENV["COVERAGE"] && SimpleCov.start do add_filter "/.rvm/" end I18n.enforce_available_locales = false include Faker module RandomGen def rand_poisson(lmbda=10) # Poisson distribution with mean & variance of lmda- via knuth's simple algorithm el = Math.exp(- lmbda); k=0; p=1 loop do k += 1; p *= rand return k - 1 if p <= el end end def rand_times(lmbda=10, &block) k = rand_poisson(lmbda) if block_given? then k.times.map(&block) else k.times end end def rand_word len = rand_poisson return '' if len == 0 /\w{#{len}}/.gen end def random_path '/' + rand_times{rand_word}.join('/') end end include RandomGen
Set the version number to 0.2.0.
Pod::Spec.new do |s| s.name = 'MRGArchitect' s.version = '0.1.1' s.license = 'BSD 3-Clause' s.summary = 'Static application configuration via JSON' s.homepage = 'https://github.com/mirego/MRGArchitect' s.authors = { 'Mirego, Inc.' => 'info@mirego.com' } s.source = { :git => 'https://github.com/mirego/MRGArchitect.git', :tag => s.version.to_s } s.source_files = 'MRGArchitect/*.{h,m}' s.requires_arc = true s.platform = :ios, '6.0' end
Pod::Spec.new do |s| s.name = 'MRGArchitect' s.version = '0.2.0' s.license = 'BSD 3-Clause' s.summary = 'Static application configuration via JSON' s.homepage = 'http://open.mirego.com' s.authors = { 'Mirego, Inc.' => 'info@mirego.com' } s.source = { :git => 'https://github.com/mirego/MRGArchitect.git', :tag => s.version.to_s } s.source_files = 'MRGArchitect/*.{h,m}' s.requires_arc = true s.platform = :ios, '6.0' end
Use Rack::Utils escape instead of CGI as it's included in Rack and may fix the travis build :)
module OmniAuth # This simple Rack endpoint that serves as the default # 'failure' mechanism for OmniAuth. If a strategy fails for # any reason this endpoint will be invoked. The default behavior # is to redirect to `/auth/failure` except in the case of # a development `RACK_ENV`, in which case an exception will # be raised. class FailureEndpoint attr_reader :env def self.call(env) new(env).call end def initialize(env) @env = env end def call raise_out! if ENV['RACK_ENV'].to_s == 'development' redirect_to_failure end def raise_out! raise env['omniauth.error'] || OmniAuth::Error.new(env['omniauth.error.type']) end def redirect_to_failure message_key = env['omniauth.error.type'] new_path = "#{env['SCRIPT_NAME']}#{OmniAuth.config.path_prefix}/failure?message=#{message_key}#{origin_query_param}#{strategy_name_query_param}" Rack::Response.new(["302 Moved"], 302, 'Location' => new_path).finish end def strategy_name_query_param return "" unless env['omniauth.error.strategy'] "&strategy=#{env['omniauth.error.strategy'].name}" end def origin_query_param return "" unless env['omniauth.origin'] "&origin=#{CGI.escape(env['omniauth.origin'])}" end end end
module OmniAuth # This simple Rack endpoint that serves as the default # 'failure' mechanism for OmniAuth. If a strategy fails for # any reason this endpoint will be invoked. The default behavior # is to redirect to `/auth/failure` except in the case of # a development `RACK_ENV`, in which case an exception will # be raised. class FailureEndpoint attr_reader :env def self.call(env) new(env).call end def initialize(env) @env = env end def call raise_out! if ENV['RACK_ENV'].to_s == 'development' redirect_to_failure end def raise_out! raise env['omniauth.error'] || OmniAuth::Error.new(env['omniauth.error.type']) end def redirect_to_failure message_key = env['omniauth.error.type'] new_path = "#{env['SCRIPT_NAME']}#{OmniAuth.config.path_prefix}/failure?message=#{message_key}#{origin_query_param}#{strategy_name_query_param}" Rack::Response.new(["302 Moved"], 302, 'Location' => new_path).finish end def strategy_name_query_param return "" unless env['omniauth.error.strategy'] "&strategy=#{env['omniauth.error.strategy'].name}" end def origin_query_param return "" unless env['omniauth.origin'] "&origin=#{Rack::Utils.escape(env['omniauth.origin'])}" end end end
Add tests for patched User
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe User do before(:all) do @user = FactoryGirl.create(:user) end subject { @user } it { should be_valid } it { should respond_to(:gitolite_identifier) } it "has a gitolite_identifier" do expect(@user.gitolite_identifier).to match(/redmine_user\d+_\d+/) end end
Work around RSpec + 1.9.2 issue with pending specs.
require File.expand_path("spec_helper", File.dirname(__FILE__)) require "watir-webdriver/extensions/wait" describe Watir::Wait do describe "#until" do it "waits until the block returns true" it "times out" end describe "#while" do it "waits while the block returns true" it "times out" end end describe Watir::Element do describe "#present?" do it "returns true if the element exists and is visible" it "returns false if the element exists but is not visible" it "returns false if the element does not exist" end describe "#when_present" do it "invokes subsequent methods after waiting for the element's presence" it "times out" end end
require File.expand_path("spec_helper", File.dirname(__FILE__)) require "watir-webdriver/extensions/wait" describe Watir::Wait do describe "#until" do it "waits until the block returns true" do pending end it "times out" do pending end end describe "#while" do it "waits while the block returns true" do pending end it "times out" do pending end end end describe Watir::Element do describe "#present?" do it "returns true if the element exists and is visible" do pending end it "returns false if the element exists but is not visible" do pending end it "returns false if the element does not exist" do pending end end describe "#when_present" do it "invokes subsequent methods after waiting for the element's presence" do pending end it "times out" do pending end end end
Fix source in podspec file.
Pod::Spec.new do |s| s.name = "RNDeviceInfo" s.version = "0.4.0" s.summary = "Device Information for react-native" s.homepage = "https://github.com/rebeccahughes/react-native-device-info" s.license = "MIT" s.platform = :ios, "7.0" s.source = { :git => "https://github.com/rebeccahughes/react-native-device-info", :head } s.source_files = "RNDeviceInfo/*.{h,m}" end
Pod::Spec.new do |s| s.name = "RNDeviceInfo" s.version = "0.4.0" s.summary = "Device Information for react-native" s.homepage = "https://github.com/rebeccahughes/react-native-device-info" s.license = "MIT" s.platform = :ios, "7.0" s.source = { :git => "https://github.com/rebeccahughes/react-native-device-info" } s.source_files = "RNDeviceInfo/*.{h,m}" end
Order feeds by last activity
xml.instruct! :xml, version: '1.0' xml.feed xmlns: 'http://www.w3.org/2005/Atom' do xml.id category_feed_url(@category) xml.title "New Questions - #{@category.name} - #{SiteSetting['SiteName']}" xml.author do xml.name "#{SiteSetting['SiteName']} - Codidact" end xml.link nil, rel: 'self', href: category_url(@category) xml.updated @posts.maximum(:created_at)&.iso8601 || RequestContext.community.created_at&.iso8601 @posts.each do |post| xml.entry do xml.id question_url(post) xml.title post.title xml.author do xml.name post.user.username xml.uri user_url(post.user) end xml.published post.created_at&.iso8601 xml.updated post.updated_at&.iso8601 xml.link href: question_path(post) xml.summary post.body.truncate(200), type: 'html' end end end
xml.instruct! :xml, version: '1.0' xml.feed xmlns: 'http://www.w3.org/2005/Atom' do xml.id category_feed_url(@category) xml.title "New Questions - #{@category.name} - #{SiteSetting['SiteName']}" xml.author do xml.name "#{SiteSetting['SiteName']} - Codidact" end xml.link nil, rel: 'self', href: category_url(@category) xml.updated @posts.maximum(:last_activity)&.iso8601 || RequestContext.community.created_at&.iso8601 @posts.each do |post| xml.entry do xml.id question_url(post) xml.title post.title xml.author do xml.name post.user.username xml.uri user_url(post.user) end xml.published post.created_at&.iso8601 xml.updated post.last_activity&.iso8601 xml.link href: question_path(post) xml.summary post.body.truncate(200), type: 'html' end end end
Add comments to confusing metaprogramming
module CoreExtensions module RubifyKeys # Creates methods #rubify_keys! and #unrubify_keys! {"rubify" => "snake_case", "unrubify" => "camel_case"}.each do |name, kase| method_name = "#{name}_keys!" define_method(method_name) do keys.each do |key| val = delete(key) new_key = self.send("convert_to_#{kase}", key.to_s) self[new_key] = val val.send(method_name) if val.is_a?(Hash) val.each { |p| p.send(method_name) if p.is_a?(Hash) } if val.is_a?(Array) end self end end private_class_method def convert_to_snake_case(string) string.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end def convert_to_camel_case(string) arr = string.split(/[_,-]/).inject([]) do |buffer,e| buffer.push(buffer.empty? ? e : e.capitalize) end arr.join end end end
module CoreExtensions module RubifyKeys # Dynamically creates methods #rubify_keys! and #unrubify_keys!, each of which # modify the object in place {"rubify" => "snake_case", "unrubify" => "camel_case"}.each do |name, kase| method_name = "#{name}_keys!" define_method(method_name) do keys.each do |key| val = delete(key) new_key = self.send("convert_to_#{kase}", key.to_s) self[new_key] = val # Recursively call method on any nested hashes val.send(method_name) if val.is_a?(Hash) val.each { |p| p.send(method_name) if p.is_a?(Hash) } if val.is_a?(Array) end self end end private_class_method def convert_to_snake_case(string) string.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end def convert_to_camel_case(string) arr = string.split(/[_,-]/).inject([]) do |buffer,e| buffer.push(buffer.empty? ? e : e.capitalize) end arr.join end end end
Add helper method for race categories
module Admin::RacesHelper def link_to_events(race) html = "" race.event.ancestors.reverse.each do |e| html << link_to(truncate(e.name, :length => 40), edit_admin_event_path(e), :class => "obvious") html << ": " end html << link_to(truncate(race.event.name, :length => 40), edit_admin_event_path(race.event), :class => "obvious") html << ": " html end end
module Admin::RacesHelper def link_to_events(race) html = "" race.event.ancestors.reverse.each do |e| html << link_to(truncate(e.name, :length => 40), edit_admin_event_path(e), :class => "obvious") html << ": " end html << link_to(truncate(race.event.name, :length => 40), edit_admin_event_path(race.event), :class => "obvious") html << ": " html end # BAR category or Rider Rankings category def competition_category_name(race) if race && race.category if race.category.parent return race.category.parent.name else return race.category.name end end "" end end
Allow spree 2.1 and 2.2
# -*- encoding: utf-8 -*- require File.expand_path('../lib/alchemy/spree/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Thomas von Deyen"] gem.email = ["tvd@magiclabs.de"] gem.description = %q{A Alchemy CMS and Spree connector} gem.summary = %q{The World's Most Flexible E-Commerce Platform meets The World's Most Flexible Content Management System!} gem.homepage = "https://github.com/magiclabs/alchemy_spree" gem.license = 'BSD New' gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } gem.files = `git ls-files`.split("\n") gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") gem.name = "alchemy_spree" gem.require_paths = ["lib"] gem.version = Alchemy::Spree::VERSION gem.add_dependency('alchemy_cms', ['~> 3.0.0.rc4']) gem.add_dependency('spree', ['~> 2.1.5']) end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/alchemy/spree/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Thomas von Deyen"] gem.email = ["tvd@magiclabs.de"] gem.description = %q{A Alchemy CMS and Spree connector} gem.summary = %q{The World's Most Flexible E-Commerce Platform meets The World's Most Flexible Content Management System!} gem.homepage = "https://github.com/magiclabs/alchemy_spree" gem.license = 'BSD New' gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } gem.files = `git ls-files`.split("\n") gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") gem.name = "alchemy_spree" gem.require_paths = ["lib"] gem.version = Alchemy::Spree::VERSION gem.add_dependency('alchemy_cms', ['~> 3.0.0.rc4']) gem.add_dependency('spree', ['>= 2.1', '< 3.0']) end
Add missing utf-8 encoding comment
# `cop` and `source` must be declared with #let. shared_examples_for 'accepts' do it 'accepts' do inspect_source(cop, source) expect(cop.offences).to be_empty end end shared_examples_for 'mimics MRI 2.0' do |grep_mri_warning| if RUBY_ENGINE == 'ruby' && RUBY_VERSION.start_with?('2.0') it "mimics MRI #{RUBY_VERSION} built-in syntax checking" do inspect_source(cop, source) offences_by_mri = MRISyntaxChecker.offences_for_source( source, cop.name, grep_mri_warning ) # Compare objects before comparing counts for clear failure output. cop.offences.each_with_index do |offence_by_cop, index| offence_by_mri = offences_by_mri[index] # Exclude column attribute since MRI does not # output column number. [:severity, :line, :cop_name, :message].each do |a| expect(offence_by_cop.send(a)).to eq(offence_by_mri.send(a)) end end expect(cop.offences.count).to eq(offences_by_mri.count) end end end
# encoding: utf-8 # `cop` and `source` must be declared with #let. shared_examples_for 'accepts' do it 'accepts' do inspect_source(cop, source) expect(cop.offences).to be_empty end end shared_examples_for 'mimics MRI 2.0' do |grep_mri_warning| if RUBY_ENGINE == 'ruby' && RUBY_VERSION.start_with?('2.0') it "mimics MRI #{RUBY_VERSION} built-in syntax checking" do inspect_source(cop, source) offences_by_mri = MRISyntaxChecker.offences_for_source( source, cop.name, grep_mri_warning ) # Compare objects before comparing counts for clear failure output. cop.offences.each_with_index do |offence_by_cop, index| offence_by_mri = offences_by_mri[index] # Exclude column attribute since MRI does not # output column number. [:severity, :line, :cop_name, :message].each do |a| expect(offence_by_cop.send(a)).to eq(offence_by_mri.send(a)) end end expect(cop.offences.count).to eq(offences_by_mri.count) end end end
Add tests for Course class methods
require 'rails_helper' describe Course do let(:user) { build(:user) } describe '.courses_for_person' do before(:each) do allow(described_class).to receive(:collection_for_person) end it 'calls .collection_for_person' do expect(described_class).to receive(:collection_for_person).with(1) described_class.courses_for_person(1) end end describe '._collection_for_person' do let(:relation) { double('relation') } before(:each) do allow(described_class) .to receive(:teacher_id_or_student_id_matches) .and_return(:foo) allow(described_class).to receive(:joins).and_return(relation) allow(relation).to receive(:where).and_return(relation) allow(relation).to receive(:distinct) end after(:each) do described_class.send(:_collection_for_person, 1) end it 'calls .teacher_id_or_student_id_matches' do expect(described_class) .to receive(:teacher_id_or_student_id_matches) .with(1) end it 'calls .joins' do expect(described_class).to receive(:joins).with(:enrollments) end it 'calls .where' do expect(relation).to receive(:where).with(:foo) end it 'calls .distinct' do expect(relation).to receive(:distinct) end end end
Fix the test with fakefs
require 'test_helper' require 'fakefs/safe' require 'apns-s3' class TestApnsS3 < Test::Unit::TestCase setup do @pem_filename = 'dummy.pem' end test "pemfile exists" do stub(ApnsS3).pemfile_exist?(@pem_filename) { true } mock(APNS).pem=(@pem_filename) ApnsS3.set_pemfile filename: @pem_filename end test "pemfile DOES NOT exist" do stub(ApnsS3).pemfile_exist?(@pem_filename) { false } credentials_stub = Object.new stub(Aws::Credentials).new { credentials_stub } region = 'dummy-region-name' stub(Aws.config).update(region: region, credentials: credentials_stub) client_stub = Object.new stub(Aws::S3::Client).new { client_stub } stub(client_stub).get_object mock(APNS).pem=(@pem_filename) ApnsS3.set_pemfile region: region, filename: @pem_filename end end
require 'test_helper' require 'fakefs/safe' require 'apns-s3' class TestApnsS3 < Test::Unit::TestCase setup do @pem_filename = 'dummy.pem' end test "pemfile exists" do # FakeFS do # FileUtils.touch @pem_filename # mock(APNS).pem=(@pem_filename) # ApnsS3.set_pemfile filename: @pem_filename # end # # # NOTE: this code makes a warning below: # # .../vendor/bundle/ruby/2.4.0/gems/fakefs-0.10.2/lib/fakefs/base.rb:21:warning: instance variable @activated not initialized FakeFS.activate! FileUtils.touch @pem_filename mock(APNS).pem=(@pem_filename) ApnsS3.set_pemfile filename: @pem_filename FakeFS.deactivate! end test "pemfile DOES NOT exist" do assert !File.exist?(@pem_filename) client_stub = Object.new stub(Aws::S3::Client).new { client_stub } stub(client_stub).get_object mock(APNS).pem=(@pem_filename) ApnsS3.set_pemfile region: 'fake-region', filename: @pem_filename end end
Implement update method for tips controller
class TipsController < ApplicationController attr_accessor :content def index @tips = Tip.order("created_at").reverse end def search @tips = Tip.search(params[:q]) render "index" end def show @tip = Tip.find(params[:id]) end def new @tip = Tip.new() end def edit @tip = Tip.find(params[:id]) end def create attributes = params.require(:tip).permit(:title, :body, :tags, :category, :language, :author) @tip = Tip.new(attributes) # @tip = Tip.new(params[:tip]) if @tip.save redirect_to @tip, notice: "Posted tip" else render "new" end end def update end def destroy @tip = Tip.find(params[:id]) @tip.destroy redirect_to :tips, notice: "Deleted article" end end
class TipsController < ApplicationController attr_accessor :content def index @tips = Tip.order("created_at").reverse end def search @tips = Tip.search(params[:q]) render "index" end def show @tip = Tip.find(params[:id]) end def new @tip = Tip.new() end def edit @tip = Tip.find(params[:id]) end def create attributes = params.require(:tip).permit(:title, :body, :tags, :category, :language, :author) @tip = Tip.new(attributes) # @tip = Tip.new(params[:tip]) if @tip.save redirect_to @tip, notice: "Posted tip" else render "new" end end def update @tip = Tip.find(params[:id]) attributes = params.require(:tip).permit(:title, :body, :tags, :category, :language, :author) @tip.assign_attributes(attributes) if @tip.save redirect_to @tip, notice: "Updated tip" else render "new" end end def destroy @tip = Tip.find(params[:id]) @tip.destroy redirect_to :tips, notice: "Deleted article" end end
Add error/success helper functions mainly for non-ajax form submission
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper end
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper def display_success if !flash[:success] || flash[:success].empty? return '' end ret = '<ul id="success">' flash[:success].each do |s| ret = ret + '<li>' + s + '</li>' end ret = ret + '</ul>' return ret end def display_errors if !flash[:errors] || flash[:errors].empty? return '' end ret = '<ul id="errors">' flash[:errors].each_full do |e| ret = ret + '<li>' + e + '</li>' end ret = ret + '</ul>' return ret end end
Remove caching in node changes template
module Api::PoiLog extend ActiveSupport::Concern included do def around_api_response(api_template) custom_cache_key = "api_response_#{I18n.locale}_#{self.cache_key}_#{api_template.to_s}" Rails.cache.fetch(custom_cache_key, :expires_in => 1.hour) do yield end end # API template for '/nodes/changes' api_accessible :changes_stream do |t| t.add :osm_id t.add :action t.add lambda { |poi| poi.created_at }, :as => :timestamp end end end
module Api::PoiLog extend ActiveSupport::Concern included do # API template for '/nodes/changes' api_accessible :changes_stream do |t| t.add :osm_id t.add :action t.add lambda { |poi| poi.created_at }, :as => :timestamp end end end
Add database cleaner rspec support.
RSpec.configure do |config| config.before(:suite) do DatabaseCleaner.clean end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end
Sort filters by field since where() hashes do not have a fixed order
module POSLavu::APIStub def poslavu_api_stub(params = {}, &block) stub = stub_http_request(:post, POSLavu::Client::URL).with(:body => hash_including(params)) if block stub.to_return { |request| response = block.call(request) if response.instance_of?(Hash) response else body = case response when Array then response.map(&:to_xml).join # assume array of rows when POSLavu::Row then response.to_xml else response.to_s end { :body => body, :status => 200 } end } end stub end def have_requested_poslavu_api(params = {}) expected_filters = params.delete('filters') have_requested(:post, POSLavu::Client::URL).with(:body => hash_including(params)) { |req| if expected_filters # filters is JSON, which needs to be an equivalent data structure params = WebMock::Util::QueryMapper.query_to_values(req.body) if actual_filters = params['filters'] # request has parameter # parse both expected = MultiJson.load(expected_filters) actual = MultiJson.load(actual_filters) # compare expected == actual else # request missing parameter; fail false end else # no filters parameter; match true end } end end
module POSLavu::APIStub def poslavu_api_stub(params = {}, &block) stub = stub_http_request(:post, POSLavu::Client::URL).with(:body => hash_including(params)) if block stub.to_return { |request| response = block.call(request) if response.instance_of?(Hash) response else body = case response when Array then response.map(&:to_xml).join # assume array of rows when POSLavu::Row then response.to_xml else response.to_s end { :body => body, :status => 200 } end } end stub end def have_requested_poslavu_api(params = {}) expected_filters = params.delete('filters') have_requested(:post, POSLavu::Client::URL).with(:body => hash_including(params)) { |req| if expected_filters # filters is JSON, which needs to be an equivalent data structure params = WebMock::Util::QueryMapper.query_to_values(req.body) if actual_filters = params['filters'] # request has parameter # parse both expected = MultiJson.load(expected_filters).sort_by { |f| f['field'] } actual = MultiJson.load(actual_filters).sort_by { |f| f['field'] } # compare expected == actual else # request missing parameter; fail false end else # no filters parameter; match true end } end end
Move function for writing Git provenance header into a support module
# Support functions used by the Pallet Jack tools require 'rugged' # Return a string stating the Git provenance of a warehouse directory, # suitable for inclusion at the top of a generated configuration file, # with each line prefixed by +comment_char+. # # If +warehouse_path+ points within a Git repository, return a string # stating its absolute path, active branch and commit ID. # # If Git information cannot be found for +warehouse_path+, return a # string stating its path and print an error message on stderr. def git_header(tool_name, warehouse_path, comment_char = '#') repo = Rugged::Repository.discover(warehouse_path) workdir = repo.workdir branch = repo.head.name commit = repo.head.target_id return "#{comment_char}#{comment_char} #{comment_char}#{comment_char} Automatically generated by #{tool_name} from #{comment_char}#{comment_char} Repository: #{workdir} #{comment_char}#{comment_char} Branch: #{branch} #{comment_char}#{comment_char} Commit ID: #{commit} #{comment_char}#{comment_char} " rescue STDERR.puts "Error finding Git sourcing information: #{$!}" return "#{comment_char}#{comment_char} #{comment_char}#{comment_char} Automatically generated by #{tool_name} from #{warehouse_path} #{comment_char}#{comment_char} " end
Move sleep variables into settings file
require 'fallen' require 'fallen/cli' require 'data_mapper' require_relative 'postman/config' require_relative 'postman/database' require_relative 'postman/adapter' module Postman extend Fallen extend Fallen::CLI URGENT_QUOTA = 100 NORMAL_QUOTA = 100 LOW_QUOTA = 100 @@normal_sleep = 0 @@low_sleep = 0 def self.run while running? mails = [] #Urgent mails mails.concat Postman.find_mails(MailUrgent, Postman.settings['urgent_quota']) @@normal_sleep += 1 @@low_sleep += 1 if(@@normal_sleep == 12) mails.concat Postman.find_mails(MailNormal, Postman.settings['normal_quota']) @@normal_sleep = 0 end if(@@low_sleep == 54) mails.concat Postman.find_mails(MailLow, Postman.settings['low_quota']) @@low_sleep = 0 end Postman.send_mails(mails) sleep 5 end end end case Clap.run(ARGV, Postman.cli).first when "start" Postman.start! when "stop" Postman.stop! else Postman.fallen_usage end
require 'fallen' require 'fallen/cli' require 'data_mapper' require_relative 'postman/config' require_relative 'postman/database' require_relative 'postman/adapter' module Postman extend Fallen extend Fallen::CLI URGENT_QUOTA = 100 NORMAL_QUOTA = 100 LOW_QUOTA = 100 @@normal_sleep = 0 @@low_sleep = 0 def self.run while running? mails = [] #Urgent mails mails.concat Postman.find_mails(MailUrgent, Postman.settings['urgent_quota']) @@normal_sleep += 1 @@low_sleep += 1 if(@@normal_sleep == Postman.settings['normal_sleep']) mails.concat Postman.find_mails(MailNormal, Postman.settings['normal_quota']) @@normal_sleep = 0 end if(@@low_sleep == Postman.settings['low_sleep']) mails.concat Postman.find_mails(MailLow, Postman.settings['low_quota']) @@low_sleep = 0 end Postman.send_mails(mails) sleep Postman.settings['sleep'] end end end case Clap.run(ARGV, Postman.cli).first when "start" Postman.start! when "stop" Postman.stop! else Postman.fallen_usage end
Remove incorrect c from is_tax_exempt
Promiscuous.define do subscribe :customer do attributes :entity_id, :contact_id, :location_id, :parent_customer_id, :salesperson_id, :deleted_at, :bill_to_location_id, :ship_to_location_id, :is_tax_excempt, :is_active, :uuid end end
Promiscuous.define do subscribe :customer do attributes :entity_id, :contact_id, :location_id, :parent_customer_id, :salesperson_id, :deleted_at, :bill_to_location_id, :ship_to_location_id, :is_tax_exempt, :is_active, :uuid end end
Add Diaclone::Result, the object that transformers pass around
# Parse result that's passed around in the stack and eventually returned # at the end of parsing. Includes a `lines` array for holding each line # of the message, a `body` string for holding the entire raw message # data, and a `hash` that is eventually read into the `ActiveRecord` object # for storage in the database and dissemination to eLocal.com. # # A result must start with a body, but this can be an empty string so # long as the other ^fields are filled out. These fields, like `lines` # and `hash`, can be populated here as well, so one can "preload" # the result with test data or begin at a specific point in the stack. # # Example: # # Diaclone::Result.new "Message: body." # Diaclone::Result.new "", hash: { message: "body." } module Diaclone class Result attr_accessor :body, :lines, :hash def initialize(body, options={}) @body, @lines, @hash, @extras = body, [], {}, nil unless options.empty? options.each do |property, value| send :"#{property}=", value end end end # Make an exact duplicate of this Result, allowing experimentation # or modulation without touching the original object (or perhaps # creating an entirely new object to pass around). def dup pr = Result.new(body) pr.lines = lines.nil? ? nil : lines.dup pr.hash = hash.nil? ? nil : hash.dup pr.extras = extras.nil? ? nil : extras.dup pr end # Access the Hash if a symbol is passed in as the key, otherwise # access the `lines` array. def [] key if key.is_a? Symbol self.hash[key] else self.lines[key] end end # Mutate the Hash if a symbol is passed in as the key, otherwise # mutate the `lines` array. def []= key, value self.hash[key] = value end # Print the parsed Hash as a String. def to_s self.hash.reduce("") { |a,(k,v)| a << "#{k}: #{v}" } end # Print the raw body as a String. def raw self.body end # Delete a key from the Hash. def delete key self.hash.delete key end # An Array of all attributes in the Hash. def keys self.hash.keys end end end
Include more documentation for Biased::Client
require "httparty" require "wikipedia" module Biased # @author Justin Harrison # @since 0.0.1 # @attr_reader [String] parent The potentially biased website's parent # organization. class Client attr_reader(:parent) # @param [String] domain The potentially biased website's domain. def initialize(domain) @domain = domain @parent = gather_from_wikipedia end # Gathers the parent organization of any website from wikipedia # if possible. # @since 0.0.1 # @return [String, nil] The parent organization or nil. def gather_from_wikipedia parent = nil content = Wikipedia.find(@domain).content # Wikipedia has multiple fields for a parent organization, # so we need to try each one %w(parent owner).each do |field| # This Regex should be cleaned up. match = /(#{field}\s*=\s\[\[)(.*\w+)/.match(content) if match parent = match[2] break end end parent end end end
require "httparty" require "wikipedia" module Biased # The main class that a end user will use to interact with the application. # @author Justin Harrison # @since 0.0.1 # @attr_reader [String] parent The potentially biased website's parent # organization. # Biased::Client.new("huffingtonpost.com") class Client attr_reader(:parent) # @param [String] domain The potentially biased website's domain. def initialize(domain) @domain = domain @parent = gather_from_wikipedia end # Gathers the parent organization of any website from wikipedia # if possible. # @since 0.0.1 # @return [String, nil] The parent organization or nil. def gather_from_wikipedia parent = nil content = Wikipedia.find(@domain).content # Wikipedia has multiple fields for a parent organization, # so we need to try each one %w(parent owner).each do |field| # This Regex should be cleaned up. match = /(#{field}\s*=\s\[\[)(.*\w+)/.match(content) if match parent = match[2] break end end parent end end end
Add ability to define a custom view key resolver
class Roda module RodaPlugins module DryView def self.load_dependencies(app) app.plugin :flow end module InstanceMethods def view_context self.class["view.context"].with(view_context_options) end def view_context_options {} end end module RequestMethods def view(name, options = {}) options = {context: scope.view_context}.merge(options) is to: "views.#{name}", call_with: [options] end end end register_plugin :dry_view, DryView end end
class Roda module RodaPlugins module DryView def self.load_dependencies(app) app.plugin :flow end module InstanceMethods def view_context self.class["view.context"].with(view_context_options) end def view_context_options {} end def view_key(name) "views.#{name}" end end module RequestMethods def view(name, options = {}) options = {context: scope.view_context}.merge(options) is to: scope.view_key(name), call_with: [options] end end end register_plugin :dry_view, DryView end end
Validate the presence of campus and unit activity set
class CampusActivitySet < ActiveRecord::Base end
class CampusActivitySet < ActiveRecord::Base belongs_to :campus belongs_to :unit_activity_set validates :campus, presence: true validates :unit_activity_set, presence: true end
Load Extensions before rails initialize
Rails.application.config.after_initialize do extensions_path = "#{Rails.root}/lib/extensions" # Load the base Extensions module require "#{extensions_path}.rb" # Get the extensions, sort by file name so the parent modules are included first extensions = Dir["#{extensions_path}/**/*.rb"] extensions.sort! extensions.each do |path| require path # Deduce the class we are trying to extend relative_path = path.slice(extensions_path.length + 1, path.length) relative_dir = File.dirname(relative_path) relative_dir = if relative_dir == '.' '' else relative_dir + '/' end filename = File.basename(relative_path, File.extname(relative_path)) relative_filename = "#{relative_dir}#{filename}" class_to_extend = relative_filename.camelize module_to_include_name = "Extensions::#{class_to_extend}" module_to_include = module_to_include_name.constantize module_to_extend_name = "#{module_to_include}::ClassMethods" class_to_extend.constantize.class_eval do include module_to_include if module_to_include.const_defined?(module_to_extend_name, false) extend module_to_extend.constantize end end end end
Rails.application.config.before_initialize do extensions_path = "#{Rails.root}/lib/extensions" # Load the base Extensions module require "#{extensions_path}.rb" # Get the extensions, sort by file name so the parent modules are included first extensions = Dir["#{extensions_path}/**/*.rb"] extensions.sort! extensions.each do |path| require path # Deduce the class we are trying to extend relative_path = path.slice(extensions_path.length + 1, path.length) relative_dir = File.dirname(relative_path) relative_dir = if relative_dir == '.' '' else relative_dir + '/' end filename = File.basename(relative_path, File.extname(relative_path)) relative_filename = "#{relative_dir}#{filename}" class_to_extend = relative_filename.camelize module_to_include_name = "Extensions::#{class_to_extend}" module_to_include = module_to_include_name.constantize module_to_extend_name = "#{module_to_include}::ClassMethods" class_to_extend.constantize.class_eval do include module_to_include if module_to_include.const_defined?(module_to_extend_name, false) extend module_to_extend.constantize end end end end
Prepare Pod Spec for ad-hoc usage.
Pod::Spec.new do |s| s.name = 'MagicalRecord' s.version = '1.8' s.license = 'MIT' s.summary = 'Effortless fetching, saving, and importing for Core Data.' s.homepage = 'http://github.com/magicalpanda/MagicalRecord' s.author = { 'Saul Mora' => 'saul@magicalpanda.com', 'Zachary Waldowski' => 'zwaldowski@gmail.com', 'Alexsander Akers' => 'a2@pandamonia.us' } s.source = { :git => 'http://github.com/zwaldowski/MagicalRecord.git' } s.source_dirs = 'Source' s.framework = 'CoreData' s.requires_arc = true def s.post_install(target) prefix_header = config.project_pods_root + target.prefix_header_filename prefix_header.open('a') do |file| file.puts(%{#ifdef __OBJC__\n#import "MagicalRecord.h"\n#endif}) end end end
Pod::Spec.new do |s| s.name = 'MagicalRecord' s.license = 'MIT' s.summary = 'Effortless fetching, saving, and importing for Core Data.' s.homepage = 'http://github.com/magicalpanda/MagicalRecord' s.author = { 'Saul Mora' => 'saul@magicalpanda.com', 'Zachary Waldowski' => 'zwaldowski@gmail.com', 'Alexsander Akers' => 'a2@pandamonia.us' } s.source = { :git => 'http://github.com/zwaldowski/MagicalRecord.git' } s.source_dirs = 'Source' s.clean_paths = 'iOS App Unit Tests/', 'Mac App Unit Tests/', 'Magical Record.xcodeproj/', 'Unit Tests/', '.gitignore' s.framework = 'CoreData' s.requires_arc = true def s.post_install(target) prefix_header = config.project_pods_root + target.prefix_header_filename prefix_header.open('a') do |file| file.puts(%{#ifdef __OBJC__\n#import "MagicalRecord.h"\n#endif}) end end end
Add order in room list
class RoomsController < ApplicationController before_action :authenticate, except: [:github] def index @rooms = current_user.rooms end def create @room = Rooms::Creator.new(room_params).call if @room.persisted? render :show, status: :created else fail BadRequest, @room.errors.messages end end def join membership = Rooms::Joiner.new(user: current_user, room: join_room).call if membership.persisted? render :show, status: :created else fail BadRequest, membership.errors.messages end end def left Rooms::Leaver.new(member: current_user, room: room).call head :no_content end def switch Rooms::Switcher.new(user: current_user, room: room).call head :no_content end def destroy Rooms::Destroyer.new(owner: current_user, room: room).call head :no_content end def github Rooms::GithubIntegrator.new(room: Room.find_by!(github_token: params[:token]), params: params).call head :no_content end private def join_room @room ||= Room.find_by! join_room_params end def room @room ||= Room.find params[:id] end def room_params params.require(:room).permit(:name).merge(owner: current_user) end def join_room_params params.require(:room).permit(:join_token) end end
class RoomsController < ApplicationController before_action :authenticate, except: [:github] def index @rooms = current_user.rooms.order :id end def create @room = Rooms::Creator.new(room_params).call if @room.persisted? render :show, status: :created else fail BadRequest, @room.errors.messages end end def join membership = Rooms::Joiner.new(user: current_user, room: join_room).call if membership.persisted? render :show, status: :created else fail BadRequest, membership.errors.messages end end def left Rooms::Leaver.new(member: current_user, room: room).call head :no_content end def switch Rooms::Switcher.new(user: current_user, room: room).call head :no_content end def destroy Rooms::Destroyer.new(owner: current_user, room: room).call head :no_content end def github Rooms::GithubIntegrator.new(room: Room.find_by!(github_token: params[:token]), params: params).call head :no_content end private def join_room @room ||= Room.find_by! join_room_params end def room @room ||= Room.find params[:id] end def room_params params.require(:room).permit(:name).merge(owner: current_user) end def join_room_params params.require(:room).permit(:join_token) end end
Fix exit signal of executed script
# frozen_string_literal: true require_relative 'env' require_relative 'lib/cracklib_reloaded/password.rb' password = CracklibReloaded::Password.new password.weak?(ARGV.first) puts 'Equivalent of ActiveModel::Errors#messages' puts password.errors.to_h puts password.errors.to_a.inspect exit 1 unless password.errors.any?
# frozen_string_literal: true require_relative 'env' require_relative 'lib/cracklib_reloaded/password.rb' password = CracklibReloaded::Password.new password.weak?(ARGV.first) puts 'Equivalent of ActiveModel::Errors#messages' puts password.errors.to_h puts password.errors.to_a.inspect exit 1 if password.errors.any?
Add plugin to report ohai-solo version
provides "ohai_solo" def parse_version(versionfile) data = File.open(versionfile) {|f| f.readline}.strip version = data.split(" ")[1] return version end ohai_solo Mash.new ohai_solo[:version] = parse_version("/opt/ohai-solo/version-manifest.txt")
Make sure env is always returned
class Net::PTTH IncomingRequest = Struct.new(:method, :path, :headers, :body) do def to_env env = { "PATH_INFO" => path, "SCRIPT_NAME" => "", "rack.input" => StringIO.new(body || ""), "REQUEST_METHOD" => method, } env["CONTENT_LENGTH"] = body.length unless body.nil? env.merge!(headers) if headers end end end
class Net::PTTH IncomingRequest = Struct.new(:method, :path, :headers, :body) do def to_env env = { "PATH_INFO" => path, "SCRIPT_NAME" => "", "rack.input" => StringIO.new(body || ""), "REQUEST_METHOD" => method, } env["CONTENT_LENGTH"] = body.length unless body.nil? env.merge!(headers) if headers env end end end
Fix an error in spec
require 'spec_helper' describe WechatMP do context "Testing endpoint access via methods" do let(:client) { WechatMP::Client.create } it "should find the health endpoint" do expect(@client.Datacube.class).to eql(WechatMP::Endpoints::Datacube) end end end
require 'spec_helper' describe WechatMP do context "Testing endpoint access via methods" do let(:client) { WechatMP::Client.create } it "should find the health endpoint" do expect(client.datacube.class).to eql(WechatMP::Endpoints::Datacube) end end end
Allow cucumber to login as an importer user.
Given /^I am (?:a|an) (writer|editor|admin|GDS editor)(?: called "([^"]*)")?$/ do |role, name| @user = case role when "writer" create(:policy_writer, name: (name || "Wally Writer")) when "editor" create(:departmental_editor, name: (name || "Eddie Editor")) when "admin" create(:user) when "GDS editor" create(:gds_editor) end login_as @user end Given /^I am (?:an?) (writer|editor) in the organisation "([^"]*)"$/ do |role, organisation| organisation = Organisation.find_or_create_by_name(organisation) @user = case role when "writer" create(:policy_writer, name: "Wally Writer", organisation: organisation) when "editor" create(:departmental_editor, name: "Eddie Editor", organisation: organisation) end login_as @user end Given /^I am a visitor$/ do User.stubs(:first).returns(nil) end Around("@use_real_sso") do |scenario, block| current_sso_env = ENV['GDS_SSO_MOCK_INVALID'] ENV['GDS_SSO_MOCK_INVALID'] = "1" block.call ENV['GDS_SSO_MOCK_INVALID'] = current_sso_env end
Given /^I am (?:a|an) (writer|editor|admin|GDS editor|importer)(?: called "([^"]*)")?$/ do |role, name| @user = case role when "writer" create(:policy_writer, name: (name || "Wally Writer")) when "editor" create(:departmental_editor, name: (name || "Eddie Editor")) when "admin" create(:user) when "GDS editor" create(:gds_editor) when 'importer' create(:importer) end login_as @user end Given /^I am (?:an?) (writer|editor) in the organisation "([^"]*)"$/ do |role, organisation| organisation = Organisation.find_or_create_by_name(organisation) @user = case role when "writer" create(:policy_writer, name: "Wally Writer", organisation: organisation) when "editor" create(:departmental_editor, name: "Eddie Editor", organisation: organisation) end login_as @user end Given /^I am a visitor$/ do User.stubs(:first).returns(nil) end Around("@use_real_sso") do |scenario, block| current_sso_env = ENV['GDS_SSO_MOCK_INVALID'] ENV['GDS_SSO_MOCK_INVALID'] = "1" block.call ENV['GDS_SSO_MOCK_INVALID'] = current_sso_env end
Set up redis.yml first so that subsequent generators don't fail
require 'rails/generators' class TestAppGenerator < Rails::Generators::Base source_root File.expand_path("../../../../support", __FILE__) def run_blacklight_generator say_status("warning", "GENERATING BL", :yellow) generate 'blacklight', '--devise' end def run_hydra_head_generator say_status("warning", "GENERATING HH", :yellow) generate 'hydra:head', '-f' end def run_hydra_head_generator say_status("warning", "GENERATING HH", :yellow) generate 'hydra:head', '-f' end def run_sufia_generator say_status("warning", "GENERATING SUFIA", :yellow) generate 'sufia', '-f' remove_file 'spec/factories/users.rb' end def install_redis_config copy_file "config/redis.yml" end end
require 'rails/generators' class TestAppGenerator < Rails::Generators::Base source_root File.expand_path("../../../../support", __FILE__) def run_blacklight_generator say_status("warning", "GENERATING BL", :yellow) generate 'blacklight', '--devise' end def run_hydra_head_generator say_status("warning", "GENERATING HH", :yellow) generate 'hydra:head', '-f' end def run_hydra_head_generator say_status("warning", "GENERATING HH", :yellow) generate 'hydra:head', '-f' end def install_redis_config copy_file "config/redis.yml" end def run_sufia_generator say_status("warning", "GENERATING SUFIA", :yellow) generate 'sufia', '-f' remove_file 'spec/factories/users.rb' end end
Add helper methods adjusting user points
class Feedback < ActiveRecord::Base belongs_to :chat validates_presence_of :rating belongs_to :sender, class_name: "User" belongs_to :recipient, class_name: "User" end
class Feedback < ActiveRecord::Base belongs_to :chat validates_presence_of :rating belongs_to :sender, class_name: "User" belongs_to :recipient, class_name: "User" RESET_POINTS = 0 POINTS_ADJUSTMENT_FACTOR = 10 MAX_POINTS_FOR_LEVEL = 100 def self.possible_ratings_for_select_list [["One Star", 1], ["Two Stars", 2], ["Three Stars", 3]] end def self.adjust_level_points_for_user(feedback, user) user.points += feedback.rating * POINTS_ADJUSTMENT_FACTOR if feedback.rating if user.points >= MAX_POINTS_FOR_LEVEL curr_level = user.level user.level = Level.find_by(language_id: curr_level.language_id, value: curr_level.value + 1) if user.level.value < MAX_POINTS_FOR_LEVEL user.points = RESET_POINTS end user.save end end
Remove initializer declaration (not needed)
class ReviewPeriod def initialize end def send_closure_notifications if ENV['REVIEW_PERIOD'] == 'CLOSED' participants.each do |participant| UserMailer. closure_notification(participant, participant.tokens.create). deliver end end end def participants Review.all.map { |r| [r.subject, r.subject.manager].compact }.flatten.uniq end end
class ReviewPeriod def send_closure_notifications if ENV['REVIEW_PERIOD'] == 'CLOSED' participants.each do |participant| UserMailer. closure_notification(participant, participant.tokens.create). deliver end end end def participants Review.all.map { |r| [r.subject, r.subject.manager].compact }.flatten.uniq end end
Add utility to convert existing definitions to JSON
#!/usr/bin/env ruby -wKU $:.unshift(File.expand_path("../../lib", __FILE__)) require 'fileutils' require 'whois' require 'json' def convert(type) defs = Whois::Server.definitions(type) json = {} defs.each do |(allocation, host, options)| json[allocation] = { host: host } json[allocation].merge!(options) end JSON.pretty_generate(json) end def write(type, content) File.open(File.expand_path("../../lib/whois/definitions/#{type}.json", __FILE__), "w+") do |f| f.write(content) end end Whois::Server.definitions.keys.each do |type| write(type, convert(type)) end
Use asset_roles to know which server to have upload the assets
task :precompile_and_upload_assets do on roles(:assets_precompiler) do within release_path do with rails_env: fetch(:rails_env), rails_groups: fetch(:rails_assets_groups) do execute :rake, "assets:precompile" end appyml_text = capture :cat, "#{deploy_to}/shared/config/application.yml" appyml = YAML.load appyml_text execute "AWS_ACCESS_KEY_ID=#{appyml['AWS_ACCESS_KEY_ID']}", "AWS_SECRET_ACCESS_KEY=#{appyml["AWS_SECRET_ACCESS_KEY"]}", 'aws', 's3', 'sync', 'public/assets/', 's3://mobile-doorman-dev/assets' end end end
task :upload_assets_to_s3 do on roles(fetch(:assets_roles)) do within release_path do with rails_env: fetch(:rails_env), rails_groups: fetch(:rails_assets_groups) do execute :rake, "assets:precompile" end appyml_text = capture :cat, "#{deploy_to}/shared/config/application.yml" appyml = YAML.load appyml_text execute "AWS_ACCESS_KEY_ID=#{appyml['AWS_ACCESS_KEY_ID']}", "AWS_SECRET_ACCESS_KEY=#{appyml["AWS_SECRET_ACCESS_KEY"]}", 'aws', 's3', 'sync', 'public/assets/', 's3://mobile-doorman-dev/assets' end end end
Add level of indirection to ease overriding in Groups
## # This is the class of all Groups. A Group is a role that does not depend # on context, but rather on membership - a user can be made a member # of such a role. This might be related to that person's role in the # organization, for example. module Arrthorizer class Group < Role attr_reader :name def initialize(name) @name = name Role.register(self) end def applies_to_user?(user, context) Arrthorizer.membership_service.is_member_of?(user, self) end end end
## # This is the class of all Groups. A Group is a role that does not depend # on context, but rather on membership - a user can be made a member # of such a role. This might be related to that person's role in the # organization, for example. module Arrthorizer class Group < Role attr_reader :name def initialize(name) @name = name Role.register(self) end def applies_to_user?(user, _) is_member?(user) end private def is_member?(user) Arrthorizer.membership_service.is_member_of?(user, self) end end end
Fix gemspec version at 4.2.0.alpha
version = File.read(File.expand_path('../../RAILS_VERSION', __FILE__)).strip Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'activesupport' s.version = version s.summary = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework.' s.description = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework. Rich support for multibyte strings, internationalization, time zones, and testing.' s.required_ruby_version = '>= 1.9.3' s.license = 'MIT' s.author = 'David Heinemeier Hansson' s.email = 'david@loudthinking.com' s.homepage = 'http://www.rubyonrails.org' s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.rdoc', 'lib/**/*'] s.require_path = 'lib' s.rdoc_options.concat ['--encoding', 'UTF-8'] s.add_dependency 'i18n', '~> 0.6', '>= 0.6.9' s.add_dependency 'json', '~> 1.7', '>= 1.7.7' s.add_dependency 'tzinfo', '~> 1.1' s.add_dependency 'minitest', '~> 5.1' s.add_dependency 'thread_safe','~> 0.1' end
version = '4.2.0.alpha' Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'activesupport' s.version = version s.summary = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework.' s.description = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework. Rich support for multibyte strings, internationalization, time zones, and testing.' s.required_ruby_version = '>= 1.9.3' s.license = 'MIT' s.author = 'David Heinemeier Hansson' s.email = 'david@loudthinking.com' s.homepage = 'http://www.rubyonrails.org' s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.rdoc', 'lib/**/*'] s.require_path = 'lib' s.rdoc_options.concat ['--encoding', 'UTF-8'] s.add_dependency 'i18n', '~> 0.6', '>= 0.6.9' s.add_dependency 'json', '~> 1.7', '>= 1.7.7' s.add_dependency 'tzinfo', '~> 1.1' s.add_dependency 'minitest', '~> 5.1' s.add_dependency 'thread_safe','~> 0.1' end
Replace maruku with rdiscount for Markdown library
# encoding: utf-8 require File.expand_path('../lib/gem_template/version', __FILE__) Gem::Specification.new do |gem| gem.add_development_dependency 'maruku', '~> 0.6' gem.add_development_dependency 'rake', '~> 0.9' gem.add_development_dependency 'rspec', '~> 2.6' gem.add_development_dependency 'simplecov', '~> 0.4' gem.add_development_dependency 'yard', '~> 0.7' gem.author = "Code for America" gem.description = %q{TODO: Write a gem description} gem.email = 'info@codeforamerica.org' gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)} gem.files = `git ls-files`.split("\n") gem.homepage = '' gem.name = 'gem_template' gem.require_paths = ['lib'] gem.summary = %q{TODO: Write a gem summary} gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") gem.version = GemTemplate::VERSION end
# encoding: utf-8 require File.expand_path('../lib/gem_template/version', __FILE__) Gem::Specification.new do |gem| gem.add_development_dependency 'rake', '~> 0.9' gem.add_development_dependency 'rdiscount', '~> 1.6' gem.add_development_dependency 'rspec', '~> 2.6' gem.add_development_dependency 'simplecov', '~> 0.4' gem.add_development_dependency 'yard', '~> 0.7' gem.author = "Code for America" gem.description = %q{TODO: Write a gem description} gem.email = 'info@codeforamerica.org' gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)} gem.files = `git ls-files`.split("\n") gem.homepage = '' gem.name = 'gem_template' gem.require_paths = ['lib'] gem.summary = %q{TODO: Write a gem summary} gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") gem.version = GemTemplate::VERSION end
Refactor resource concern adminable method
module Adminable module ResourceConcern extend ActiveSupport::Concern def adminable %i(title name email login id).each do |name| return OpenStruct.new(name: public_send(name)) unless try(name).nil? end end end end
module Adminable module ResourceConcern extend ActiveSupport::Concern def adminable %i(title name email login id).each do |name| begin return OpenStruct.new(name: public_send(name)) rescue NoMethodError next end end end end end
Fix download_url for windows agent installation
server_ip = node['go']['agent']['server_host'] install_path = node['go']['agent']['install_path'] opts = "" opts << "/SERVERIP=#{server_ip} " if node['go']['agent']['server_host'] opts << "/D=#{install_path}" if node['go']['agent']['install_path'] download_url = node['go']['agent']['download_url'] if !download_url major_ver = node['go']['version'].split('-', 2).first download_url = "http://download01.thoughtworks.com/go/#{major_ver}/ga/go-agent-#{node['go']['version']}-setup.exe" end windows_package 'Go Agent' do source download_url options opts action :install end
server_ip = node['go']['agent']['server_host'] install_path = node['go']['agent']['install_path'] opts = "" opts << "/SERVERIP=#{server_ip} " if node['go']['agent']['server_host'] opts << "/D=#{install_path}" if node['go']['agent']['install_path'] download_url = node['go']['agent']['download_url'] if !download_url major_ver = node['go']['version'].split('-', 2).first download_url = "http://download.go.cd/gocd/go-agent-#{node['go']['version']}-setup.exe" end windows_package 'Go Agent' do source download_url options opts action :install end
Add sass 3.2 as a dependency
$:.push File.expand_path("../lib", __FILE__) require "govuk_frontend_toolkit/version" Gem::Specification.new do |s| s.name = "govuk_frontend_toolkit" s.version = GovUKFrontendToolkit::VERSION s.summary = 'Tools for building frontend applications' s.authors = ['Bradley Wright'] s.email = 'bradley.wright@digital.cabinet-office.gov.uk' s.homepage = 'https://github.com/alphagov/govuk_frontend_toolkit' s.add_dependency "rails", ">= 3.1.0" s.add_development_dependency "gem_publisher", "~> 1.1.1" s.add_development_dependency "rake", "0.9.2.2" s.add_development_dependency "gemfury", "0.4.8" s.require_paths = ["lib", "app"] s.files = `git ls-files`.split($\) end
$:.push File.expand_path("../lib", __FILE__) require "govuk_frontend_toolkit/version" Gem::Specification.new do |s| s.name = "govuk_frontend_toolkit" s.version = GovUKFrontendToolkit::VERSION s.summary = 'Tools for building frontend applications' s.authors = ['Bradley Wright'] s.email = 'bradley.wright@digital.cabinet-office.gov.uk' s.homepage = 'https://github.com/alphagov/govuk_frontend_toolkit' s.add_dependency "rails", ">= 3.1.0" s.add_dependency "sass", ">= 3.2.0" s.add_development_dependency "gem_publisher", "~> 1.1.1" s.add_development_dependency "rake", "0.9.2.2" s.add_development_dependency "gemfury", "0.4.8" s.require_paths = ["lib", "app"] s.files = `git ls-files`.split($\) end
Add Rake task to create and assign first tenant, instead of the migration.
namespace :spree_multi_tenant do desc "Create a new tenant" task :create_tenant => :environment do domain = ENV["domain"] code = ENV["code"] if domain.blank? or code.blank? puts "Error: domain and code must be specified" puts "(e.g. rake spree_multi_tenant:create_tenant domain=mydomain.com code=mydomain)" exit end tenant = Spree::Tenant.create! do |t| t.domain = domain.dup t.code = code.dup end tenant.create_template_and_assets_paths end end
def do_create_tenant domain, code if domain.blank? or code.blank? puts "Error: domain and code must be specified" puts "(e.g. rake spree_multi_tenant:create_tenant domain=mydomain.com code=mydomain)" exit end tenant = Spree::Tenant.create!({:domain => domain.dup, :code => code.dup}) tenant.create_template_and_assets_paths tenant end namespace :spree_multi_tenant do desc "Create a new tenant and assign all exisiting items to the tenant." task :create_tenant_and_assign => :environment do tenant = do_create_tenant ENV["domain"], ENV["code"] # Assign all existing items to the new tenant SpreeMultiTenant.tenanted_models.each do |model| model.all.each do |item| item.update_attribute(:tenant_id, tenant.id) end end end desc "Create a new tenant" task :create_tenant => :environment do tenant = do_create_tenant ENV["domain"], ENV["code"] end end
Allow short-URL (intranet) autolinks in Enterprise
require 'rinku' module GitHub::HTML # HTML Filter for auto_linking urls in HTML. class AutolinkFilter < Filter def call return html if context[:autolink] == false Rinku.auto_link(html, :urls, nil, %w[a script kbd pre code]) end end end
require 'rinku' module GitHub::HTML # HTML Filter for auto_linking urls in HTML. class AutolinkFilter < Filter def call return html if context[:autolink] == false flags = 0 if GitHub.enterprise? flags |= Rinku::AUTOLINK_SHORT_DOMAINS end Rinku.auto_link(html, :urls, nil, %w[a script kbd pre code], flags) end end end
Add buttons for printing invoices in admin panel
Deface::Override.new(:virtual_path => %q{spree/admin/orders/index}, :insert_after => "[data-hook='admin_orders_index_header_actions']", :name => "print_button_header", :text => "<th>print</th>") Deface::Override.new(:virtual_path => %q{spree/admin/orders/index}, :insert_after => "[data-hook='admin_orders_index_row_actions']", :name => "print_button_link", :text => %q{<td><%= link_to "Print", "##{order.id}" %></td>})
Add new rake task to for architecture redesign
namespace :db do desc 'Migrates assessments to the new schema in 20140527151234_assessment_redesign.rb' task migrate_assessments: :environment do Mission.all.each do |m| puts m.to_yaml end end end
Use fcrepo 4.6.0 by default
require 'fcrepo_wrapper/version' require 'fcrepo_wrapper/configuration' require 'fcrepo_wrapper/settings' require 'fcrepo_wrapper/downloader' require 'fcrepo_wrapper/md5' require 'fcrepo_wrapper/instance' module FcrepoWrapper def self.default_fcrepo_version '4.5.1' end def self.default_fcrepo_port '8080' end def self.default_instance(options = {}) @default_instance ||= FcrepoWrapper::Instance.new options end ## # Ensures a fcrepo service is running before executing the block def self.wrap(options = {}, &block) default_instance(options).wrap &block end end
require 'fcrepo_wrapper/version' require 'fcrepo_wrapper/configuration' require 'fcrepo_wrapper/settings' require 'fcrepo_wrapper/downloader' require 'fcrepo_wrapper/md5' require 'fcrepo_wrapper/instance' module FcrepoWrapper def self.default_fcrepo_version '4.6.0' end def self.default_fcrepo_port '8080' end def self.default_instance(options = {}) @default_instance ||= FcrepoWrapper::Instance.new options end ## # Ensures a fcrepo service is running before executing the block def self.wrap(options = {}, &block) default_instance(options).wrap &block end end
Save a query (or a few hundred) on the dashboard
class Reason < ApplicationRecord has_and_belongs_to_many :posts has_many :feedbacks, :through => :posts def tp_percentage # I don't like the .count.count, but it does get the job done count = self.posts.where(:is_tp => true, :is_fp => false).count return (count.to_f / self.posts.count.to_f).to_f end def fp_percentage count = self.posts.where(:is_fp => true, :is_tp => false).count return (count.to_f / self.posts.count.to_f).to_f end def both_percentage count = self.posts.where(:is_fp => true, :is_tp => true).count + self.posts.includes(:feedbacks).where(:is_tp => false, :is_fp => false).where.not( :feedbacks => { :post_id => nil }).count return (count.to_f / self.posts.count.to_f).to_f end end
class Reason < ApplicationRecord has_and_belongs_to_many :posts has_many :feedbacks, :through => :posts def tp_percentage # I don't like the .count.count, but it does get the job done count = self.posts.where(:is_tp => true, :is_fp => false).count return (count.to_f / fast_post_count.to_f).to_f end def fp_percentage count = self.posts.where(:is_fp => true, :is_tp => false).count return (count.to_f / fast_post_count.to_f).to_f end def both_percentage count = self.posts.where(:is_fp => true, :is_tp => true).count + self.posts.includes(:feedbacks).where(:is_tp => false, :is_fp => false).where.not( :feedbacks => { :post_id => nil }).count return (count.to_f / fast_post_count.to_f).to_f end # Attempt to use cached post_count if it's available (included in the dashboard/index query) def fast_post_count self.post_count || self.posts.count end end
Add block option to client
require_relative 'sendgrid/exceptions' require_relative 'sendgrid/mail' require_relative 'sendgrid/version' require 'rest-client' module SendGrid class Client attr_reader :api_user, :api_key, :host, :endpoint def initialize(params) @api_user = params.fetch(:api_user) @api_key = params.fetch(:api_key) @host = params.fetch(:host, 'https://api.sendgrid.com') @endpoint = params.fetch(:endpoint, '/api/mail.send.json') @conn = params.fetch(:conn, create_conn) @user_agent = params.fetch(:user_agent, 'sendgrid/' + SendGrid::VERSION + ';ruby') end def send(mail) payload = mail.to_h.merge({api_user: @api_user, api_key: @api_key}) @conn[@endpoint].post(payload, {user_agent: @user_agent}) do |response, request, result| case response.code.to_s when /2\d\d/ response when /4\d\d|5\d\d/ raise SendGrid::Exception.new(response) else # TODO: What will reach this? "DEFAULT #{response.code} #{response}" end end end private def create_conn @conn = RestClient::Resource.new(@host) end end end
require_relative 'sendgrid/exceptions' require_relative 'sendgrid/mail' require_relative 'sendgrid/version' require 'rest-client' module SendGrid class Client attr_accessor :api_user, :api_key, :host, :endpoint def initialize(params = {}) @api_user = params.fetch(:api_user, nil) @api_key = params.fetch(:api_key, nil) @host = params.fetch(:host, 'https://api.sendgrid.com') @endpoint = params.fetch(:endpoint, '/api/mail.send.json') @conn = params.fetch(:conn, create_conn) @user_agent = params.fetch(:user_agent, 'sendgrid/' + SendGrid::VERSION + ';ruby') yield self if block_given? raise SendGrid::Exception.new('api_user and api_key are required') unless @api_user && @api_key end def send(mail) payload = mail.to_h.merge({api_user: @api_user, api_key: @api_key}) @conn[@endpoint].post(payload, {user_agent: @user_agent}) do |response, request, result| case response.code.to_s when /2\d\d/ response when /4\d\d|5\d\d/ raise SendGrid::Exception.new(response) else # TODO: What will reach this? "DEFAULT #{response.code} #{response}" end end end private def create_conn @conn = RestClient::Resource.new(@host) end end end
Add a few more edge case tests.
require 'test_helper' class Superstore::Types::IntegerRangeTypeTest < Superstore::Types::TestCase test 'encode' do assert_equal [4, 5], type.encode(4..5) assert_equal [4, nil], type.encode(4..Float::INFINITY) assert_equal [nil, 5], type.encode(-Float::INFINITY..5) end test 'decode' do assert_equal 4..5, type.decode([4, 5]) assert_equal 4..Float::INFINITY, type.decode([4, nil]) assert_equal -Float::INFINITY..5, type.decode([nil, 5]) end test 'typecast' do assert_equal 1..5, type.typecast(1..5) assert_equal 1..5, type.typecast([1, 5]) assert_equal 1..Float::INFINITY, type.typecast([1, nil]) assert_equal -Float::INFINITY..2, type.typecast([nil, 2]) end end
require 'test_helper' class Superstore::Types::IntegerRangeTypeTest < Superstore::Types::TestCase test 'encode' do assert_equal [4, 5], type.encode(4..5) assert_equal [4, nil], type.encode(4..Float::INFINITY) assert_equal [nil, 5], type.encode(-Float::INFINITY..5) assert_equal [0, 20], type.encode(20..0) end test 'decode' do assert_equal 4..5, type.decode([4, 5]) assert_equal 4..Float::INFINITY, type.decode([4, nil]) assert_equal -Float::INFINITY..5, type.decode([nil, 5]) assert_equal -Float::INFINITY..Float::INFINITY, type.decode([nil, nil]) end test 'typecast' do assert_equal 1..5, type.typecast(1..5) assert_equal 1..5, type.typecast(5..1) assert_equal 1..5, type.typecast([1, 5]) assert_equal 1..Float::INFINITY, type.typecast([1, nil]) assert_equal -Float::INFINITY..2, type.typecast([nil, 2]) assert_equal -Float::INFINITY..Float::INFINITY, type.typecast([nil, nil]) end end
Add missing wait to double/context click spec.
require File.expand_path("../spec_helper", __FILE__) module Selenium module WebDriver describe Mouse do it "clicks an element" do driver.navigate.to url_for("formPage.html") driver.mouse.click driver.find_element(:id, "imageButton") end it "can drag and drop" do driver.navigate.to url_for("droppableItems.html") draggable = long_wait.until { driver.find_element(:id => "draggable") } droppable = driver.find_element(:id => "droppable") driver.mouse.down draggable driver.mouse.move_to droppable driver.mouse.up droppable text = droppable.find_element(:tag_name => "p").text text.should == "Dropped!" end not_compliant_on :browser => :firefox, :platform => :windows do it "double clicks an element" do driver.navigate.to url_for("javascriptPage.html") element = driver.find_element(:id, 'doubleClickField') driver.mouse.double_click element element.attribute(:value).should == 'DoubleClicked' end end it "context clicks an element" do driver.navigate.to url_for("javascriptPage.html") element = driver.find_element(:id, 'doubleClickField') driver.mouse.context_click element element.attribute(:value).should == 'ContextClicked' end end end end
require File.expand_path("../spec_helper", __FILE__) module Selenium module WebDriver describe Mouse do it "clicks an element" do driver.navigate.to url_for("formPage.html") driver.mouse.click driver.find_element(:id, "imageButton") end it "can drag and drop" do driver.navigate.to url_for("droppableItems.html") draggable = long_wait.until { driver.find_element(:id => "draggable") } droppable = driver.find_element(:id => "droppable") driver.mouse.down draggable driver.mouse.move_to droppable driver.mouse.up droppable text = droppable.find_element(:tag_name => "p").text text.should == "Dropped!" end it "double clicks an element" do driver.navigate.to url_for("javascriptPage.html") element = driver.find_element(:id, 'doubleClickField') driver.mouse.double_click element wait(5).until { element.attribute(:value) == 'DoubleClicked' } end it "context clicks an element" do driver.navigate.to url_for("javascriptPage.html") element = driver.find_element(:id, 'doubleClickField') driver.mouse.context_click element wait(5).until { element.attribute(:value) == 'ContextClicked' } end end end end
Check whether the classes actually do get generated
require "fileutils" module DataMapperSalesforce class SoapWrapper def initialize(module_name, driver_name, wsdl_path, api_dir) @module_name, @driver_name, @wsdl_path, @api_dir = module_name, driver_name, File.expand_path(wsdl_path), File.expand_path(api_dir) generate_soap_classes driver end attr_reader :module_name, :driver_name, :wsdl_path, :api_dir def driver @driver ||= Object.const_get(module_name).const_get(driver_name).new end def generate_soap_classes unless File.file?(wsdl_path) raise Errno::ENOENT, "Could not find the WSDL at #{wsdl_path}" end unless File.directory?(wsdl_api_dir) FileUtils.mkdir_p wsdl_api_dir end unless Dir["#{wsdl_api_dir}/#{module_name}*.rb"].size == 3 Dir.chdir(wsdl_api_dir) do puts system(`which wsdl2ruby.rb`.chomp, "--wsdl", wsdl_path, "--module_path", module_name, "--classdef", module_name, "--type", "client") FileUtils.rm Dir["*Client.rb"] end end $:.push wsdl_api_dir require "#{module_name}Driver" end def wsdl_api_dir "#{api_dir}/#{File.basename(wsdl_path)}" end end end
require "fileutils" module DataMapperSalesforce class SoapWrapper class ClassesFailedToGenerate < StandardError; end def initialize(module_name, driver_name, wsdl_path, api_dir) @module_name, @driver_name, @wsdl_path, @api_dir = module_name, driver_name, File.expand_path(wsdl_path), File.expand_path(api_dir) generate_soap_classes driver end attr_reader :module_name, :driver_name, :wsdl_path, :api_dir def driver @driver ||= Object.const_get(module_name).const_get(driver_name).new end def generate_soap_classes unless File.file?(wsdl_path) raise Errno::ENOENT, "Could not find the WSDL at #{wsdl_path}" end unless File.directory?(wsdl_api_dir) FileUtils.mkdir_p wsdl_api_dir end unless Dir["#{wsdl_api_dir}/#{module_name}*.rb"].size == 3 Dir.chdir(wsdl_api_dir) do unless system("wsdl2ruby.rb", "--wsdl", wsdl_path, "--module_path", module_name, "--classdef", module_name, "--type", "client") raise ClassesFailedToGenerate, "Could not generate the ruby classes from the WSDL" end FileUtils.rm Dir["*Client.rb"] end end $:.push wsdl_api_dir require "#{module_name}Driver" end def wsdl_api_dir "#{api_dir}/#{File.basename(wsdl_path)}" end end end
Use admin user in tests
require 'spec_helper' describe 'GFM autocomplete loading', feature: true, js: true do let(:user) { create(:user) } let(:project) { create(:project) } before do project.team << [user, :master] login_as user visit namespace_project_path(project.namespace, project) end it 'does not load on project#show' do expect(evaluate_script('GitLab.GfmAutoComplete.dataSource')).to eq('') end it 'loads on new issue page' do visit new_namespace_project_issue_path(project.namespace, project) expect(evaluate_script('GitLab.GfmAutoComplete.dataSource')).not_to eq('') end end
require 'spec_helper' describe 'GFM autocomplete loading', feature: true, js: true do let(:project) { create(:project) } before do login_as :admin visit namespace_project_path(project.namespace, project) end it 'does not load on project#show' do expect(evaluate_script('GitLab.GfmAutoComplete.dataSource')).to eq('') end it 'loads on new issue page' do visit new_namespace_project_issue_path(project.namespace, project) expect(evaluate_script('GitLab.GfmAutoComplete.dataSource')).not_to eq('') end end
Revert "Temporary install specific version of nokogiri"
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) require 'ooxml_parser/version' Gem::Specification.new do |s| s.name = 'ooxml_parser' s.version = OoxmlParser::Version::STRING s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 1.9' s.authors = ['Pavel Lobashov', 'Roman Zagudaev'] s.summary = 'OoxmlParser Gem' s.description = 'Parse OOXML files (docx, xlsx, pptx)' s.email = ['shockwavenn@gmail.com', 'rzagudaev@gmail.com'] s.files = `git ls-files lib LICENSE.txt README.md`.split($RS) s.add_runtime_dependency('nokogiri', '1.6.8') s.add_runtime_dependency('rubyzip', '~> 1.1') s.add_runtime_dependency('ruby-filemagic') s.add_runtime_dependency('xml-simple', '~> 1.1') s.homepage = 'http://rubygems.org/gems/ooxml_parser' s.license = 'AGPL-3.0' end
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) require 'ooxml_parser/version' Gem::Specification.new do |s| s.name = 'ooxml_parser' s.version = OoxmlParser::Version::STRING s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 1.9' s.authors = ['Pavel Lobashov', 'Roman Zagudaev'] s.summary = 'OoxmlParser Gem' s.description = 'Parse OOXML files (docx, xlsx, pptx)' s.email = ['shockwavenn@gmail.com', 'rzagudaev@gmail.com'] s.files = `git ls-files lib LICENSE.txt README.md`.split($RS) s.add_runtime_dependency('nokogiri', '~> 1.6') s.add_runtime_dependency('rubyzip', '~> 1.1') s.add_runtime_dependency('ruby-filemagic') s.add_runtime_dependency('xml-simple', '~> 1.1') s.homepage = 'http://rubygems.org/gems/ooxml_parser' s.license = 'AGPL-3.0' end
Add a default Resque QUEUE to run
require 'resque/tasks' task 'resque:setup' => :environment do require './app/workers/resque_worker' end
require 'resque/tasks' task 'resque:setup' => :environment do # Add a default to run every queue, unless otherwise specified ENV['QUEUE'] = '*' unless ENV.include?('QUEUE') require './app/workers/resque_worker' end
Add throttling data for airbrake exception
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new Rack::Attack.throttled_response = ->(env) { [429, {}, [ActionView::Base.new.render(file: 'public/429.html')]] } ActiveSupport::Notifications.subscribe('rack.attack') do |name, start, finish, request_id, req| Airbrake.notify Exception.new "#{req.ip} has been rate limited for url #{req.url}" end @config = YAML.load_file("#{Rails.root}/config/rack_attack.yml").with_indifferent_access def from_config(key, field) @config[key][field] || @config[:default][field] end def throttle_request?(key, req) from_config(key, :method) == req.env['REQUEST_METHOD'] && /#{from_config(key, :path)}/.match(req.path.to_s) end @config.keys.each do |key| Rack::Attack.throttle key, limit: from_config(key, :limit), period: from_config(key, :period) do |req| req.ip if throttle_request? key, req end unless key == 'default' end
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new Rack::Attack.throttled_response = ->(env) { [429, {}, [ActionView::Base.new.render(file: 'public/429.html')]] } ActiveSupport::Notifications.subscribe('rack.attack') do |name, start, finish, request_id, req| Airbrake.notify Exception.new(message: "#{req.ip} has been rate limited for url #{req.url}", data: req.env['rack.attack.throttle_data']) end @config = YAML.load_file("#{Rails.root}/config/rack_attack.yml").with_indifferent_access def from_config(key, field) @config[key][field] || @config[:default][field] end def throttle_request?(key, req) from_config(key, :method) == req.env['REQUEST_METHOD'] && /#{from_config(key, :path)}/.match(req.path.to_s) end @config.keys.each do |key| Rack::Attack.throttle key, limit: from_config(key, :limit), period: from_config(key, :period) do |req| req.ip if throttle_request? key, req end unless key == 'default' end
Add rake as a development dependency.
# encoding: UTF-8 Gem::Specification.new do |s| s.name = "sunspot-queue" s.homepage = "https://github.com/gaffneyc/sunspot-queue" s.summary = "Background search indexing using existing worker systems." s.require_path = "lib" s.authors = ["Chris Gaffney"] s.email = ["gaffneyc@gmail.com"] s.version = "0.9.0" s.platform = Gem::Platform::RUBY s.files = Dir.glob("{lib,spec}/**/*") + %w[LICENSE README.md] s.add_dependency "resque" s.add_dependency "sunspot_rails", ">= 1.3.0" s.add_development_dependency "rspec", "~> 2.10.0" s.add_development_dependency "resque_spec" s.add_development_dependency "sunspot_solr" s.add_development_dependency "sqlite3" s.add_development_dependency "activerecord" s.add_development_dependency "guard" s.add_development_dependency "guard-rspec" s.add_development_dependency "guard-bundler" end
# encoding: UTF-8 Gem::Specification.new do |s| s.name = "sunspot-queue" s.homepage = "https://github.com/gaffneyc/sunspot-queue" s.summary = "Background search indexing using existing worker systems." s.require_path = "lib" s.authors = ["Chris Gaffney"] s.email = ["gaffneyc@gmail.com"] s.version = "0.9.0" s.platform = Gem::Platform::RUBY s.files = Dir.glob("{lib,spec}/**/*") + %w[LICENSE README.md] s.add_dependency "resque" s.add_dependency "sunspot_rails", ">= 1.3.0" s.add_development_dependency "rake" s.add_development_dependency "rspec", "~> 2.10.0" s.add_development_dependency "resque_spec" s.add_development_dependency "sunspot_solr" s.add_development_dependency "sqlite3" s.add_development_dependency "activerecord" s.add_development_dependency "guard" s.add_development_dependency "guard-rspec" s.add_development_dependency "guard-bundler" end
Fix "undefined method `today' for Date:Class" error.
require File.expand_path("../lib/omniauth-orcid/version", __FILE__) Gem::Specification.new do |s| s.authors = ["Gudmundur A. Thorisson"] s.email = %q{gthorisson@gmail.com} s.name = "omniauth-orcid" s.homepage = %q{https://github.com/gthorisson/omniauth-orcid} s.summary = %q{ORCID OAuth 2.0 Strategy for OmniAuth 1.0} s.date = Date.today s.description = %q{Enables third-party client apps to connect to the ORCID API and access/update protected profile data } s.files = Dir["{lib}/**/*.rb", "bin/*", "LICENSE.txt", "*.md", "Rakefile", "Gemfile", "demo.rb", "config.yml", "omniauth-orcid.gemspec"] s.require_paths = ["lib"] s.version = OmniAuth::ORCID::VERSION s.extra_rdoc_files = ["README.md"] # Declary dependencies here, rather than in the Gemfile s.add_dependency 'omniauth', '~> 1.0' s.add_dependency 'omniauth-oauth2', '~> 1.1' end
require "date" require File.expand_path("../lib/omniauth-orcid/version", __FILE__) Gem::Specification.new do |s| s.authors = ["Gudmundur A. Thorisson"] s.email = %q{gthorisson@gmail.com} s.name = "omniauth-orcid" s.homepage = %q{https://github.com/gthorisson/omniauth-orcid} s.summary = %q{ORCID OAuth 2.0 Strategy for OmniAuth 1.0} s.date = Date.today s.description = %q{Enables third-party client apps to connect to the ORCID API and access/update protected profile data } s.files = Dir["{lib}/**/*.rb", "bin/*", "LICENSE.txt", "*.md", "Rakefile", "Gemfile", "demo.rb", "config.yml", "omniauth-orcid.gemspec"] s.require_paths = ["lib"] s.version = OmniAuth::ORCID::VERSION s.extra_rdoc_files = ["README.md"] # Declary dependencies here, rather than in the Gemfile s.add_dependency 'omniauth', '~> 1.0' s.add_dependency 'omniauth-oauth2', '~> 1.1' end
Add plugin to enable _pages directory
# https://github.com/bbakersmith/jekyll-pages-directory/blob/master/_plugins/jekyll-pages-directory.rb module Jekyll class PagesDirGenerator < Generator def generate(site) pages_dir = site.config['pages'] || './_pages' all_raw_paths = Dir["#{pages_dir}/**/*"] all_raw_paths.each do |f| if File.file?(File.join(site.source, '/', f)) filename = f.match(/[^\/]*$/)[0] clean_filepath = f.gsub(/^#{pages_dir}\//, '') clean_dir = extract_directory(clean_filepath) site.pages << PagesDirPage.new(site, site.source, clean_dir, filename, pages_dir) end end end def extract_directory(filepath) dir_match = filepath.match(/(.*\/)[^\/]*$/) if dir_match return dir_match[1] else return '' end end end class PagesDirPage < Page def initialize(site, base, dir, name, pagesdir) @site = site @base = base @dir = dir @name = name process(name) read_yaml(File.join(base, pagesdir, dir), name) data.default_proc = proc do |hash, key| site.frontmatter_defaults.find(File.join(dir, name), type, key) end Jekyll::Hooks.trigger :pages, :post_init, self end end end
Test for minimax method, create test for winning, losing, draw, and step a way from winning and losing
require_relative '../lib/tic_tac_toe.rb' require 'pry' describe TicTacToe do # let(:ttt){TicTacToe.new} describe '#minimax' do context 'a player wins' do it "returns 1000 if it is a winning board is X" do board = ["X", "X", "X", "O", "X", "X", "O", "X", "O"] expect(TicTacToe.new(board, "X").minimax).to eq 1000 end it "returns -1000 if it is a winning board is O" do board = ["X", "X", "O", "O", "X", "X", "O", "O", "O"] expect(TicTacToe.new(board, "O").minimax).to eq -1000 end end context 'draw' do it "returns 0 if it is a draw" do board = ["X", "O", "X", "X", "O", "O", "O", "X", "O"] expect(TicTacToe.new(board, "O").minimax).to eq 0 end end context 'one move away from win' do it "returns 990 if it is a winning board is X" do board = ["X", "X", " ", " ", " ", " ", " ", " ", " "] expect(TicTacToe.new(board, "X").minimax).to eq 990 end it "returns -990 if it is a winning board is O" do board = [" ", " ", " ", " ", " ", " ", " ", "O", "O"] expect(TicTacToe.new(board, "O").minimax).to eq -990 end end end end
Update according to homebrew dev
class Picat < Formula desc "Simple, and yet powerful, logic-based multi-paradigm programming language" homepage "http://picat-lang.org" url "http://picat-lang.org/download/picat24_src.tar.gz" version "2.4.8" sha256 "72b452a8ba94d6187d837dcdb46aab0d7dc724651bac99a8cf2ada5c0a3543dd" depends_on "gcc" => :build def install inreplace "emu/Makefile.picat.mac64", "/usr/local/bin/gcc", HOMEBREW_PREFIX/"bin/gcc-8" system "make", "-C", "emu", "-f", "Makefile.picat.mac64" prefix.install Dir["doc", "emu", "exs", "lib"] end def post_install ln_sf prefix/"emu/picat_macx", HOMEBREW_PREFIX/"bin/picat" end test do system "picat", "#{prefix}/exs/euler/p1.pi" end end
class Picat < Formula desc "Simple, and yet powerful, logic-based multi-paradigm programming language" homepage "http://picat-lang.org" url "http://picat-lang.org/download/picat24_src.tar.gz" version "2.4.8" sha256 "72b452a8ba94d6187d837dcdb46aab0d7dc724651bac99a8cf2ada5c0a3543dd" depends_on "gcc" def install inreplace "emu/Makefile.picat.mac64", "/usr/local/bin/gcc", HOMEBREW_PREFIX/"bin/gcc-8" system "make", "-C", "emu", "-f", "Makefile.picat.mac64" mv "lib", "pi_lib" prefix.install Dir["doc", "emu", "exs", "pi_lib"] bin.install_symlink prefix/"emu/picat_macx" => "picat" end test do system "#{HOMEBREW_PREFIX}/bin/picat", "#{prefix}/exs/euler/p1.pi" end end
Remove meaningless line that was leftover.
Dummy::Application.routes.draw do api vendor_string: "myvendor" do version 1 do cache as: 'v1' do resources :bar end end version 2 do cache as: 'v2' do resources :foo inherit from: 'v1' end end version 3 do inherit from: 'v2' end end get '*a' => 'errors#not_found' get 'index' => 'simplified_format#index' end
Dummy::Application.routes.draw do api vendor_string: "myvendor" do version 1 do cache as: 'v1' do resources :bar end end version 2 do cache as: 'v2' do resources :foo inherit from: 'v1' end end version 3 do inherit from: 'v2' end end get '*a' => 'errors#not_found' end
Increase test memory limit to stop random failures
RSpec.configure do |config| config.after :each do ObjectSpace.each_object(File) do |file| next if file.closed? next if file.path == '/dev/null' next if file.path == Rails.root.join('log/test.log').to_s fail "You have not closed #{file.path}" end end config.after :each do memory = GetProcessMem.new.mb.to_i fail "Memory is too high: #{memory} MB" if memory > 320 end config.after :suite do memory = GetProcessMem.new.mb.to_i puts "Test memory is #{memory} MB" end if ENV['COVERAGE'] config.after :suite do examples = config.reporter.examples.count duration = Time.zone.now - config.start_time average = duration / examples if duration > 2.minutes || average > 0.25 fail "Tests took too long: total=#{duration.to_i}s average=#{average.round(5)}s" end end end end
RSpec.configure do |config| config.after :each do ObjectSpace.each_object(File) do |file| next if file.closed? next if file.path == '/dev/null' next if file.path == Rails.root.join('log/test.log').to_s fail "You have not closed #{file.path}" end end config.after :each do memory = GetProcessMem.new.mb.to_i fail "Memory is too high: #{memory} MB" if memory > 320 end config.after :suite do memory = GetProcessMem.new.mb.to_i puts "Test memory is #{memory} MB" end if ENV['COVERAGE'] config.after :suite do examples = config.reporter.examples.count duration = Time.zone.now - config.start_time average = duration / examples if duration > 2.minutes || average > 0.26 fail "Tests took too long: total=#{duration.to_i}s average=#{average.round(5)}s" end end end end
Send Util.log to both STDOUT and UI when in server mode.
require 'sinatra' module Kosmos module Web class App < Sinatra::Application set server: 'thin', connection: nil get '/' do send_file(File.join(settings.public_folder, 'index.html')) end get '/stream', provides: 'text/event-stream' do stream :keep_open do |out| settings.connection = out end end post '/' do Kosmos.configure do |config| config.output_method = Proc.new do |str| str.split("\n").each do |line| settings.connection << "data: #{line}\n\n" end end end kosmos_params = params[:params].split(' ') kosmos_command = %w(init install uninstall list).find do |command| command == params[:command] end UserInterface.send(kosmos_command, kosmos_params) 204 end end end end
require 'sinatra' module Kosmos module Web class App < Sinatra::Application set server: 'thin', connection: nil get '/' do send_file(File.join(settings.public_folder, 'index.html')) end get '/stream', provides: 'text/event-stream' do stream :keep_open do |out| settings.connection = out end end post '/' do Kosmos.configure do |config| config.output_method = Proc.new do |str| # Send to STDOUT puts str # And to the in-browser UI str.split("\n").each do |line| settings.connection << "data: #{line}\n\n" end end end kosmos_params = params[:params].split(' ') kosmos_command = %w(init install uninstall list).find do |command| command == params[:command] end UserInterface.send(kosmos_command, kosmos_params) 204 end end end end
Fix security issue with updating and deleting other users tips
class TipsController < ApplicationController before_filter :authenticate_user!, except: [:show, :index] before_filter :set_tip, except: [:index, :new, :create] def index @tips = Tip.includes(:user).paginate(page: params[:page], per_page: 10) end def show @bookmark = @tip.bookmarked_by(current_user) end def new @tip = Tip.new end def create @tip = current_user.tips.build(tip_params) if @tip.save flash[:success] = "Tip created!" redirect_to @tip else render :new end end def edit end def update @tip = Tip.find(params[:id]) if @tip.update_attributes(tip_params) flash[:notice] = "Successfully updated your tip." redirect_to @tip else render :edit end end def destroy end def send_destroy_email @delete = DeleteMailer.reason_to_delete(@tip, params[:message]).deliver redirect_to tips_path, notice: 'Thanks for your input!' end private # Never trust parameters from the scary internet, only allow the white list through. def tip_params params.require(:tip).permit(:title, :description, :body) end def set_tip @tip = Tip.find(params[:id]) end end
class TipsController < ApplicationController before_filter :authenticate_user!, except: [:show, :index] before_filter :set_tip, except: [:index, :new, :create] def index @tips = Tip.includes(:user).paginate(page: params[:page], per_page: 10) end def show @bookmark = @tip.bookmarked_by(current_user) end def new @tip = Tip.new end def create @tip = current_user.tips.build(tip_params) if @tip.save flash[:success] = "Tip created!" redirect_to @tip else render :new end end def edit redirect_to tip_path(@tip), alert: "That's not yours to edit!" unless can? :update, @tip end def update @tip = Tip.find(params[:id]) if @tip.update_attributes(tip_params) flash[:notice] = "Successfully updated your tip." redirect_to @tip else render :edit end end def destroy redirect_to tip_path(@tip), alert: "That's not yours to delete!" unless can? :destroy, @tip end def send_destroy_email @delete = DeleteMailer.reason_to_delete(@tip, params[:message]).deliver redirect_to tips_path, notice: 'Thanks for your input!' end private # Never trust parameters from the scary internet, only allow the white list through. def tip_params params.require(:tip).permit(:title, :description, :body) end def set_tip @tip = Tip.find(params[:id]) end end
Migrate from Sidekiq to Java worker
class UsersController < ApplicationController include Concerns::Pageable PER_PAGE = 50 before_filter :validate_page_param, only: :index def index @users = User.not_organization.starred_first.page(params[:page]) end def show @user = User.find_by!(login: params[:login]) @repositories = @user.repositories.page(params[:page]).per(PER_PAGE) end def update_org @organization = User.find_by!(login: params[:organization][:login]) raise ActionController::BadRequest unless organization_member?(@organization.login, current_user.login) if @organization.queued_recently? redirect_to user_path(@organization), alert: 'Your organization has been already updated recently. Please retry later.' return end UserFetchJob.perform_later(@organization.id) @organization.update(queued_at: Time.now) redirect_to user_path(@organization), notice: 'Update request is successfully queued. Please wait a moment.' end def update_myself if current_user.queued_recently? redirect_to current_user, alert: 'You have already updated your stars recently. Please retry later.' return end UserFetchJob.perform_later(current_user.id) current_user.update(queued_at: Time.now) redirect_to current_user, notice: 'Update request is successfully queued. Please wait a moment.' end end
class UsersController < ApplicationController include Concerns::Pageable PER_PAGE = 50 before_filter :validate_page_param, only: :index def index @users = User.not_organization.starred_first.page(params[:page]) end def show @user = User.find_by!(login: params[:login]) @repositories = @user.repositories.page(params[:page]).per(PER_PAGE) end def update_org @organization = User.find_by!(login: params[:organization][:login]) raise ActionController::BadRequest unless organization_member?(@organization.login, current_user.login) if @organization.queued_recently? redirect_to user_path(@organization), alert: 'Your organization has been already updated recently. Please retry later.' return end ActiveRecord::Base.transaction do @organization.update(queued_at: Time.now) UpdateUserJob.perform_later(@organization.id) end redirect_to user_path(@organization), notice: 'Update request is successfully queued. Please wait a moment.' end def update_myself if current_user.queued_recently? redirect_to current_user, alert: 'You have already updated your stars recently. Please retry later.' return end ActiveRecord::Base.transaction do current_user.update(queued_at: Time.now) UpdateUserJob.perform_later(current_user.id) end redirect_to current_user, notice: 'Update request is successfully queued. Please wait a moment.' end end
Fix redirect path if a user has no topics
class UsersController < ApplicationController def new end def create @user = User.new(user_params) if @user.save session[:user_id] = @user.id redirect_to user_path(@user) else redirect_to 'new' end end def show @user = User.find(session[:user_id]) @topics = @user.topics redirect_to new_topics_path if @topics.length == 0 end def login end def logout end private def user_params params.require(:user).permit(:first_name, :last_name, :username, :email, :password) end end
class UsersController < ApplicationController def new end def create @user = User.new(user_params) if @user.save session[:user_id] = @user.id redirect_to user_path(@user) else redirect_to 'new' end end def show @user = User.find(session[:user_id]) @topics = @user.topics redirect_to new_topic_path if @topics.length == 0 end def login end def logout end private def user_params params.require(:user).permit(:first_name, :last_name, :username, :email, :password) end end
Update votes controller to handle question voting and response voting on create action
class VotesController < ApplicationController def create @vote = Vote.new(vote_params) @question = Question.find(params[:vote][:votable_id]) if @vote.save redirect_to question_path(@question) else flash[:notice] = @vote.errors.full_messages.join(", ") render 'questions/show.html.erb' end end def vote_params params.require(:vote).permit(:value, :voter_id, :votable_id, :votable_type) end end
class VotesController < ApplicationController def create @vote = Vote.new(vote_params) type = (params[:vote][:votable_type]) if type == "Question" @question = Question.find(params[:vote][:votable_id]) end if type == "Response" response = Response.find(params[:vote][:votable_id]) if response.respondable_type == "Question" @question = Question.find(response.respondable_id) end if response.respondable_type == "Answer" @question = Answer.find(response.respondable_id).question end end if type == "Answer" @question = Answer.find(params[:vote][:votable_id]).question end if @vote.save redirect_to question_path(@question) else flash[:notice] = @vote.errors.full_messages.join(", ") render 'questions/show.html.erb' end end def vote_params params.require(:vote).permit(:value, :voter_id, :votable_id, :votable_type) end end
Add license to gemspec, is MIT
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require 'simplecov-html/version' Gem::Specification.new do |s| s.name = "simplecov-html" s.version = SimpleCov::Formatter::HTMLFormatter::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Christoph Olszowka"] s.email = ["christoph at olszowka de"] s.homepage = "https://github.com/colszowka/simplecov-html" s.summary = %Q{Default HTML formatter for SimpleCov code coverage tool for ruby 1.9+} s.description = %Q{Default HTML formatter for SimpleCov code coverage tool for ruby 1.9+} s.rubyforge_project = "simplecov-html" s.add_development_dependency 'rake' s.add_development_dependency 'sprockets' s.add_development_dependency 'sass' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require 'simplecov-html/version' Gem::Specification.new do |s| s.name = "simplecov-html" s.version = SimpleCov::Formatter::HTMLFormatter::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Christoph Olszowka"] s.email = ["christoph at olszowka de"] s.homepage = "https://github.com/colszowka/simplecov-html" s.summary = %Q{Default HTML formatter for SimpleCov code coverage tool for ruby 1.9+} s.description = %Q{Default HTML formatter for SimpleCov code coverage tool for ruby 1.9+} s.license = "MIT" s.rubyforge_project = "simplecov-html" s.add_development_dependency 'rake' s.add_development_dependency 'sprockets' s.add_development_dependency 'sass' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] end
Use correct serialport for demo.
require 'bundler/setup' require 'firmata' board = Firmata::Board.new('/dev/tty.usbmodemfd13131') board.connect pin_number = 3 rate = 0.5 10.times do board.digital_write pin_number, Firmata::Board::HIGH puts '+' board.delay rate board.digital_write pin_number, Firmata::Board::LOW puts '-' board.delay rate end
require 'bundler/setup' require 'firmata' board = Firmata::Board.new('/dev/tty.usbmodemfa131') board.connect pin_number = 3 rate = 0.5 10.times do board.digital_write pin_number, Firmata::Board::HIGH puts '+' board.delay rate board.digital_write pin_number, Firmata::Board::LOW puts '-' board.delay rate end
Fix authentication bug in non-SSL production mode
# Be sure to restart your server when you modify this file. #Avalon::Application.config.session_store :cookie_store, :key => '_avalon_session' Avalon::Application.config.session_store :active_record_store, secure: Rails.env.production?, httponly: true # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rails generate session_migration") # Avalon::Application.config.session_store :active_record_store
# Be sure to restart your server when you modify this file. #Avalon::Application.config.session_store :cookie_store, :key => '_avalon_session' Avalon::Application.config.session_store :active_record_store, secure: Settings.domain.protocol == "https" && Rails.env.production?, httponly: true # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rails generate session_migration") # Avalon::Application.config.session_store :active_record_store
Update bundler and rake versions in gemspec.
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'ldp_testsuite_wrapper/version' Gem::Specification.new do |spec| spec.name = "ldp_testsuite_wrapper" spec.version = LdpTestsuiteWrapper::VERSION spec.authors = ["Chris Beer"] spec.email = ["chris@cbeer.info"] spec.summary = %q{LDP Test Suite service wrapper} spec.homepage = "https://github.com/cbeer/ldp_testsuite_wrapper" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency "rubyzip" spec.add_dependency "faraday" spec.add_dependency "ruby-progressbar" spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec" spec.add_development_dependency "coveralls" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'ldp_testsuite_wrapper/version' Gem::Specification.new do |spec| spec.name = "ldp_testsuite_wrapper" spec.version = LdpTestsuiteWrapper::VERSION spec.authors = ["Chris Beer"] spec.email = ["chris@cbeer.info"] spec.summary = %q{LDP Test Suite service wrapper} spec.homepage = "https://github.com/cbeer/ldp_testsuite_wrapper" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency "rubyzip" spec.add_dependency "faraday" spec.add_dependency "ruby-progressbar" spec.add_development_dependency "bundler", "~> 2.1", ">= 2.1.10" spec.add_development_dependency "rake", "~> 13.0" spec.add_development_dependency "rspec" spec.add_development_dependency "coveralls" end
Return nil, don't want to return data to client
require 'date' module Bluecap class Event def date(timestamp) Time.at(timestamp).strftime('%Y%m%d') end def key(name, timestamp) return "events:#{Bluecap::Keys.clean(name)}:#{date(timestamp)}" end def handle(data) data[:event][:timestamp] ||= Time.now.to_i Bluecap.redis.setbit( key(data[:event][:name], data[:event][:timestamp]), data[:event][:id], 1) end end end
require 'date' module Bluecap class Event def date(timestamp) Time.at(timestamp).strftime('%Y%m%d') end def key(name, timestamp) return "events:#{Bluecap::Keys.clean(name)}:#{date(timestamp)}" end def handle(data) data[:event][:timestamp] ||= Time.now.to_i Bluecap.redis.setbit( key(data[:event][:name], data[:event][:timestamp]), data[:event][:id], 1) nil end end end
Use heredoc so it's more clear
module QA module Runtime module User extend self def name ENV['GITLAB_USERNAME'] || 'root' end def password ENV['GITLAB_PASSWORD'] || '5iveL!fe' end def ssh_key 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDFf6RYK3qu/RKF/3ndJmL5xgMLp3O9' \ '6x8lTay+QGZ0+9FnnAXMdUqBq/ZU6d/gyMB4IaW3nHzM1w049++yAB6UPCzMB8Uo27K5' \ '/jyZCtj7Vm9PFNjF/8am1kp46c/SeYicQgQaSBdzIW3UDEa1Ef68qroOlvpi9PYZ/tA7' \ 'M0YP0K5PXX+E36zaIRnJVMPT3f2k+GnrxtjafZrwFdpOP/Fol5BQLBgcsyiU+LM1SuaC' \ 'rzd8c9vyaTA1CxrkxaZh+buAi0PmdDtaDrHd42gqZkXCKavyvgM5o2CkQ5LJHCgzpXy0' \ '5qNFzmThBSkb+XtoxbyagBiGbVZtSVow6Xa7qewz= dummy@gitlab.com' end end end end
module QA module Runtime module User extend self def name ENV['GITLAB_USERNAME'] || 'root' end def password ENV['GITLAB_PASSWORD'] || '5iveL!fe' end def ssh_key <<~KEY.tr("\n", '') ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDFf6RYK3qu/RKF/3ndJmL5xgMLp3O9 6x8lTay+QGZ0+9FnnAXMdUqBq/ZU6d/gyMB4IaW3nHzM1w049++yAB6UPCzMB8Uo27K5 /jyZCtj7Vm9PFNjF/8am1kp46c/SeYicQgQaSBdzIW3UDEa1Ef68qroOlvpi9PYZ/tA7 M0YP0K5PXX+E36zaIRnJVMPT3f2k+GnrxtjafZrwFdpOP/Fol5BQLBgcsyiU+LM1SuaC rzd8c9vyaTA1CxrkxaZh+buAi0PmdDtaDrHd42gqZkXCKavyvgM5o2CkQ5LJHCgzpXy0 5qNFzmThBSkb+XtoxbyagBiGbVZtSVow6Xa7qewz= dummy@gitlab.com KEY end end end end
Add due items to full text search results
class DueItem < ActiveRecord::Base include MyplaceonlineActiveRecordIdentityConcern belongs_to :calendar end
class DueItem < ActiveRecord::Base include MyplaceonlineActiveRecordIdentityConcern belongs_to :calendar def final_search_result self.calendar end end
Allow passing credentials via environment variables
require "yaml" class ShinseiBank module CLI class Subcommand < Thor DEFAULT_CREDENTIALS_PATH = "./shinsei_account.yaml".freeze class_option :credentials, type: :string, aliases: "-c", default: DEFAULT_CREDENTIALS_PATH private def shinsei_bank @shinsei_bank ||= ShinseiBank.connect(credentials) end def logout puts "Logging out..." @shinsei_bank&.logout end def credentials YAML.load_file(options[:credentials]) end end end end
require "yaml" class ShinseiBank module CLI class Subcommand < Thor DEFAULT_CREDENTIALS_YAML = "./shinsei_account.yaml".freeze class_option :credentials, type: :string, aliases: "-c", default: DEFAULT_CREDENTIALS_YAML private def shinsei_bank @shinsei_bank ||= ShinseiBank.connect(credentials) end def logout puts "Logging out..." @shinsei_bank&.logout end def credentials env_credentials || yaml_credentials end def yaml_credentials YAML.load_file(options[:credentials]) end def env_credentials return unless env_var(:account) { "account" => env_var(:account), "password" => env_var(:password), "pin" => env_var(:pin), "code_card" => env_var(:code_card).split(",") } end def env_var(key) ENV["SHINSEIBANK_#{key.upcase}"] end end end end
Test other cases aswell in gem tag test using stubs.
require 'test_helper' class GemTest < ActiveSupport::TestCase context "gem with version" do setup do @gem = Mactag::Tag::Gem.new("thinking-sphinx", :version => "1.0.0") end should "return the gem with that version" do assert_contains @gem.files, File.join(Mactag::Config.gem_home, "thinking-sphinx-1.0.0", "**", "*.rb") end end end
require 'test_helper' class GemTest < ActiveSupport::TestCase context "gem with version" do setup do @gem = Mactag::Tag::Gem.new("thinking-sphinx", :version => "1.0.0") end should "return the gem with that version" do assert_contains @gem.files, File.join(Mactag::Config.gem_home, "thinking-sphinx-1.0.0", "**", "*.rb") end end context "gem without version" do context "one gem" do setup do Dir.stubs(:glob).returns("whenever") @gem = Mactag::Tag::Gem.new("whenever") end should "return that gem" do assert_contains @gem.files, "whenever/**/*.rb" end end context "multiple gems" do setup do Dir.stubs(:glob).returns(["whenever-0.3.7", "whenever-0.3.6"]) @gem = Mactag::Tag::Gem.new("whenever") end should "return the gem with the latest version" do assert_contains @gem.files, "whenever-0.3.7/**/*.rb" assert_does_not_contain @gem.files, "whenever-0.3.6/**/*.rb" end end end end
Update jekyll version dependency to get it working with jekyll v3
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'jekyll-fridge/version' Gem::Specification.new do |spec| spec.add_development_dependency 'bundler', '~> 1.0' spec.add_dependency 'jekyll', '~> 2.5.3' spec.add_dependency 'fridge_api', '~> 0.2.2' spec.authors = ["Mike Kruk"] spec.email = ['mike@ripeworks.com'] spec.summary = %q{Jekyll plugin for building sites using Fridge content} spec.description = %q{Jekyll plugin for building sites using Fridge content} spec.files = %w(Rakefile LICENSE README.md jekyll-fridge.gemspec) spec.files += Dir.glob("lib/**/*.rb") spec.homepage = 'https://github.com/fridge-cms/jekyll-fridge' spec.licenses = ['MIT'] spec.name = 'jekyll-fridge' spec.require_paths = ['lib'] spec.required_ruby_version = '>= 1.9.2' spec.required_rubygems_version = '>= 1.3.5' spec.version = Jekyll::Fridge::VERSION.dup end
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'jekyll-fridge/version' Gem::Specification.new do |spec| spec.add_development_dependency 'bundler', '~> 1.0' spec.add_dependency 'jekyll', '>= 2.0' spec.add_dependency 'fridge_api', '~> 0.2.2' spec.authors = ["Mike Kruk"] spec.email = ['mike@ripeworks.com'] spec.summary = %q{Jekyll plugin for building sites using Fridge content} spec.description = %q{Jekyll plugin for building sites using Fridge content} spec.files = %w(Rakefile LICENSE README.md jekyll-fridge.gemspec) spec.files += Dir.glob("lib/**/*.rb") spec.homepage = 'https://github.com/fridge-cms/jekyll-fridge' spec.licenses = ['MIT'] spec.name = 'jekyll-fridge' spec.require_paths = ['lib'] spec.required_ruby_version = '>= 1.9.2' spec.required_rubygems_version = '>= 1.3.5' spec.version = Jekyll::Fridge::VERSION.dup end
Add lockfile parser unit tests
# frozen_string_literal: true require "spec_helper" require "bundler/lockfile_parser" describe Bundler::LockfileParser do let(:lockfile_contents) { strip_whitespace(<<-L) } GIT remote: https://github.com/alloy/peiji-san.git revision: eca485d8dc95f12aaec1a434b49d295c7e91844b specs: peiji-san (1.2.0) GEM remote: https://rubygems.org/ specs: rake (10.3.2) PLATFORMS ruby DEPENDENCIES peiji-san! rake RUBY VERSION ruby 2.1.3p242 BUNDLED WITH 1.12.0.rc.2 L describe ".attributes_in_lockfile" do it "returns the attributes" do attributes = described_class.attributes_in_lockfile(lockfile_contents) expect(attributes).to contain_exactly( "BUNDLED WITH", "DEPENDENCIES", "GEM", "GIT", "PLATFORMS", "RUBY VERSION" ) end end describe ".unknown_attributes_in_lockfile" do let(:lockfile_contents) { strip_whitespace(<<-L) } UNKNOWN ATTR UNKNOWN ATTR 2 random contents L it "returns the unknown attributes" do attributes = described_class.unknown_attributes_in_lockfile(lockfile_contents) expect(attributes).to contain_exactly("UNKNOWN ATTR", "UNKNOWN ATTR 2") end end describe ".attributes_to_ignore" do subject { described_class.attributes_to_ignore(base_version) } context "with a nil base version" do let(:base_version) { nil } it "returns the same as > 1.0" do expect(subject).to contain_exactly( described_class::BUNDLED, described_class::RUBY ) end end context "with a prerelease base version" do let(:base_version) { Gem::Version.create("1.11.0.rc.1") } it "returns the same as for the release version" do expect(subject).to contain_exactly( described_class::RUBY ) end end context "with a current version" do let(:base_version) { Gem::Version.create(Bundler::VERSION) } it "returns an empty array" do expect(subject).to eq([]) end end context "with a future version" do let(:base_version) { Gem::Version.create("5.5.5") } it "returns an empty array" do expect(subject).to eq([]) end end end end
Remove test files from gem bundle.
# coding: utf-8 Gem::Specification.new do |spec| spec.name = "jekyll-watch" spec.version = "1.1.0" spec.authors = ["Parker Moore"] spec.email = ["parkrmoore@gmail.com"] spec.summary = %q{Rebuild your Jekyll site when a file changes with the `--watch` switch.} spec.homepage = "https://github.com/jekyll/jekyll-watch" 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_runtime_dependency "listen", "~> 2.7" require 'rbconfig' if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/ spec.add_runtime_dependency "wdm", "~> 0.1.0" end spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake" spec.add_development_dependency "rspec", "~> 3.0" spec.add_development_dependency "jekyll", "~> 2.0" end
# coding: utf-8 Gem::Specification.new do |spec| spec.name = "jekyll-watch" spec.version = "1.1.0" spec.authors = ["Parker Moore"] spec.email = ["parkrmoore@gmail.com"] spec.summary = %q{Rebuild your Jekyll site when a file changes with the `--watch` switch.} spec.homepage = "https://github.com/jekyll/jekyll-watch" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").grep(%r{(bin|lib)/}) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_runtime_dependency "listen", "~> 2.7" require 'rbconfig' if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/ spec.add_runtime_dependency "wdm", "~> 0.1.0" end spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake" spec.add_development_dependency "rspec", "~> 3.0" spec.add_development_dependency "jekyll", "~> 2.0" end
Fix bug with Rails 5.2
module ActiveRecord module Annotate module Dumper class << self def dump(table_name, connection = ActiveRecord::Base.connection) string_io = StringIO.new if connection.table_exists?(table_name) dumper(connection).send(:table, table_name, string_io) else string_io.write(" # can't find table `#{table_name}`") end process_annotation(string_io) end private def dumper(connection) ActiveRecord::SchemaDumper.send(:new, connection) end def process_annotation(string_io) string_io.string.split(?\n).map do |line| line.tap do |line| # commenting out the line line[0] = '#' # replacing strings with symbols line.gsub!(/"(\w+)"/, ':\1') end end end end end end end
module ActiveRecord module Annotate module Dumper class << self def dump(table_name, connection = ActiveRecord::Base.connection, config = ActiveRecord::Base) string_io = StringIO.new if connection.table_exists?(table_name) dumper(connection, config).send(:table, table_name, string_io) else string_io.write(" # can't find table `#{table_name}`") end process_annotation(string_io) end private def dumper(connection, config) if connection.respond_to?(:create_schema_dumper) connection.create_schema_dumper(ActiveRecord::SchemaDumper.send(:generate_options, config)) else ActiveRecord::SchemaDumper.send(:new, connection) end end def process_annotation(string_io) string_io.string.split(?\n).map do |line| line.tap do |line| # commenting out the line line[0] = '#' # replacing strings with symbols line.gsub!(/"(\w+)"/, ':\1') end end end end end end end
Allow CI to use the latest rubygems version
Project.configure do |project| project.build_command = 'sudo gem update --system 1.6.2 && ruby ci/ci_build.rb' project.email_notifier.from = 'rails-ci@wyeworks.com' # project.campfire_notifier.account = 'rails' # project.campfire_notifier.token = '' # project.campfire_notifier.room = 'Rails 3' # project.campfire_notifier.ssl = true end
Project.configure do |project| project.build_command = 'sudo gem update --system && ruby ci/ci_build.rb' project.email_notifier.from = 'rails-ci@wyeworks.com' # project.campfire_notifier.account = 'rails' # project.campfire_notifier.token = '' # project.campfire_notifier.room = 'Rails 3' # project.campfire_notifier.ssl = true end
Fix 'ArgumentError: "VpiHigh" is not a valid VPI property'
<% clock = aModuleInfo.clock_port.name rescue "YOUR_CLOCK_SIGNAL_HERE" %> # Simulates the design under test for one clock cycle. def DUT.cycle! <%= clock %>.high! advance_time <%= clock %>.low! advance_time end <% reset = aModuleInfo.reset_port.name rescue "YOUR_RESET_SIGNAL_HERE" %> # Brings the design under test into a blank state. def DUT.reset! <%= reset %>.high! cycle! <%= reset %>.low! end
<% clock = aModuleInfo.clock_port.name rescue "YOUR_CLOCK_SIGNAL_HERE" %> # Simulates the design under test for one clock cycle. def DUT.cycle! <%= clock %>.t! advance_time <%= clock %>.f! advance_time end <% reset = aModuleInfo.reset_port.name rescue "YOUR_RESET_SIGNAL_HERE" %> # Brings the design under test into a blank state. def DUT.reset! <%= reset %>.t! cycle! <%= reset %>.f! end
Use Kaminari's default config for (max_)per_page
require "grape/kaminari/version" require "grape/kaminari/max_value_validator" require "kaminari/grape" module Grape module Kaminari def self.included(base) base.class_eval do helpers do def paginate(collection) collection.page(params[:page]).per(params[:per_page]).tap do |data| header "X-Total", data.total_count.to_s header "X-Total-Pages", data.num_pages.to_s header "X-Per-Page", params[:per_page].to_s header "X-Page", data.current_page.to_s header "X-Next-Page", data.next_page.to_s header "X-Prev-Page", data.prev_page.to_s end end end def self.paginate(options = {}) options.reverse_merge!( per_page: 10, max_per_page: false ) params do optional :page, type: Integer, default: 1, desc: 'Page offset to fetch.' optional :per_page, type: Integer, default: options[:per_page], desc: 'Number of results to return per page.', max_value: options[:max_per_page] end end end end end end
require "grape/kaminari/version" require "grape/kaminari/max_value_validator" require "kaminari/grape" module Grape module Kaminari def self.included(base) base.class_eval do helpers do def paginate(collection) collection.page(params[:page]).per(params[:per_page]).tap do |data| header "X-Total", data.total_count.to_s header "X-Total-Pages", data.num_pages.to_s header "X-Per-Page", params[:per_page].to_s header "X-Page", data.current_page.to_s header "X-Next-Page", data.next_page.to_s header "X-Prev-Page", data.prev_page.to_s end end end def self.paginate(options = {}) options.reverse_merge!( per_page: ::Kaminari.config.default_per_page || 10, max_per_page: ::Kaminari.config.max_per_page ) params do optional :page, type: Integer, default: 1, desc: 'Page offset to fetch.' optional :per_page, type: Integer, default: options[:per_page], desc: 'Number of results to return per page.', max_value: options[:max_per_page] end end end end end end
Fix of nill values v2
require 'json' require 'net/http' require 'uri' module PagerDuty class Full attr_reader :apikey, :subdomain def initialize(apikey, subdomain) @apikey = apikey @subdomain = subdomain end def api_call(path, params) uri = URI.parse("https://#{@subdomain}.pagerduty.com/api/v1/#{path}") http = Net::HTTP.new(uri.host, uri.port) output = [] params.each_pair do |key,val| if (!val.nil?) output << "#{URI.encode(key.to_s)}=#{URI.encode(val)}" end end uri.query = "?#{output.join("&")}" req = Net::HTTP::Get.new(uri.request_uri) res = http.get(uri.to_s, { 'Content-type' => 'application/json', 'Authorization' => "Token token=#{@apikey}" }) end def Incident() PagerDuty::Resource::Incident.new(@apikey, @subdomain) end def Schedule() PagerDuty::Resource::Schedule.new(@apikey, @subdomain) end end end
require 'json' require 'net/http' require 'uri' module PagerDuty class Full attr_reader :apikey, :subdomain def initialize(apikey, subdomain) @apikey = apikey @subdomain = subdomain end def api_call(path, params) uri = URI.parse("https://#{@subdomain}.pagerduty.com/api/v1/#{path}") http = Net::HTTP.new(uri.host, uri.port) output = [] params.each_pair do |key,val| if (!val.nil?) output << "#{URI.encode(key.to_s)}=#{URI.encode(val)}" end end uri.query = "#{output.join("&")}" req = Net::HTTP::Get.new(uri.request_uri) res = http.get(uri.to_s, { 'Content-type' => 'application/json', 'Authorization' => "Token token=#{@apikey}" }) end def Incident() PagerDuty::Resource::Incident.new(@apikey, @subdomain) end def Schedule() PagerDuty::Resource::Schedule.new(@apikey, @subdomain) end end end
Fix minor formatting issues in HerokuDataclip
class HerokuDataclipPlugin < Scout::Plugin OPTIONS=<<-EOS dataclip_ids: default: "" # a comma-delimited list of dataclip IDs (the string of letters from the url) which return ONLY ONE FIELD AND ROW each EOS def build_report dataclip_ids = option(:dataclip_ids) if dataclip_ids.nil? || dataclip_ids.empty? || dataclip_ids !~ /^[a-z,]+$/ return error("Invalid or missing option \"dataclip_ids\"", "The \"dataclip_ids\" option is required to be a comma-delimited list of dataclip IDs " + "(the string of letters from the \"dataclips.heroku.com\" url) " + "which return ONLY ONE FIELD AND ROW each " + "(e.g. \"SELECT COUNT(*) AS total_count FROM tablename;\". " + "Provided value was \"#{dataclip_ids}\"" ) end dataclip_ids = dataclip_ids.split(',') dataclip_result_arrays = [] dataclip_ids.each do |dataclip_id| dataclip_result_arrays << `curl -L https://dataclips.heroku.com/#{dataclip_id}.csv`.split end dataclip_result_arrays.each do |dataclip_result_array| field_name = dataclip_result_array[0].to_sym field_value = dataclip_result_array[1] report(field_name => field_value) end end end
class HerokuDataclip < Scout::Plugin OPTIONS=<<-EOS dataclip_ids: default: "" notes: A comma-delimited list of dataclip IDs (the string of letters from the url) which return ONLY ONE FIELD AND ROW each EOS def build_report dataclip_ids = option(:dataclip_ids) if dataclip_ids.nil? || dataclip_ids.empty? || dataclip_ids !~ /^[a-z,]+$/ return error('Invalid or missing option "dataclip_ids"', 'The "dataclip_ids\" option is required to be a comma-delimited list of dataclip IDs ' + '(the string of letters from the "dataclips.heroku.com" url) ' + 'which return ONLY ONE FIELD AND ROW each ' + '(e.g. "SELECT COUNT(*) AS total_count FROM tablename;".' ) end dataclip_ids = dataclip_ids.split(',') dataclip_result_arrays = [] dataclip_ids.each do |dataclip_id| dataclip_result_arrays << `curl -L https://dataclips.heroku.com/#{dataclip_id}.csv`.split end dataclip_result_arrays.each do |dataclip_result_array| field_name = dataclip_result_array[0].to_sym field_value = dataclip_result_array[1] report(field_name => field_value) end end end
Return guard for generate_username; no need to validate e-mail presence
module Outpost module Model module Authentication extend ActiveSupport::Concern included do has_secure_password before_validation :downcase_email, if: -> { self.email_changed? } before_validation :generate_username, on: :create, if: -> { self.username.blank? } validates :name, presence: true validates :email, presence: true validates :username, presence: true, uniqueness: true end module ClassMethods def authenticate(username, unencrypted_password) self.find_by_username(username).try(:authenticate, unencrypted_password) end end private # Private: Generate a username based on real name # # Returns String of the username def generate_username names = self.name.to_s.split base = (names.first.chars.first + names.last).downcase.gsub(/\W/, "") dirty_name = base i = 1 while self.class.exists?(username: dirty_name) dirty_name = base + i.to_s i += 1 end self.username = dirty_name end # Private: Downcase the user's e-mail # # Returns String of the e-mail def downcase_email if self.email.present? self.email = self.email.downcase end end end end end
module Outpost module Model module Authentication extend ActiveSupport::Concern included do has_secure_password before_validation :downcase_email, if: -> { self.email_changed? } before_validation :generate_username, on: :create, if: -> { self.username.blank? } validates :name, presence: true validates :username, presence: true, uniqueness: true end module ClassMethods def authenticate(username, unencrypted_password) self.find_by_username(username).try(:authenticate, unencrypted_password) end end # Private: Generate a username based on real name # # Returns String of the username def generate_username return nil if !self.name.present? names = self.name.to_s.split base = (names.first.chars.first + names.last).downcase.gsub(/\W/, "") dirty_name = base i = 1 while self.class.exists?(username: dirty_name) dirty_name = base + i.to_s i += 1 end self.username = dirty_name end # Private: Downcase the user's e-mail # # Returns String of the e-mail def downcase_email if self.email.present? self.email = self.email.downcase end end end end end
Use https to report exceptions
## # This class hold all configurations related to Bugflux. Our aim is to make this # a generalized class that collects metrics for all the apps like: bugflux, # perflux etc based on the host application configuration. # # Also, it would be better to extract the notice sending logic to its own gem. # This is because all hook applications might not be on the same address. module AppfluxRuby class BugfluxConfig ## # @return [ID] Identify the application where to send the notification. # This value *must* be set. attr_accessor :app_id, :ignored_environments ## # @return [Logger] the default logger used for debug output # attr_accessor :logger ## # @return [String] the host, which provides the API endpoint to which # exceptions should be sent attr_reader :host def initialize config = Hash.new @host = host_name end ## # @return [Boolean], Whether we are using secure connection or not. def use_ssl false end private # This is the URL to API that accepts notifications generated by this gem. # Should be something like: /applications/<app_id>/notifications [POST] def host_name 'http://appflux.io/exceptions' end end end
## # This class hold all configurations related to Bugflux. Our aim is to make this # a generalized class that collects metrics for all the apps like: bugflux, # perflux etc based on the host application configuration. # # Also, it would be better to extract the notice sending logic to its own gem. # This is because all hook applications might not be on the same address. module AppfluxRuby class BugfluxConfig ## # @return [ID] Identify the application where to send the notification. # This value *must* be set. attr_accessor :app_id, :ignored_environments ## # @return [Logger] the default logger used for debug output # attr_accessor :logger ## # @return [String] the host, which provides the API endpoint to which # exceptions should be sent attr_reader :host def initialize config = Hash.new @host = host_name end ## # @return [Boolean], Whether we are using secure connection or not. def use_ssl false end private # This is the URL to API that accepts notifications generated by this gem. # Should be something like: /applications/<app_id>/notifications [POST] def host_name 'https://appflux.io/exceptions' end end end
Set the default parameters for chef-client on startup
# Copyright 2011, Dell # # 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. # package "ipmitool" do package_name "OpenIPMI-tools" if node[:platform] =~ /^(redhat|centos)$/ action :install end directory "/root/.ssh" do owner "root" group "root" mode "0700" action :create end cookbook_file "/root/.ssh/authorized_keys" do owner "root" group "root" mode "0700" action :create source "authorized_keys" end cookbook_file "/etc/default/chef-client" do owner "root" group "root" mode "0644" action :create source "chef-client" end
# Copyright 2011, Dell # # 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. # package "ipmitool" do package_name "OpenIPMI-tools" if node[:platform] =~ /^(redhat|centos)$/ action :install end directory "/root/.ssh" do owner "root" group "root" mode "0700" action :create end cookbook_file "/root/.ssh/authorized_keys" do owner "root" group "root" mode "0700" action :create source "authorized_keys" end config_file = "/etc/default/chef-client" config_file = "/etc/sysconfig/chef-client" if node[:platform] =~ /^(redhat|centos)$/ cookbook_file config_file do owner "root" group "root" mode "0644" action :create source "chef-client" end
Put `{` on the same line as `(`.
class AccessToken < ActiveRecord::Base belongs_to :repository attr_accessible :expiration, :token scope :expired, ->() { where('expiration <= ?', Time.now) } scope :unexpired, ->() { where('expiration > ?', Time.now) } def self.destroy_expired expired.find_each(&:destroy) end def self.create_for(ontology_version) # Although unlikely, the token could clash with another one. Generate tokens # until there is no conflict. This should converge extremely fast. access_token = nil while access_token.nil? || access_token.invalid? do access_token = build_for(ontology_version) end access_token.save! access_token end def self.fresh_expiration_date Settings.access_token.expiration_minutes.minutes.from_now end def self.build_for(ontology_version) repository = ontology_version.repository AccessToken.new( {repository: repository, expiration: fresh_expiration_date, token: generate_token_string(ontology_version, repository)}, {without_protection: true}) end def self.generate_token_string(ontology_version, repository) id = [ repository.to_param, ontology_version.path, Time.now.strftime('%Y-%m-%d-%H-%M-%S-%6N') ].join('|') Digest::SHA2.hexdigest(id) end def to_s token end def expired? expiration <= Time.now end end
class AccessToken < ActiveRecord::Base belongs_to :repository attr_accessible :expiration, :token scope :expired, ->() { where('expiration <= ?', Time.now) } scope :unexpired, ->() { where('expiration > ?', Time.now) } def self.destroy_expired expired.find_each(&:destroy) end def self.create_for(ontology_version) # Although unlikely, the token could clash with another one. Generate tokens # until there is no conflict. This should converge extremely fast. access_token = nil while access_token.nil? || access_token.invalid? do access_token = build_for(ontology_version) end access_token.save! access_token end def self.fresh_expiration_date Settings.access_token.expiration_minutes.minutes.from_now end def self.build_for(ontology_version) repository = ontology_version.repository AccessToken.new({ repository: repository, expiration: fresh_expiration_date, token: generate_token_string(ontology_version, repository)}, {without_protection: true}) end def self.generate_token_string(ontology_version, repository) id = [ repository.to_param, ontology_version.path, Time.now.strftime('%Y-%m-%d-%H-%M-%S-%6N') ].join('|') Digest::SHA2.hexdigest(id) end def to_s token end def expired? expiration <= Time.now end end
Add auth_signin spec to features spec folder with test for visiting signin page
require 'spec_helper' RSpec.feature "User Sign Up", :type => :feature do scenario "A user can access the signin page" do visit signin_path expect(page).to have_content("Sign In") expect(page).to have_content("Name") expect(page).to have_content("Password") end