Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Remove reference to non-existing readme.rdoc file
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "product_food/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "product_food" s.version = ProductFood::VERSION s.authors = ["Chris Blackburn"] s.email = ["chris@madebymade.co.uk"] s.homepage = "http://www.madebymade.co.uk/" s.summary = "Product food engine." s.description = "Rails engine that provides the functionality required to add food-based products to a site" s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 3.2.11" end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "product_food/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "product_food" s.version = ProductFood::VERSION s.authors = ["Chris Blackburn"] s.email = ["chris@madebymade.co.uk"] s.homepage = "http://www.madebymade.co.uk/" s.summary = "Product food engine." s.description = "Rails engine that provides the functionality required to add food-based products to a site" s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 3.2.11" end
Revert "The refined Module should be `using`ed where the method is executed"
using ActionArgs::ParamsHandler module ActionArgs module ActiveSupport module CallbackParameterizer if Rails.version > '4.1' # Extending AS::Callbacks::Callback's `make_lambda` not just to call specified # method but to call the method with method parameters taken from `params`. # This would happen only when # * the filter was defined in Symbol form # * the target object is_a ActionController object def make_lambda(filter) if Symbol === filter lambda do |target, _, &blk| if ActionController::Base === target target.send_with_method_parameters_from_params filter, &blk else target.send filter, &blk end end else super end end elsif Rails.version > '4.0' def apply(code) if (Symbol === @filter) && (@klass < ActionController::Base) method_body = <<-FILTER using ActionArgs::ParamsHandler send_with_method_parameters_from_params :#{@filter} FILTER if @kind == :before @filter = "begin\n#{method_body}\nend" else @filter = method_body.chomp end end super end end end end end module ActiveSupport module Callbacks class Callback prepend ActionArgs::ActiveSupport::CallbackParameterizer end end end
using ActionArgs::ParamsHandler module ActionArgs module ActiveSupport module CallbackParameterizer if Rails.version > '4.1' # Extending AS::Callbacks::Callback's `make_lambda` not just to call specified # method but to call the method with method parameters taken from `params`. # This would happen only when # * the filter was defined in Symbol form # * the target object is_a ActionController object def make_lambda(filter) if Symbol === filter lambda do |target, _, &blk| if ActionController::Base === target target.send_with_method_parameters_from_params filter, &blk else target.send filter, &blk end end else super end end elsif Rails.version > '4.0' def apply(code) if (Symbol === @filter) && (@klass < ActionController::Base) method_body = <<-FILTER send_with_method_parameters_from_params :#{@filter} FILTER if @kind == :before @filter = "begin\n#{method_body}\nend" else @filter = method_body.chomp end end super end end end end end module ActiveSupport module Callbacks class Callback prepend ActionArgs::ActiveSupport::CallbackParameterizer end end end
Modify field name of topIssue API
require 'fabricio/models/abstract_model' module Fabricio module Model # This model represents an application build class Issue < AbstractModel attr_reader :id, :displayId, :externalId, :title, :subtitle, :createdAt, :type, :state, :occurrenceCount, :impactedDevices # Returns a Build model object # # @param attributes [Hash] # @return [Fabricio::Model::Build] def initialize(attributes) @id = attributes['id'] @displayId = attributes['displayId'] @externalId = attributes['externalId'] @title = attributes['title'] @subtitle = attributes['subtitle'] @createdAt = attributes['createdAt'] @type = attributes['type'] @state = attributes['state'] @occurrenceCount = attributes['_occurrenceCount2I980d"'] @impactedDevices = attributes['_impactedDevices2oATOx'] @json = attributes end end end end
require 'fabricio/models/abstract_model' module Fabricio module Model # This model represents an application build class Issue < AbstractModel attr_reader :id, :displayId, :externalId, :title, :subtitle, :createdAt, :type, :state, :occurrenceCount, :impactedDevices # Returns a Build model object # # @param attributes [Hash] # @return [Fabricio::Model::Build] def initialize(attributes) @id = attributes['id'] @displayId = attributes['displayId'] @externalId = attributes['externalId'] @title = attributes['title'] @subtitle = attributes['subtitle'] @createdAt = attributes['createdAt'] @type = attributes['type'] @state = attributes['state'] @occurrenceCount = attributes['_occurrenceCount2I980d"'] || attributes['occurrenceCount'] @impactedDevices = attributes['_impactedDevices2oATOx'] || attributes['impactedDevices'] @json = attributes end end end end
Add missing explicit action* requires
require 'action_view' require 'webmachine/actionview/version' require 'webmachine/actionview/configuration' require 'webmachine/actionview/resource'
require 'action_view' require 'active_support/core_ext/hash' require 'active_support/core_ext/string' require 'action_dispatch/http/mime_type' require 'webmachine/actionview/version' require 'webmachine/actionview/configuration' require 'webmachine/actionview/resource'
Move the slugs for No10 and DPMO
Organisation.find_by_slug('the-prime-ministers-office-number-10').update_attribute(:slug, 'prime-ministers-office-10-downing-street') Organisation.find_by_slug('the-deputy-prime-ministers-office').update_attribute(:slug, 'deputy-prime-ministers-office')
Set default timeout to 4 seconds because 1 is not really enough
module CurrencyRate class Adapter include Singleton FETCH_URL = nil API_KEY_PARAM = nil def name self.class.name.gsub /^.*::/, "" end def fetch_rates begin normalize exchange_data rescue StandardError => e CurrencyRate.logger.error("Error in #{self.name}#fetch_rates") CurrencyRate.logger.error(e) nil end end def normalize(data) if data.nil? CurrencyRate.logger.warn("#{self.name}#normalize: data is nil") return nil end true end def exchange_data raise "FETCH_URL is not defined!" unless self.class::FETCH_URL begin if self.class::FETCH_URL.kind_of?(Hash) self.class::FETCH_URL.reduce({}) do |result, (name, url)| result[name] = request url result end else request self.class::FETCH_URL end rescue StandardError => e CurrencyRate.logger.error("Error in #{self.name}#exchange_data") CurrencyRate.logger.error(e) nil end end def request(url) fetch_url = url if self.class::API_KEY_PARAM api_key = CurrencyRate.configuration.api_keys[self.name] fetch_url << "&#{self.class::API_KEY_PARAM}=#{api_key}" if api_key end http_client = HTTP.timeout(connect: 1, read: 1) JSON.parse(http_client.get(fetch_url).to_s) end end end
module CurrencyRate class Adapter include Singleton FETCH_URL = nil API_KEY_PARAM = nil def name self.class.name.gsub /^.*::/, "" end def fetch_rates begin normalize exchange_data rescue StandardError => e CurrencyRate.logger.error("Error in #{self.name}#fetch_rates") CurrencyRate.logger.error(e) nil end end def normalize(data) if data.nil? CurrencyRate.logger.warn("#{self.name}#normalize: data is nil") return nil end true end def exchange_data raise "FETCH_URL is not defined!" unless self.class::FETCH_URL begin if self.class::FETCH_URL.kind_of?(Hash) self.class::FETCH_URL.reduce({}) do |result, (name, url)| result[name] = request url result end else request self.class::FETCH_URL end rescue StandardError => e CurrencyRate.logger.error("Error in #{self.name}#exchange_data") CurrencyRate.logger.error(e) nil end end def request(url) fetch_url = url if self.class::API_KEY_PARAM api_key = CurrencyRate.configuration.api_keys[self.name] fetch_url << "&#{self.class::API_KEY_PARAM}=#{api_key}" if api_key end http_client = HTTP.timeout(connect: 4, read: 4) JSON.parse(http_client.get(fetch_url).to_s) end end end
Include all dependencies in gemspec
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "flag_shih_tzu/version" Gem::Specification.new do |s| s.name = "flag_shih_tzu" s.version = FlagShihTzu::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Patryk Peszko", "Sebastian Roebke", "David Anderson", "Tim Payton"] s.homepage = "https://github.com/xing/flag_shih_tzu" s.summary = %q{A rails plugin to store a collection of boolean attributes in a single ActiveRecord column as a bit field} s.description = <<-EODOC This plugin lets you use a single integer column in an ActiveRecord model to store a collection of boolean attributes (flags). Each flag can be used almost in the same way you would use any boolean attribute on an ActiveRecord object. EODOC 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 "flag_shih_tzu/version" Gem::Specification.new do |s| s.name = "flag_shih_tzu" s.version = FlagShihTzu::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Patryk Peszko", "Sebastian Roebke", "David Anderson", "Tim Payton"] s.homepage = "https://github.com/xing/flag_shih_tzu" s.summary = %q{A rails plugin to store a collection of boolean attributes in a single ActiveRecord column as a bit field} s.description = <<-EODOC This plugin lets you use a single integer column in an ActiveRecord model to store a collection of boolean attributes (flags). Each flag can be used almost in the same way you would use any boolean attribute on an ActiveRecord object. EODOC s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_dependency "activerecord", ">= 2.3.0" s.add_development_dependency "bundler" s.add_development_dependency "rdoc", ">= 2.4.2" s.add_development_dependency "rake" s.add_development_dependency "rcov" s.add_development_dependency "sqlite3" end
Fix bug -- multiple scribbles was created per user unless user refreshes page after first scribble
class ScribblesController < ApplicationController def create if scribble_params['id'] == "" @scribble = Scribble.new(scribble_params) else @scribble = Scribble.find(scribble_params['id']) @scribble.update_attributes(scribble_params) end @scribble.save respond_to do |format| format.json { render :json => @post } end end private def scribble_params params[:scribble].slice :content, :std_course_id, :scribing_answer_id, :id end end
class ScribblesController < ApplicationController def create if scribble_params['id'] != "" @scribble = Scribble.find(scribble_params['id']) else @scribble = Scribble.where({ std_course_id: scribble_params[:std_course_id], scribing_answer_id: scribble_params[:scribing_answer_id] }).first end if @scribble @scribble.update_attributes(scribble_params) else @scribble = Scribble.new(scribble_params) end @scribble.save respond_to do |format| format.json { render :json => @post } end end private def scribble_params params[:scribble].slice :content, :std_course_id, :scribing_answer_id, :id end end
Reorganize gemspec and add nokogiri as a dev dependency.
# -*- encoding: utf-8 -*- require File.expand_path('../lib/liquor/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Peter Zotov"] gem.email = ["whitequark@whitequark.org"] gem.description = %q{TODO: Write a gem description} gem.summary = %q{TODO: Write a gem summary} gem.homepage = "" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "liquor" gem.require_paths = ["lib"] gem.version = Liquor::VERSION gem.required_ruby_version = '>= 1.9' gem.add_development_dependency 'kramdown' gem.add_development_dependency 'rake' gem.add_development_dependency 'racc' gem.add_development_dependency 'rspec' gem.add_development_dependency 'guard-rspec' gem.add_development_dependency 'rack' gem.add_development_dependency 'activerecord' gem.add_development_dependency 'sqlite3' end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/liquor/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Peter Zotov"] gem.email = ["whitequark@whitequark.org"] gem.description = %q{TODO: Write a gem description} gem.summary = %q{TODO: Write a gem summary} gem.homepage = "" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "liquor" gem.require_paths = ["lib"] gem.version = Liquor::VERSION gem.required_ruby_version = '>= 1.9' # Generation of the parsers and documentation. gem.add_development_dependency 'rake' gem.add_development_dependency 'racc' gem.add_development_dependency 'kramdown' # Testing. gem.add_development_dependency 'rspec' gem.add_development_dependency 'guard-rspec' # Testing dependencies. gem.add_development_dependency 'rack' gem.add_development_dependency 'nokogiri' gem.add_development_dependency 'activerecord' gem.add_development_dependency 'sqlite3' end
Add provider attribute to Voucher
module Rabatt class Voucher ATTRIBUTES = %i(code expires_on valid_from url summary terms program) attr_accessor *ATTRIBUTES attr_accessor :payload def self.build(&block) new.tap(&block) end def attributes Hash[ATTRIBUTES.map { |key| [key, send(key)] }] end def inspect "#<#{self.class.name} #{inspect_attributes.join(', ')}>" end def inspect_attributes attributes.map do |name, value| "#{name}: #{value.inspect}" end end end end
module Rabatt class Voucher ATTRIBUTES = %i(provider code expires_on valid_from url summary terms program) attr_accessor *ATTRIBUTES attr_accessor :payload def self.build(&block) new.tap(&block) end def attributes Hash[ATTRIBUTES.map { |key| [key, send(key)] }] end def inspect "#<#{self.class.name} #{inspect_attributes.join(', ')}>" end def inspect_attributes attributes.map do |name, value| "#{name}: #{value.inspect}" end end end end
Allow all 0.2 patch releases
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'alephant/logger/version' Gem::Specification.new do |spec| spec.name = "alephant-logger" spec.version = Alephant::Logger::VERSION spec.authors = ["BBC News"] spec.email = ["FutureMediaNewsRubyGems@bbc.co.uk"] spec.summary = %q{Logger functionality for Alephant} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_runtime_dependency "alephant-logger-json", "~> 0.2.0" spec.add_development_dependency "rspec" spec.add_development_dependency "rspec-nc" spec.add_development_dependency "guard" spec.add_development_dependency "guard-rspec" spec.add_development_dependency "pry" spec.add_development_dependency "pry-remote" spec.add_development_dependency "pry-nav" spec.add_development_dependency "bundler", "~> 1.5" spec.add_development_dependency "rake" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'alephant/logger/version' Gem::Specification.new do |spec| spec.name = "alephant-logger" spec.version = Alephant::Logger::VERSION spec.authors = ["BBC News"] spec.email = ["FutureMediaNewsRubyGems@bbc.co.uk"] spec.summary = %q{Logger functionality for Alephant} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_runtime_dependency "alephant-logger-json", "~> 0.2" spec.add_development_dependency "rspec" spec.add_development_dependency "rspec-nc" spec.add_development_dependency "guard" spec.add_development_dependency "guard-rspec" spec.add_development_dependency "pry" spec.add_development_dependency "pry-remote" spec.add_development_dependency "pry-nav" spec.add_development_dependency "bundler", "~> 1.5" spec.add_development_dependency "rake" end
Add MIT license to gemspec
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "garage/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "the_garage" s.version = Garage::VERSION s.authors = ["Tatsuhiko Miyagawa"] s.email = ["miyagawa@bulknews.net"] s.homepage = "https://github.com/cookpad/garage" s.summary = "Garage Platform Engine" s.description = "Garage extends your RESTful, Hypermedia APIs as a Platform" s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"] s.add_dependency "rails", '>= 4.0.0' s.add_dependency "rack-accept-default", "~> 0.0.2" s.add_dependency "oj" s.add_dependency "responders" s.add_dependency "oauth2" s.add_dependency "redcarpet", ">= 3.1.1" s.add_dependency "haml" s.add_dependency "hashie" s.add_dependency "sass-rails" s.add_dependency "coffee-rails" s.add_dependency "http_accept_language", ">= 2.0.0" s.add_development_dependency "appraisal" end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "garage/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "the_garage" s.version = Garage::VERSION s.authors = ["Tatsuhiko Miyagawa"] s.email = ["miyagawa@bulknews.net"] s.homepage = "https://github.com/cookpad/garage" s.summary = "Garage Platform Engine" s.description = "Garage extends your RESTful, Hypermedia APIs as a Platform" s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"] s.add_dependency "rails", '>= 4.0.0' s.add_dependency "rack-accept-default", "~> 0.0.2" s.add_dependency "oj" s.add_dependency "responders" s.add_dependency "oauth2" s.add_dependency "redcarpet", ">= 3.1.1" s.add_dependency "haml" s.add_dependency "hashie" s.add_dependency "sass-rails" s.add_dependency "coffee-rails" s.add_dependency "http_accept_language", ">= 2.0.0" s.add_development_dependency "appraisal" end
Drop support for Ruby 2.2
# frozen_string_literal: true lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "bashcov/version" Gem::Specification.new do |gem| gem.name = "bashcov" gem.version = Bashcov::VERSION gem.authors = ["Cédric Félizard"] gem.email = ["cedric@felizard.fr"] gem.description = "Code coverage tool for Bash" gem.summary = gem.description gem.homepage = "https://github.com/infertux/bashcov" gem.license = "MIT" gem.files = `git ls-files -z`.split("\x0").reject do |file| file.start_with?(".") || file.match(%r{\A(test|spec|features)/}) end gem.executables = gem.files.grep(%r{\Abin/}).map { |f| File.basename(f) } gem.require_paths = ["lib"] gem.required_ruby_version = ">= 2.2.7" gem.add_dependency "simplecov", "~> 0.15" gem.add_development_dependency "coveralls" gem.add_development_dependency "mutant-rspec" gem.add_development_dependency "rake" gem.add_development_dependency "rspec" gem.add_development_dependency "rubocop" gem.add_development_dependency "yard" end
# frozen_string_literal: true lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "bashcov/version" Gem::Specification.new do |gem| gem.name = "bashcov" gem.version = Bashcov::VERSION gem.authors = ["Cédric Félizard"] gem.email = ["cedric@felizard.fr"] gem.description = "Code coverage tool for Bash" gem.summary = gem.description gem.homepage = "https://github.com/infertux/bashcov" gem.license = "MIT" gem.files = `git ls-files -z`.split("\x0").reject do |file| file.start_with?(".") || file.match(%r{\A(test|spec|features)/}) end gem.executables = gem.files.grep(%r{\Abin/}).map { |f| File.basename(f) } gem.require_paths = ["lib"] gem.required_ruby_version = ">= 2.3.0" gem.add_dependency "simplecov", "~> 0.15" gem.add_development_dependency "coveralls" gem.add_development_dependency "mutant-rspec" gem.add_development_dependency "rake" gem.add_development_dependency "rspec" gem.add_development_dependency "rubocop" gem.add_development_dependency "yard" end
Add prettier as dev dependency
# coding: utf-8 # frozen_string_literal: true lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rack/rejector/version' Gem::Specification.new do |spec| spec.name = 'rack-rejector' spec.version = Rack::Rejector::VERSION spec.authors = ['Tristan Druyen', 'Maik Röhrig'] spec.email = %w[tristan.druyen@invision.de maik.roehrig@invision.de] spec.summary = 'This gem is a Rack Middleware to reject requests.' spec.homepage = 'https://github.com/ivx/rack-rejector' spec.required_ruby_version = '>= 3.1' spec.metadata = { 'rubygems_mfa_required' => 'true' } spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.require_paths = %w[lib] spec.add_dependency 'rack' spec.add_development_dependency 'bundler', '~> 2' spec.add_development_dependency 'rake', '~> 13.0' spec.add_development_dependency 'rspec', '~> 3.0' end
# coding: utf-8 # frozen_string_literal: true lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rack/rejector/version' Gem::Specification.new do |spec| spec.name = 'rack-rejector' spec.version = Rack::Rejector::VERSION spec.authors = ['Tristan Druyen', 'Maik Röhrig'] spec.email = %w[tristan.druyen@invision.de maik.roehrig@invision.de] spec.summary = 'This gem is a Rack Middleware to reject requests.' spec.homepage = 'https://github.com/ivx/rack-rejector' spec.required_ruby_version = '>= 3.1' spec.metadata = { 'rubygems_mfa_required' => 'true' } spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.require_paths = %w[lib] spec.add_dependency 'rack' spec.add_development_dependency 'bundler', '~> 2' spec.add_development_dependency 'prettier' spec.add_development_dependency 'rake', '~> 13.0' spec.add_development_dependency 'rspec', '~> 3.0' end
Fix referenced form ID for filter reference popup
module Admin::EventsHelper def event_edit_javascripts <<-CODE var lastFilter = '#{@event.filter_id}'; var filterWindows = {}; function loadFilterReference() { var filter = $F('event_filter_id'); if (filter != "") { if (!filterWindows[filter]) filterWindows[filter] = new Popup.AjaxWindow("#{admin_reference_path('filters')}?filter_name="+encodeURIComponent(filter), {reload: false}); var window = filterWindows[filter]; if(lastFilter != filter) { window.show(); } else { window.toggle(); } lastFilter = filter; } else { alert('No documentation for filter.'); } return false; } CODE end end
module Admin::EventsHelper def event_edit_javascripts <<-CODE var lastFilter = '#{@event.filter_id}'; var filterWindows = {}; function loadFilterReference() { var filter = $F('event_description_filter_id'); if (filter != "") { if (!filterWindows[filter]) filterWindows[filter] = new Popup.AjaxWindow("#{admin_reference_path('filters')}?filter_name="+encodeURIComponent(filter), {reload: false}); var window = filterWindows[filter]; if(lastFilter != filter) { window.show(); } else { window.toggle(); } lastFilter = filter; } else { alert('No documentation for filter.'); } return false; } CODE end end
Add Failing test printer to Formatter
require 'colorize' module Dest class Formatter def initialize(evald_result) @evald_result end def print if @evald_result[:result][0] print_passing_test else print_failing_test end end private def print_passing_test ".".green end def print_failing_test end end end
require 'colorize' module Dest class Formatter @@fail_count = 1 def initialize(evald_result) @evald_result = evald_result end def print if @evald_result[:result][0] print_passing_test else print_failing_test @@fail_count += 1 end end private def print_passing_test Kernel.print ".".green end def print_failing_test puts "\n #{@@fail_count}) Test in #{@evald_result[:file_path]} failed on line #{@evald_result[:result][1]}".red + "\n Expected: #{@evald_result[:result][2].cyan} " + "\n To Equal: #{@evald_result[:result][3].to_s.cyan} " + "\n But got: #{@evald_result[:result][4].to_s.cyan} \n" end end end
Fix to identify ifd style based on L2NG system
Junos::Ez::Facts::Keeper.define( :ifd_style ) do |ndev, facts| persona = uses :personality facts[:ifd_style] = case persona when :SWITCH :SWITCH else :CLASSIC end end
Junos::Ez::Facts::Keeper.define( :ifd_style ) do |ndev, facts| persona,sw_style = uses :personality,:switch_style facts[:ifd_style] = case persona when :SWITCH if sw_style == :VLAN_L2NG :CLASSIC else :SWITCH end else :CLASSIC end end
Add gift and gift_text to line_item
class AddGiftAndGiftTexttoSpreeLineItem < ActiveRecord::Migration def change add_column :spree_line_items, :gift, :boolean add_column :spree_line_items, :gift_text, :text end end
Hide other occurrences of the same user from appearing in wrong StudyGroup
class StudyGroupsController < ApplicationController include CommonBehavior before_action :set_group, only: MEMBER_ACTIONS def index @search = StudyGroup.search(params[:q]) @study_groups = @search.result.includes(:consumer).order(:name).paginate(page: params[:page]) authorize! end def show @search = @study_group.users.search(params[:q]) end def edit @search = @study_group.users.search(params[:q]) @members = StudyGroupMembership.where(user: @search.result) end def update myparams = study_group_params myparams[:users] = StudyGroupMembership.find(myparams[:study_group_membership_ids].reject(&:empty?)).map(&:user) myparams.delete(:study_group_membership_ids) update_and_respond(object: @study_group, params: myparams) end def destroy destroy_and_respond(object: @study_group) end def study_group_params params[:study_group].permit(:id, :name, :study_group_membership_ids => []) if params[:study_group].present? end private :study_group_params def set_group @study_group = StudyGroup.find(params[:id]) authorize! end private :set_group def authorize! authorize(@study_groups || @study_group) end private :authorize! end
class StudyGroupsController < ApplicationController include CommonBehavior before_action :set_group, only: MEMBER_ACTIONS def index @search = StudyGroup.search(params[:q]) @study_groups = @search.result.includes(:consumer).order(:name).paginate(page: params[:page]) authorize! end def show @search = @study_group.users.search(params[:q]) end def edit @search = @study_group.users.search(params[:q]) @members = StudyGroupMembership.where(user: @search.result, study_group: @study_group) end def update myparams = study_group_params myparams[:users] = StudyGroupMembership.find(myparams[:study_group_membership_ids].reject(&:empty?)).map(&:user) myparams.delete(:study_group_membership_ids) update_and_respond(object: @study_group, params: myparams) end def destroy destroy_and_respond(object: @study_group) end def study_group_params params[:study_group].permit(:id, :name, :study_group_membership_ids => []) if params[:study_group].present? end private :study_group_params def set_group @study_group = StudyGroup.find(params[:id]) authorize! end private :set_group def authorize! authorize(@study_groups || @study_group) end private :authorize! end
Add development_dependency gem * rspec * pry
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'enchant_encoder/version' Gem::Specification.new do |spec| spec.name = "enchant_encoder" spec.version = EnchantEncoder::VERSION spec.authors = ["mgi166"] spec.email = ["skskoari@gmail.com"] spec.summary = %q{TODO: Write a short summary, because Rubygems requires one.} spec.description = %q{TODO: Write a longer description or delete this line.} spec.homepage = "TODO: Put your gem's website or public repo URL here." spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] if spec.respond_to?(:metadata) spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com' to prevent pushes to rubygems.org, or delete to allow pushes to any server." end spec.add_development_dependency "bundler", "~> 1.9" spec.add_development_dependency "rake", "~> 10.0" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'enchant_encoder/version' Gem::Specification.new do |spec| spec.name = "enchant_encoder" spec.version = EnchantEncoder::VERSION spec.authors = ["mgi166"] spec.email = ["skskoari@gmail.com"] spec.summary = %q{TODO: Write a short summary, because Rubygems requires one.} spec.description = %q{TODO: Write a longer description or delete this line.} spec.homepage = "TODO: Put your gem's website or public repo URL here." spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] if spec.respond_to?(:metadata) spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com' to prevent pushes to rubygems.org, or delete to allow pushes to any server." end spec.add_development_dependency "bundler", "~> 1.9" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec" spec.add_development_dependency "pry" # debug end
Change to remove unnecessary load
# frozen_string_literal: true if ENV['COVERAGE'] || ENV['TRAVIS'] require 'simplecov' require 'coveralls' SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new([ SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter ]) SimpleCov.start do command_name 'spec' add_filter 'spec' end end require 'finite_machine' require 'thwait' require 'rspec-benchmark' RSpec.configure do |config| config.run_all_when_everything_filtered = true config.filter_run :focus config.raise_errors_for_deprecations! config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.disable_monkey_patching! if config.files_to_run.one? config.default_formatter = 'doc' end config.order = :random end
# frozen_string_literal: true if ENV['COVERAGE'] || ENV['TRAVIS'] require 'simplecov' require 'coveralls' SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new([ SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter ]) SimpleCov.start do command_name 'spec' add_filter 'spec' end end require 'finite_machine' require 'rspec-benchmark' RSpec.configure do |config| config.run_all_when_everything_filtered = true config.filter_run :focus config.raise_errors_for_deprecations! config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.disable_monkey_patching! if config.files_to_run.one? config.default_formatter = 'doc' end config.order = :random end
Use local version of rdf-n3, if it exists.
$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $:.unshift File.dirname(__FILE__) require 'rubygems' require 'spec' require 'matchers' require 'bigdecimal' # XXX Remove Me require 'rdf/rdfxml' require 'rdf/ntriples' require 'rdf/spec' require 'rdf/isomorphic' include Matchers module RDF module Isomorphic alias_method :==, :isomorphic_with? end class Graph def to_ntriples RDF::Writer.for(:ntriples).buffer do |writer| self.each_statement do |statement| writer << statement end end end end end Spec::Runner.configure do |config| config.include(RDF::Spec::Matchers) end # Heuristically detect the input stream def detect_format(stream) # Got to look into the file to see if stream.is_a?(IO) || stream.is_a?(StringIO) stream.rewind string = stream.read(1000) stream.rewind else string = stream.to_s end case string when /<\w+:RDF/ then RDF::RDFXML::Reader when /<RDF/ then RDF::RDFXML::Reader when /<html/i then RDF::RDFa::Reader when /@prefix/i then RDF::N3::Reader else RDF::NTriples::Reader end end
$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $:.unshift(File.join(File.dirname(__FILE__), '..', '..', 'rdf-n3', 'lib')) $:.unshift File.dirname(__FILE__) require 'rubygems' require 'spec' require 'matchers' require 'bigdecimal' # XXX Remove Me require 'rdf/rdfxml' require 'rdf/ntriples' require 'rdf/spec' require 'rdf/isomorphic' include Matchers module RDF module Isomorphic alias_method :==, :isomorphic_with? end class Graph def to_ntriples RDF::Writer.for(:ntriples).buffer do |writer| self.each_statement do |statement| writer << statement end end end end end Spec::Runner.configure do |config| config.include(RDF::Spec::Matchers) end # Heuristically detect the input stream def detect_format(stream) # Got to look into the file to see if stream.is_a?(IO) || stream.is_a?(StringIO) stream.rewind string = stream.read(1000) stream.rewind else string = stream.to_s end case string when /<\w+:RDF/ then RDF::RDFXML::Reader when /<RDF/ then RDF::RDFXML::Reader when /<html/i then RDF::RDFa::Reader when /@prefix/i then RDF::N3::Reader else RDF::NTriples::Reader end end
Move debian into ext, not top level
# The tar task for creating a tarball of puppetdb JAR_FILE_V = "puppetdb-#{@version}-standalone.jar" # JAR_FILE the constant is defined in Rakefile # file JAR_FILE do |t| Rake::Task[:uberjar].invoke end namespace :package do desc "Create source tarball" task :tar => [ :package ] end desc "Create a source tar archive" task :package => [ :clobber, JAR_FILE, :template ] do temp = `mktemp -d -t tmpXXXXXX`.strip workdir = File.join(temp, "#{@name}-#{@version}") mkdir_p workdir FileList[ "tasks", "ext", "*.md", JAR_FILE, "documentation", "Rakefile" ].each do |f| cp_pr f, workdir end # Lay down version file for later reading File.open(File.join(workdir,'version'), File::CREAT|File::TRUNC|File::RDWR, 0644) do |f| f.puts @version end mv "#{workdir}/ext/files/debian", workdir cp_pr "puppet", "#{workdir}/ext/master" mkdir_p "pkg" pkg_dir = File.expand_path(File.join(".", "pkg")) sh "cd #{temp}; tar --exclude=.gitignore -zcf #{pkg_dir}/#{@name}-#{@version}.tar.gz #{@name}-#{@version}" rm_rf temp puts puts "Wrote #{`pwd`.strip}/pkg/#{@name}-#{@version}" end
# The tar task for creating a tarball of puppetdb JAR_FILE_V = "puppetdb-#{@version}-standalone.jar" # JAR_FILE the constant is defined in Rakefile # file JAR_FILE do |t| Rake::Task[:uberjar].invoke end namespace :package do desc "Create source tarball" task :tar => [ :package ] end desc "Create a source tar archive" task :package => [ :clobber, JAR_FILE, :template ] do temp = `mktemp -d -t tmpXXXXXX`.strip workdir = File.join(temp, "#{@name}-#{@version}") mkdir_p workdir FileList[ "tasks", "ext", "*.md", JAR_FILE, "documentation", "Rakefile" ].each do |f| cp_pr f, workdir end # Lay down version file for later reading File.open(File.join(workdir,'version'), File::CREAT|File::TRUNC|File::RDWR, 0644) do |f| f.puts @version end mv "#{workdir}/ext/files/debian", "#{workdir}/ext" cp_pr "puppet", "#{workdir}/ext/master" mkdir_p "pkg" pkg_dir = File.expand_path(File.join(".", "pkg")) sh "cd #{temp}; tar --exclude=.gitignore -zcf #{pkg_dir}/#{@name}-#{@version}.tar.gz #{@name}-#{@version}" rm_rf temp puts puts "Wrote #{`pwd`.strip}/pkg/#{@name}-#{@version}" end
Change admin table default sort to be :subject, :asc
if defined?(EffectiveDatatables) module Effective module Datatables class EmailTemplates < Effective::Datatable default_order :id, :desc table_column :id, visible: false table_column :slug table_column :subject table_column :from table_column :cc, sortable: false, visible: false, label: 'CC' table_column :bcc, sortable: false, visible: false, label: 'BCC' table_column :body, sortable: false, visible: false table_column :actions, sortable: false, partial: '/admin/email_templates/actions' def collection Effective::EmailTemplate.all end end end end end
if defined?(EffectiveDatatables) module Effective module Datatables class EmailTemplates < Effective::Datatable default_order :subject, :asc table_column :id, visible: false table_column :slug table_column :subject table_column :from table_column :cc, sortable: false, visible: false, label: 'CC' table_column :bcc, sortable: false, visible: false, label: 'BCC' table_column :body, sortable: false, visible: false table_column :actions, sortable: false, partial: '/admin/email_templates/actions' def collection Effective::EmailTemplate.all end end end end end
Update gemspec > 2.0.0 🎆
# coding: utf-8 # frozen_string_literal: true lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = "jekyll-twitter-plugin" spec.version = "2.0.0.beta" spec.authors = ["Rob Murray"] spec.email = ["robmurray17@gmail.com"] spec.summary = "A Liquid tag plugin for Jekyll that renders Tweets from Twitter API" spec.homepage = "https://github.com/rob-murray/jekyll-twitter-plugin" spec.license = "MIT" spec.required_ruby_version = ">= 2.0.0" spec.files = `git ls-files -z`.split("\x0") spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" spec.add_development_dependency "webmock" spec.add_development_dependency "byebug" if RUBY_VERSION >= "2.0" end
# coding: utf-8 # frozen_string_literal: true lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = "jekyll-twitter-plugin" spec.version = "2.0.0" spec.authors = ["Rob Murray"] spec.email = ["robmurray17@gmail.com"] spec.summary = "A Liquid tag plugin for Jekyll blogging engine that embeds Tweets, Timelines and more from Twitter API." spec.homepage = "https://github.com/rob-murray/jekyll-twitter-plugin" spec.license = "MIT" spec.required_ruby_version = ">= 2.0.0" spec.files = `git ls-files -z`.split("\x0") spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" spec.add_development_dependency "webmock" spec.add_development_dependency "byebug" if RUBY_VERSION >= "2.0" end
Add spec for testing informing of user
require File.expand_path('../../../spec_helper', __FILE__) MODULE_ENTRY_XPATH = "/project/component[@name='ProjectModuleManager']/modules/module" describe "generate task" do describe "with a single project definition" do before do @foo = define "foo" end it "informs the user about generating IPR" do lambda { task('iidea').invoke }.should show_info(/Writing (.+)\/foo\.ipr/) end it "informs the user about generating IML" do lambda { task('iidea').invoke }.should show_info(/Writing (.+)\/foo\.iml/) end end describe "with a subproject" do before do @foo = define "foo" do define 'bar' end end it "informs the user about generating subporoject IML" do lambda { task('iidea').invoke }.should show_info(/Writing (.+)\/bar\/bar\.iml/) end end end
Add specs for hash serialization.
require 'spec_helper' module Crashplan describe Resource do describe '#serialize' do before do Resource.class_eval do attribute :created_at, :from => 'creationDate', :as => DateTime attribute :updated_at, :from => 'modificationDate', :as => DateTime attribute :name end end it 'serializes attributes correctly' do resource = Resource.new(name: 'Test', created_at: DateTime.now(), updated_at: DateTime.now()) resource.serialize.should == { name: 'Test', created_at: 1 } end end end end
require 'spec_helper' module Crashplan describe Resource do describe '#serialize' do before do Resource.class_eval do attribute :created_at, :from => 'creationDate', :as => DateTime attribute :updated_at, :from => 'modificationDate', :as => DateTime attribute :name attribute :permissions end end it 'serializes attributes correctly' do resource = Resource.new( name: 'Test', created_at: DateTime.new(2013,1,1), updated_at: DateTime.new(2013,1,1), permissions: { foo_id: 1, bar: 2 } ) serialized = resource.serialize serialized.should include('name' => 'Test') serialized.should include('creationDate' => '2013-01-01T00:00:00+00:00') serialized.should include('modificationDate' => '2013-01-01T00:00:00+00:00') serialized.should include('permissions') serialized['permissions'].should include('fooId' => 1) serialized['permissions'].should include('bar' => 2) end end end end
Update Etcher version to 1.0.0-beta.14
cask 'etcher' do version '1.0.0-beta.13' sha256 '0a7b9f7b8b2a21478957e2815f430444285736761652f9b3c7f4fbefea7db356' # resin-production-downloads.s3.amazonaws.com was verified as official when first introduced to the cask url "https://resin-production-downloads.s3.amazonaws.com/etcher/#{version}/Etcher-darwin-x64.dmg" name 'Etcher' homepage 'https://www.etcher.io/' license :apache app 'Etcher.app' end
cask 'etcher' do version '1.0.0-beta.14' sha256 '2d28c18b4df262d251f217447a726841397039153d22a3801b74d871d10a6693' # resin-production-downloads.s3.amazonaws.com was verified as official when first introduced to the cask url "https://resin-production-downloads.s3.amazonaws.com/etcher/#{version}/Etcher-darwin-x64.dmg" name 'Etcher' homepage 'https://www.etcher.io/' license :apache app 'Etcher.app' end
Simplify creating online data object
# Notify clients when users go online/offline and how many of them are named class AppearanceChannel < ApplicationCable::Channel def subscribed # Notify clients who are not the current one that someone has come online # Current stats need to be sent to client before `stream_for` to avoid an error send_user_stats :global stream_for :global stream_from "appearance:#{self}" end def unsubscribed send_user_stats :global end # Available for clients to specifically ask for current users online def online send_user_stats self end private def send_user_stats(channel) success channel, :online, current_users_online end def user_names(user_ids) User.where(id: user_ids).select(:name, :id) end # Get various stats about the number of users online. # This gets called a lot so use Redis cached data. def current_users_online total_count = ActionCable.server.connections.count users_count = Redis.current.scard(:users_online) anonymous_count = Redis.current.scard(:anonymous_online) user_ids = Redis.current.srandmember(:users_online, 5) { total_online: total_count, anonymous_online: anonymous_count, users_online: users_count, users: user_names(user_ids) } end end
# Notify clients when users go online/offline and how many of them are named class AppearanceChannel < ApplicationCable::Channel def subscribed # Notify clients who are not the current one that someone has come online # Current stats need to be sent to client before `stream_for` to avoid an error send_user_stats :global stream_for :global stream_from "appearance:#{self}" end def unsubscribed send_user_stats :global end # Available for clients to specifically ask for current users online def online send_user_stats self end private def send_user_stats(channel) success channel, :online, current_users_online end def user_names(user_ids) User.where(id: user_ids).select(:name, :id) end # Get various stats about the number of users online. # This gets called a lot so use Redis cached data. def current_users_online { total_online: ActionCable.server.connections.count, anonymous_online: Redis.current.scard(:anonymous_online), users_online: Redis.current.scard(:users_online), users: user_names(Redis.current.srandmember(:users_online, 5)) } end end
Add Sequel Pro Nightly Build 4293
class SequelProNightly < Cask version '4293' sha256 '8d75ee4c5198de7bfde6a3fb5578812c1dbe13e08f6451dc219f31fc0d3ef722' url 'http://nightly.sequelpro.com/builds/Sequel_Pro_r0c2ea8b95e.dmg' homepage 'http://nightly.sequelpro.com/' link 'Sequel Pro.app' end
Copy locale file on install
module DeviseUserbin module Generators class InstallGenerator < Rails::Generators::Base source_root File.expand_path("../../templates", __FILE__) desc "Add DeviseUserbin config variables to the Devise initializer" argument :api_secret, :desc => "Your Userbin API secret, which can be found on your Userbin dashboard." def add_config_options_to_initializer devise_initializer_path = "config/initializers/devise.rb" if File.exist?(devise_initializer_path) old_content = File.read(devise_initializer_path) if old_content.match(Regexp.new(/^\s*# ==> Configuration for :userbin\n/)) false else inject_into_file(devise_initializer_path, :before => " # ==> Mailer Configuration\n") do <<-CONTENT # ==> Configuration for :userbin config.userbin_api_secret = '#{api_secret}' CONTENT end end end end end end end
module DeviseUserbin module Generators class InstallGenerator < Rails::Generators::Base source_root File.expand_path("../../templates", __FILE__) desc "Add DeviseUserbin config variables to the Devise initializer" argument :api_secret, :desc => "Your Userbin API secret, which can be found on your Userbin dashboard." def add_config_options_to_initializer devise_initializer_path = "config/initializers/devise.rb" if File.exist?(devise_initializer_path) old_content = File.read(devise_initializer_path) if old_content.match(Regexp.new(/^\s*# ==> Configuration for :userbin\n/)) false else inject_into_file(devise_initializer_path, :before => " # ==> Mailer Configuration\n") do <<-CONTENT # ==> Configuration for :userbin config.userbin_api_secret = '#{api_secret}' CONTENT end end end end def copy_locale copy_file "../../../config/locales/en.yml", "config/locales/devise_userbin.en.yml" end end end end
Remove old reference to TrustCommerce
config.cache_classes = true config.whiny_nils = true # Show full error reports and disable caching config.action_controller.consider_all_requests_local = false config.action_controller.perform_caching = true config.action_view.cache_template_loading = true config.action_view.debug_rjs = true config.action_mailer.raise_delivery_errors = true config.action_mailer.delivery_method = :test RAILS_HOST = "localhost:3000" unless defined?(RAILS_HOST) config.after_initialize do ActiveMerchant::Billing::Base.mode = :test ::GATEWAY = ActiveMerchant::Billing::Base.gateway(:trust_commerce).new( :login => "834347", :password => "commerce7" ) end
config.cache_classes = true config.whiny_nils = true # Show full error reports and disable caching config.action_controller.consider_all_requests_local = false config.action_controller.perform_caching = true config.action_view.cache_template_loading = true config.action_view.debug_rjs = true config.action_mailer.raise_delivery_errors = true config.action_mailer.delivery_method = :test RAILS_HOST = "localhost:3000" unless defined?(RAILS_HOST)
Make it easier to test production builds locally
CarrierWave.configure do |config| if EnvironmentBasedUploader.use_fog? config.fog_provider = 'fog/aws' config.fog_credentials = { provider: 'AWS', aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'], aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'], region: ENV['AWS_S3_REGION'] || 'us-east-1' } config.fog_directory = ENV['AWS_S3_BUCKET'] config.asset_host = ENV['UPLOADS_HOST'] if ENV['UPLOADS_HOST'].present? end end
CarrierWave.configure do |config| if EnvironmentBasedUploader.use_fog? missing_keys = %w[AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_S3_BUCKET].select do |required_key| ENV[required_key].blank? end if missing_keys.any? Rails.logger.warn <<~TEXT Missing configuration for S3. The following environment variables are needed but not present: #{missing_keys.join(", ")} TEXT else config.fog_provider = 'fog/aws' config.fog_credentials = { provider: 'AWS', aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'], aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'], region: ENV['AWS_S3_REGION'] || 'us-east-1' } config.fog_directory = ENV['AWS_S3_BUCKET'] config.asset_host = ENV['UPLOADS_HOST'] if ENV['UPLOADS_HOST'].present? end end end
Bump Bash 4.1 patch level to 9
require 'formula' class Bash <Formula url 'http://ftp.gnu.org/gnu/bash/bash-4.1.tar.gz' homepage 'http://www.gnu.org/software/bash/' sha1 '3bd1ec9c66f3689f6b3495bdaaf9077b2e5dc150' version '4.1.7' depends_on 'readline' def patches patch_level = version.split('.').last.to_i {'p0' => (1..patch_level).map { |i| "http://ftp.gnu.org/gnu/bash/bash-4.1-patches/bash41-%03d" % i }} end def install system "./configure", "--prefix=#{prefix}", "--disable-debug", "--disable-dependency-tracking" system "make install" end end
require 'formula' class Bash <Formula url 'http://ftp.gnu.org/gnu/bash/bash-4.1.tar.gz' homepage 'http://www.gnu.org/software/bash/' sha1 '3bd1ec9c66f3689f6b3495bdaaf9077b2e5dc150' version '4.1.9' depends_on 'readline' def patches patch_level = version.split('.').last.to_i {'p0' => (1..patch_level).map { |i| "http://ftp.gnu.org/gnu/bash/bash-4.1-patches/bash41-%03d" % i }} end def install system "./configure", "--prefix=#{prefix}", "--disable-debug", "--disable-dependency-tracking" system "make install" end end
Add new api system to library
require 'spree_core' require 'spree_amazon_fps/engine' require 'amazon/fps/signature_utils'
require 'spree_core' require 'spree_amazon_fps/engine' require 'amazon/fps/signature_utils' require 'amazon/fps/api_call'
Remove no longer existing CachedGemFile Re-alphabetize the autoloads
#:nodoc: module Gemstash autoload :Authorization, "gemstash/authorization" autoload :Cache, "gemstash/cache" autoload :CachedGemFile, "gemstash/storage" autoload :CLI, "gemstash/cli" autoload :Configuration, "gemstash/configuration" autoload :DBHelper, "gemstash/db_helper" autoload :Dependencies, "gemstash/dependencies" autoload :Env, "gemstash/env" autoload :GemPusher, "gemstash/gem_pusher" autoload :GemSource, "gemstash/gem_source" autoload :Logging, "gemstash/logging" autoload :Storage, "gemstash/storage" autoload :LruReduxClient, "gemstash/cache" autoload :NotAuthorizedError, "gemstash/not_authorized_error" autoload :Web, "gemstash/web" autoload :WebError, "gemstash/web_helper" autoload :WebHelper, "gemstash/web_helper" autoload :HTTPClientBuilder, "gemstash/web_helper" autoload :VERSION, "gemstash/version" end
#:nodoc: module Gemstash autoload :Authorization, "gemstash/authorization" autoload :Cache, "gemstash/cache" autoload :CLI, "gemstash/cli" autoload :Configuration, "gemstash/configuration" autoload :DBHelper, "gemstash/db_helper" autoload :Dependencies, "gemstash/dependencies" autoload :Env, "gemstash/env" autoload :GemPusher, "gemstash/gem_pusher" autoload :GemSource, "gemstash/gem_source" autoload :HTTPClientBuilder, "gemstash/web_helper" autoload :Logging, "gemstash/logging" autoload :LruReduxClient, "gemstash/cache" autoload :NotAuthorizedError, "gemstash/not_authorized_error" autoload :Storage, "gemstash/storage" autoload :Web, "gemstash/web" autoload :WebError, "gemstash/web_helper" autoload :WebHelper, "gemstash/web_helper" autoload :VERSION, "gemstash/version" end
Tweak style to please CircleCI
# frozen_string_literal: true SecureHeaders::Configuration.default do |config| normal_src = ["'self'"] if ENV['PUBLIC_HOSTNAME'] fastly_alternate = 'https://' + ENV['PUBLIC_HOSTNAME'] + '.global.ssl.fastly.net' normal_src += [fastly_alternate] end config.hsts = "max-age=#{20.years.to_i}; includeSubDomains; preload" config.x_frame_options = 'DENY' config.x_content_type_options = 'nosniff' config.x_xss_protection = '1; mode=block' config.x_download_options = 'noopen' config.x_permitted_cross_domain_policies = 'none' # Configure CSP config.csp = { default_src: normal_src, img_src: %w(secure.gravatar.com 'self'), object_src: normal_src, style_src: normal_src } # Not using Public Key Pinning Extension for HTTP (HPKP). # Yes, it can counter some attacks, but it can also cause a lot of problems; # one wrong move can render the site useless, and it makes it hard to # switch CAs if the CA behaves badly. end
# frozen_string_literal: true SecureHeaders::Configuration.default do |config| normal_src = ["'self'"] if ENV['PUBLIC_HOSTNAME'] fastly_alternate = 'https://' + ENV['PUBLIC_HOSTNAME'] + '.global.ssl.fastly.net' normal_src += [fastly_alternate] end config.hsts = "max-age=#{20.years.to_i}; includeSubDomains; preload" config.x_frame_options = 'DENY' config.x_content_type_options = 'nosniff' config.x_xss_protection = '1; mode=block' config.x_download_options = 'noopen' config.x_permitted_cross_domain_policies = 'none' # Configure CSP config.csp = { default_src: normal_src, img_src: ['secure.gravatar.com', "'self'"], object_src: normal_src, style_src: normal_src } # Not using Public Key Pinning Extension for HTTP (HPKP). # Yes, it can counter some attacks, but it can also cause a lot of problems; # one wrong move can render the site useless, and it makes it hard to # switch CAs if the CA behaves badly. end
Allow draft content to be tagged
class ContentLookupForm attr_accessor :base_path include ActiveModel::Model validates_presence_of :base_path validate :base_path_should_be_a_content_item def content_id @content_id ||= begin Services.statsd.time "base_path_lookup" do Services.publishing_api.lookup_content_id(base_path: base_path) end end end private def base_path_should_be_a_content_item return if errors.any? strip_host && content_item_should_have_been_found! end def content_item_should_have_been_found! return true if content_id errors[:base_path] << "No page found with this path" false end def strip_host self.base_path = URI.parse(base_path).path rescue URI::InvalidURIError errors[:base_path] << "This is not a valid URL or path" false end end
class ContentLookupForm attr_accessor :base_path include ActiveModel::Model validates_presence_of :base_path validate :base_path_should_be_a_content_item def content_id @content_id ||= begin Services.statsd.time "base_path_lookup" do Services.publishing_api.lookup_content_id(base_path: base_path, with_drafts: true) end end end private def base_path_should_be_a_content_item return if errors.any? strip_host && content_item_should_have_been_found! end def content_item_should_have_been_found! return true if content_id errors[:base_path] << "No page found with this path" false end def strip_host self.base_path = URI.parse(base_path).path rescue URI::InvalidURIError errors[:base_path] << "This is not a valid URL or path" false end end
Add skipped spec defininig special pages
require 'spec_helper' class SpecialPagesIntegrationSpec < AcceptanceSpec describe "viewing the recently_updated page" do it "can be viewed" do skip Page.create(slug: 'index', body: 'Hoo **boy** [link](/link)') visit "/recently_updated" page.must have_text "index" end end end
Set the auto_ids option off for Markdown.
module UsesThis class Site < Salt::Site attr_accessor :wares, :links def setup(path = nil, config = {}) super @paths[:wares] = File.join(@paths[:source], 'data', 'wares') @paths[:links] = File.join(@paths[:source], 'data', 'links') @wares, @links = {}, { personal: [], inspired: [] } end def scan_files super Dir.glob(File.join(@paths[:wares], '**', '*.yml')).each do |path| ware = UsesThis::Ware.new(path) @wares[ware.slug] = ware end Dir.glob(File.join(@paths[:links], '**', '*.yml')).each do |path| link = UsesThis::Link.new(path) @links[link.summary ? :inspired : :personal] << link end @posts.each do |post| post.scan_links end end end end
module UsesThis class Site < Salt::Site attr_accessor :wares, :links def setup(path = nil, config = {}) super @paths[:wares] = File.join(@paths[:source], 'data', 'wares') @paths[:links] = File.join(@paths[:source], 'data', 'links') @wares, @links = {}, { personal: [], inspired: [] } @settings[:markdown_options][:auto_ids] = false end def scan_files super Dir.glob(File.join(@paths[:wares], '**', '*.yml')).each do |path| ware = UsesThis::Ware.new(path) @wares[ware.slug] = ware end Dir.glob(File.join(@paths[:links], '**', '*.yml')).each do |path| link = UsesThis::Link.new(path) @links[link.summary ? :inspired : :personal] << link end @posts.each do |post| post.scan_links end end end end
Add refactored smallest integer solution
# Smallest Integer # I worked on this challenge by myself. # smallest_integer is a method that takes an array of integers as its input # and returns the smallest integer in the array # # +list_of_nums+ is an array of integers # smallest_integer(list_of_nums) should return the smallest integer in +list_of_nums+ # # If +list_of_nums+ is empty the method should return nil # Your Solution Below def smallest_integer(list_of_nums) # Your code goes here! if (list_of_nums.length == 0) return nil else smallest_num = list_of_nums[0] list_of_nums.each do |num| if (num < smallest_num) smallest_num = num end end return smallest_num end end
# Smallest Integer # I worked on this challenge by myself. # smallest_integer is a method that takes an array of integers as its input # and returns the smallest integer in the array # # +list_of_nums+ is an array of integers # smallest_integer(list_of_nums) should return the smallest integer in +list_of_nums+ # # If +list_of_nums+ is empty the method should return nil # Your Solution Below =begin Initial Solution def smallest_integer(list_of_nums) # Your code goes here! if (list_of_nums.length == 0) return nil else smallest_num = list_of_nums[0] list_of_nums.each do |num| if (num < smallest_num) smallest_num = num end end return smallest_num end end =end #Refactored Solution def smallest_integer(list_of_nums) return list_of_nums.sort().slice(0) end
Fix converted strings file format
require "rexml/document" output = "./output.strings" # no input input = ARGV[0] if input.nil? || input.empty? printf("No input file.\n") exit(0) end # check if file is exist file = input if !File.exist?(file) printf("No file exist.\n") exit(0) end dictionary = Hash.new # convert xml doc = REXML::Document.new(File.new(file)) doc.elements.each("resources/string") do |element| dictionary[element.attributes["name"]] = element.text end File.open(output, "w") { |file| file.print("\n") dictionary.each { |key, value| stored_value = value.strip if stored_value.start_with?("\"") && stored_value.end_with?("\"") stored_value = stored_value.slice(1..-1) stored_value = stored_value.chop end file.printf("\"%s\" = \"%s\";\n\n", key, stored_value) } }
require "rexml/document" output = "./output.strings" # no input input = ARGV[0] if input.nil? || input.empty? printf("No input file.\n") exit(0) end # check if file is exist file = input if !File.exist?(file) printf("No file exist.\n") exit(0) end dictionary = Hash.new # convert xml doc = REXML::Document.new(File.new(file)) doc.elements.each("resources/string") do |element| dictionary[element.attributes["name"]] = element.text end File.open(output, "w") { |file| dictionary.each { |key, value| stored_value = value.strip if stored_value.start_with?("\"") && stored_value.end_with?("\"") stored_value = stored_value.slice(1..-1) stored_value = stored_value.chop end file.printf("\"%s\" = \"%s\";\n", key, stored_value) } }
Add to_s for readability of results of specs
module Serverspec module Type class Service def initialize name @name = name end def enabled? backend.check_enabled(nil, @name) end def running? under if under check_method = "check_running_under_#{under}".to_sym unless backend.respond_to?(check_method) raise ArgumentError.new("`be_running` matcher doesn't support #{@under}") end backend.send(check_method, nil, @name) else backend.check_running(nil, @name) end end end end end
module Serverspec module Type class Service def initialize name @name = name end def enabled? backend.check_enabled(nil, @name) end def running? under if under check_method = "check_running_under_#{under}".to_sym unless backend.respond_to?(check_method) raise ArgumentError.new("`be_running` matcher doesn't support #{@under}") end backend.send(check_method, nil, @name) else backend.check_running(nil, @name) end end def to_s "Service #{@name}" end end end end
Remove ancestry from dev gems(1)
$:.push File.expand_path('../lib', __FILE__) # Maintain your gem's version: require 'seo_cms/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = 'seo_cms' s.version = SeoCms::VERSION s.authors = ['Romain Vigo Benia'] s.email = ['romain@livementor.com'] s.homepage = 'http://www.livementor.com' s.summary = 'simple SEO static CMS.' s.description = 'simple SEO static CMS.' s.files = Dir['{app,config,db,lib}/**/*'] + ['MIT-LICENSE', 'Rakefile', 'README.md'] s.test_files = Dir['test/**/*'] s.add_runtime_dependency 'rails', '~> 3.2' s.add_runtime_dependency 'ancestry', '>= 0', '>= 0' s.add_development_dependency 'sqlite3' s.add_development_dependency 'ancestry', '>= 0', '>= 0' # s.add_development_dependency 'test-unit' end
$:.push File.expand_path('../lib', __FILE__) # Maintain your gem's version: require 'seo_cms/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = 'seo_cms' s.version = SeoCms::VERSION s.authors = ['Romain Vigo Benia'] s.email = ['romain@livementor.com'] s.homepage = 'http://www.livementor.com' s.summary = 'simple SEO static CMS.' s.description = 'simple SEO static CMS.' s.files = Dir['{app,config,db,lib}/**/*'] + ['MIT-LICENSE', 'Rakefile', 'README.md'] s.test_files = Dir['test/**/*'] s.add_runtime_dependency 'rails', '~> 3.2' s.add_runtime_dependency 'ancestry', '>= 0', '>= 0' s.add_development_dependency 'sqlite3' # s.add_development_dependency 'ancestry', '>= 0', '>= 0' spec.add_development_dependency 'bundler', '~> 1.7' spec.add_development_dependency 'rake', '~> 10.0' s.add_development_dependency 'test-unit' end
Remove symlinks conflicting with OS X tar
require 'formula' class Star < Formula url 'ftp://ftp.berlios.de/pub/star/star-1.5.1.tar.bz2' homepage 'http://cdrecord.berlios.de/old/private/star.html' md5 'f9a28f83702624c4c08ef1a343014c7a' depends_on "smake" def install system "smake", "GMAKE_NOWARN=true", "INS_BASE=#{prefix}", "MANDIR=share/man" system "smake", "GMAKE_NOWARN=true", "INS_BASE=#{prefix}", "MANDIR=share/man", "install" end end
require 'formula' class Star < Formula url 'ftp://ftp.berlios.de/pub/star/star-1.5.1.tar.bz2' homepage 'http://cdrecord.berlios.de/old/private/star.html' md5 'f9a28f83702624c4c08ef1a343014c7a' depends_on "smake" def install system "smake", "GMAKE_NOWARN=true", "INS_BASE=#{prefix}", "MANDIR=share/man" system "smake", "GMAKE_NOWARN=true", "INS_BASE=#{prefix}", "MANDIR=share/man", "install" # Remove symlinks that override built-in utilities Dir.chdir bin do Pathname.glob(%w[gnutar tar]) {|p| p.unlink} end end end
Add simple test for Secrets object.
# frozen_string_literal: true require_relative "spec_helper" require_relative "../lib/impasta/secrets" require_relative "../lib/impasta/spies/infiltrate" target = Array spy = Impasta.infiltrate target secrets = spy.impasta spec "retains information about the spy" do secrets.target == target || secrets.target end
Make sure the User model has a key
share_examples_for "A property with flags" do before :all do %w[ @property_klass ].each do |ivar| raise "+#{ivar}+ should be defined in before block" unless instance_variable_defined?(ivar) end @flags = [ :one, :two, :three ] class ::User include DataMapper::Resource end @property = User.property :item, @property_klass[@flags] end describe ".generated_classes" do it "should cache the generated class" do @property_klass.generated_classes[@flags].should_not be_nil end end it "should include :flags in accepted_options" do @property_klass.accepted_options.should include(:flags) end it "should respond to :generated_classes" do @property_klass.should respond_to(:generated_classes) end it "should respond to :flag_map" do @property.should respond_to(:flag_map) end it "should be custom" do @property.custom?.should be(true) end end
share_examples_for "A property with flags" do before :all do %w[ @property_klass ].each do |ivar| raise "+#{ivar}+ should be defined in before block" unless instance_variable_defined?(ivar) end @flags = [ :one, :two, :three ] class ::User include DataMapper::Resource end @property = User.property :item, @property_klass[@flags], :key => true end describe ".generated_classes" do it "should cache the generated class" do @property_klass.generated_classes[@flags].should_not be_nil end end it "should include :flags in accepted_options" do @property_klass.accepted_options.should include(:flags) end it "should respond to :generated_classes" do @property_klass.should respond_to(:generated_classes) end it "should respond to :flag_map" do @property.should respond_to(:flag_map) end it "should be custom" do @property.custom?.should be(true) end end
Add class comment for Acfs::Request.
require 'acfs/request/callbacks' module Acfs class Request attr_accessor :body, :format attr_reader :url, :headers, :params, :data include Request::Callbacks def initialize(url, options = {}) @url = URI.parse(url).tap do |url| @data = options.delete(:data) || nil @format = options.delete(:format) || :json @headers = options.delete(:headers) || {} @params = options.delete(:params) || {} url.query = nil # params.any? ? params.to_param : nil end.to_s end def data? !data.nil? end class << self def new(*attrs) return attrs[0] if attrs[0].is_a? self super end end end end
require 'acfs/request/callbacks' module Acfs # Encapsulate all data required to make up a request to the # underlaying http library. # class Request attr_accessor :body, :format attr_reader :url, :headers, :params, :data include Request::Callbacks def initialize(url, options = {}) @url = URI.parse(url).tap do |url| @data = options.delete(:data) || nil @format = options.delete(:format) || :json @headers = options.delete(:headers) || {} @params = options.delete(:params) || {} url.query = nil # params.any? ? params.to_param : nil end.to_s end def data? !data.nil? end class << self def new(*attrs) return attrs[0] if attrs[0].is_a? self super end end end end
Add a Rake task that loads documents from Qiita
require "open-uri" require "json" namespace :data do namespace :load do desc "Load data from Qiita" task :qiita => :environment do tag = "groonga" url = "https://qiita.com/api/v2/items?page=1&per_page=100&query=tag:#{tag}" open(url) do |entries_json| entries = JSON.parse(entries_json.read) entries.each do |entry| Document.create(title: entry["title"], content: entry["body"]) end end end end end
Change mime time to improve readability
require "spec_helper" describe AcceptableModel::DSL do describe "#define" do context "defined model" do before :each do AcceptableModel.define 'artist' end after do AcceptableModel.send :remove_const, :Artist end it "dynamically defines a new class" do expect { AcceptableModel::Artist.new :name => 'Busta Rhymes' }.to_not raise_error Exception end it "exposes the originating models accessors" do model = AcceptableModel::Artist.new :name => 'Busta Rhymes' model.name.should eql 'Busta Rhymes' end end it "can only define if the model is defined" do expect { AcceptableModel.define 'gopher' }.to raise_error AcceptableModel::ModelNotFound end end describe "#mime_types" do before :each do AcceptableModel.define 'artist' end after do AcceptableModel.send :remove_const, :Artist end it "should allow me to define a versioned response" do expect { class AcceptableModel::Artist mime_types ['json'] do |artist| { :id => artist.id, :name => artist.name } end end }.to_not raise_error NoMethodError end it "deprecates #version" do Kernel.should_receive :warn class AcceptableModel::Artist version ['vnd.acme.artist-v3+xml'] do |artist| { :name => artist.name } end end end end end
require "spec_helper" describe AcceptableModel::DSL do describe "#define" do context "defined model" do before :each do AcceptableModel.define 'artist' end after do AcceptableModel.send :remove_const, :Artist end it "dynamically defines a new class" do expect { AcceptableModel::Artist.new :name => 'Busta Rhymes' }.to_not raise_error Exception end it "exposes the originating models accessors" do model = AcceptableModel::Artist.new :name => 'Busta Rhymes' model.name.should eql 'Busta Rhymes' end end it "can only define if the model is defined" do expect { AcceptableModel.define 'gopher' }.to raise_error AcceptableModel::ModelNotFound end end describe "#mime_types" do before :each do AcceptableModel.define 'artist' end after do AcceptableModel.send :remove_const, :Artist end it "should allow me to define a versioned response" do expect { class AcceptableModel::Artist mime_types ['vnd.acme.artist-v3+xml'] do |artist| { :id => artist.id, :name => artist.name } end end }.to_not raise_error NoMethodError end it "deprecates #version" do Kernel.should_receive :warn class AcceptableModel::Artist version ['vnd.acme.artist-v3+xml'] do |artist| { :name => artist.name } end end end end end
Include pry for debug flag
#!/usr/bin/env ruby require_relative 'logger' require_relative 'game' require_relative 'grammar' require_relative 'meanings' require 'optparse' options = { population: 10, iterations: 500, probability: 10, print_grammars: false, } OptionParser.new do |opts| opts.banner = "Usage: learner.rb [options]" opts.on("-p N", "--population N", Integer, "Set population size") do |v| options[:population] = v end opts.on("-i N", "--iterations N", Integer, "Set iterations count") do |v| options[:iterations] = v end opts.on("--probability N", Float, "Set invention probability") do |p| options[:probability] = p end opts.on("-d", "--debug", "Show debug messages") do |debug| if debug MyLogger.level = Logger::DEBUG end end opts.on("--print-grammars", "Print final grammars") do |print_grammars| options[:print_grammars] = true end end.parse! game = Game.new(options) game.play(options[:iterations]) if options[:print_grammars] puts game.grammars end
#!/usr/bin/env ruby require_relative 'logger' require_relative 'game' require_relative 'grammar' require_relative 'meanings' require 'optparse' options = { population: 10, iterations: 500, probability: 10, print_grammars: false, } OptionParser.new do |opts| opts.banner = "Usage: learner.rb [options]" opts.on("-p N", "--population N", Integer, "Set population size") do |v| options[:population] = v end opts.on("-i N", "--iterations N", Integer, "Set iterations count") do |v| options[:iterations] = v end opts.on("--probability N", Float, "Set invention probability") do |p| options[:probability] = p end opts.on("-d", "--debug", "Show debug messages") do |debug| if debug require 'pry' MyLogger.level = Logger::DEBUG end end opts.on("--print-grammars", "Print final grammars") do |print_grammars| options[:print_grammars] = true end end.parse! game = Game.new(options) game.play(options[:iterations]) if options[:print_grammars] puts game.grammars end
Use constant time string comparison to avoid timing attacks.
module Twilio module Util class RequestValidator def initialize(auth_token = nil) @auth_token = auth_token || Twilio.auth_token raise ArgumentError, 'Auth token is required' if @auth_token.nil? end def validate(url, params, signature) expected = build_signature_for url, params expected == signature end def build_signature_for(url, params) data = url + params.sort.join digest = OpenSSL::Digest.new('sha1') Base64.encode64(OpenSSL::HMAC.digest(digest, @auth_token, data)).strip end end end end
module Twilio module Util class RequestValidator def initialize(auth_token = nil) @auth_token = auth_token || Twilio.auth_token raise ArgumentError, 'Auth token is required' if @auth_token.nil? end def validate(url, params, signature) expected = build_signature_for url, params secure_compare(expected, signature) end def build_signature_for(url, params) data = url + params.sort.join digest = OpenSSL::Digest.new('sha1') Base64.encode64(OpenSSL::HMAC.digest(digest, @auth_token, data)).strip end private # Compares two strings in constant time to avoid timing attacks. # Borrowed from ActiveSupport::MessageVerifier. # https://github.com/rails/rails/blob/master/activesupport/lib/active_support/message_verifier.rb def secure_compare(a, b) return false unless a.bytesize == b.bytesize l = a.unpack("C#{a.bytesize}") res = 0 b.each_byte { |byte| res |= byte ^ l.shift } res == 0 end end end end
Make sure stderr sync is also true
require 'vm/development/rake/build_tasks' VmDevelopment::BuildTasks.new STDOUT.sync = true
require 'vm/development/rake/build_tasks' VmDevelopment::BuildTasks.new STDOUT.sync = true STDERR.sync = true
Update migration generation test to use 'ActiveRecord::Migration.current_version'
require 'helper' require 'rails/generators/test_case' require 'active_record/session_store' require 'generators/active_record/session_migration_generator' class SessionMigrationGeneratorTest < Rails::Generators::TestCase tests ActiveRecord::Generators::SessionMigrationGenerator destination 'tmp' setup :prepare_destination def active_record_version "\\[#{ActiveRecord::VERSION::MAJOR}\\.#{ActiveRecord::VERSION::MINOR}\\]" if ActiveRecord::VERSION::MAJOR >= 5 end def test_session_migration_with_default_name run_generator assert_migration "db/migrate/add_sessions_table.rb", /class AddSessionsTable < ActiveRecord::Migration#{active_record_version}/ end def test_session_migration_with_given_name run_generator ["create_session_table"] assert_migration "db/migrate/create_session_table.rb", /class CreateSessionTable < ActiveRecord::Migration#{active_record_version}/ end def test_session_migration_with_custom_table_name ActiveRecord::SessionStore::Session.table_name = "custom_table_name" run_generator assert_migration "db/migrate/add_sessions_table.rb" do |migration| assert_match(/class AddSessionsTable < ActiveRecord::Migration#{active_record_version}/, migration) assert_match(/create_table :custom_table_name/, migration) end ensure ActiveRecord::SessionStore::Session.table_name = "sessions" end end
require 'helper' require 'rails/generators/test_case' require 'active_record/session_store' require 'generators/active_record/session_migration_generator' class SessionMigrationGeneratorTest < Rails::Generators::TestCase tests ActiveRecord::Generators::SessionMigrationGenerator destination 'tmp' setup :prepare_destination def active_record_version "\\[#{ActiveRecord::Migration.current_version}\\]" if ActiveRecord::Migration.respond_to?(:current_version) end def test_session_migration_with_default_name run_generator assert_migration "db/migrate/add_sessions_table.rb", /class AddSessionsTable < ActiveRecord::Migration#{active_record_version}/ end def test_session_migration_with_given_name run_generator ["create_session_table"] assert_migration "db/migrate/create_session_table.rb", /class CreateSessionTable < ActiveRecord::Migration#{active_record_version}/ end def test_session_migration_with_custom_table_name ActiveRecord::SessionStore::Session.table_name = "custom_table_name" run_generator assert_migration "db/migrate/add_sessions_table.rb" do |migration| assert_match(/class AddSessionsTable < ActiveRecord::Migration#{active_record_version}/, migration) assert_match(/create_table :custom_table_name/, migration) end ensure ActiveRecord::SessionStore::Session.table_name = "sessions" end end
Mark Celluloid::TaskThread specs as pending
require 'spec_helper' describe Celluloid::TaskThread do it_behaves_like "a Celluloid Task", Celluloid::TaskThread end
require 'spec_helper' describe Celluloid::TaskThread do #it_behaves_like "a Celluloid Task", Celluloid::TaskThread it "behaves like a Celluloid Task" do pending "deadlocks :(" end end
Add basic tests for Additional Visitor
require 'rails_helper' RSpec.describe AdditionalVisitor do it { is_expected.to belong_to(:visit) } it { is_expected.to validate_presence_of(:visit_id) } it { is_expected.to validate_presence_of(:first_name) } it { is_expected.to validate_presence_of(:last_name) } it { is_expected.to validate_presence_of(:date_of_birth) } end
Use mas cms client gem for debt management campaign page
class DebtManagementController < ApplicationController layout '_unconstrained' COMPANY_LIST_ARTICLE_ID = 'debt-management-companies' private def company_list return @company_list if @company_list @company_list = Core::ArticleReader.new(COMPANY_LIST_ARTICLE_ID).call do not_found end @company_list = ContentItemDecorator.decorate(@company_list) end helper_method :company_list def hide_contact_panels? true end helper_method :hide_contact_panels? end
class DebtManagementController < ApplicationController layout '_unconstrained' COMPANY_LIST_ARTICLE_ID = 'debt-management-companies' private def company_list @company_list ||= ContentItemDecorator.decorate(resource) end helper_method :company_list def hide_contact_panels? true end helper_method :hide_contact_panels? def resource Mas::Cms::Article.find( COMPANY_LIST_ARTICLE_ID, locale: I18n.locale ) end end
Update the URL of logstash jar to download
# # Copyright 2011, Peter Donald # # 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. # default['logstash']['package_url'] = 'http://semicomplete.com/files/logstash/logstash-1.1.0-monolithic.jar' default['logstash']['user'] = 'logstash' default['logstash']['group'] = 'logstash' default['logstash']['listen_ports'] = [] default['logstash']['install_path'] = '/usr/local/logstash' default['logstash']['config_path'] = '/etc/logstash' default['logstash']['log_path'] = '/var/log/logstash'
# # Copyright 2011, Peter Donald # # 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. # default['logstash']['package_url'] = 'http://databits.net/petef/tmp/logstash-1.1.1-pre-monolithic-jruby1.7.0pre1.jar' default['logstash']['user'] = 'logstash' default['logstash']['group'] = 'logstash' default['logstash']['listen_ports'] = [] default['logstash']['install_path'] = '/usr/local/logstash' default['logstash']['config_path'] = '/etc/logstash' default['logstash']['log_path'] = '/var/log/logstash'
Fix undefined method error when visit /user/favorite_courses
class Users::FavoriteCoursesController < ApplicationController include CourseManager before_action :authenticate_user! before_action :redis_state, only: [:show, :export] def show @courses = Course.show_favorite_courses(current_user.favorite_courses).includes(:entries, comments: :replies) end def create append_course(:favorite_courses, params[:favorite_course]) end def destroy delete_course(:favorite_courses, params[:favorite_course]) end def export if current_user.student? && !@state[:queued] && !params[:csys_password].blank? BookmarkingCoursesJob.perform_later(current_user, params[:csys_password]) else if current_user.student? redis_state(message: '工作尚未結束或密碼空白') else redis_state(message: '非學生帳號,請洽管理員') end end end private def redis_state(**args) @state = JSON.parse($job_redis.get(current_user.id) || '{}') @state.merge!(args) $job_redis.set(current_user.id, @state.to_json) end end
class Users::FavoriteCoursesController < ApplicationController include CourseManager before_action :authenticate_user! before_action :redis_state, only: [:show, :export] def show @courses = Course.by_code(current_user.favorite_courses).includes(:entries, comments: :replies) end def create append_course(:favorite_courses, params[:favorite_course]) end def destroy delete_course(:favorite_courses, params[:favorite_course]) end def export if current_user.student? && !@state[:queued] && !params[:csys_password].blank? BookmarkingCoursesJob.perform_later(current_user, params[:csys_password]) else if current_user.student? redis_state(message: '工作尚未結束或密碼空白') else redis_state(message: '非學生帳號,請洽管理員') end end end private def redis_state(**args) @state = JSON.parse($job_redis.get(current_user.id) || '{}') @state.merge!(args) $job_redis.set(current_user.id, @state.to_json) end end
Revert "Uses thread-local variables instead of a global variable for setting the configuration"
require 'logging' require "netvisor/version" require "netvisor/base" require "netvisor/configuration" module Netvisor class << self attr_accessor :configuration, :logger end def self.new Netvisor::Base.new end def self.configure yield(configuration) end def self.configuration init_config if (Thread.current[:netvisor_configuration].nil? || Thread.current[:netvisor_configuration] == 1) Thread.current[:netvisor_configuration] end def self.reset init_config init_logger end def self.init_logger @logger = Logging.logger(STDOUT) @logger.level = configuration.log_level end def self.init_config Thread.current[:netvisor_configuration] = Configuration.new(:sender => 'Netvisor gem', :log_level => :debug) end def self.logger init_logger if (@logger.nil? || @logger == 1) @logger end end
require 'logging' require "netvisor/version" require "netvisor/base" require "netvisor/configuration" module Netvisor class << self attr_accessor :configuration, :logger end def self.new Netvisor::Base.new end def self.configure yield(configuration) end def self.configuration init_config if (@configuration.nil? || @configuration == 1) @configuration end def self.reset init_config init_logger end def self.init_logger @logger = Logging.logger(STDOUT) @logger.level = configuration.log_level end def self.init_config @configuration = Configuration.new(:sender => 'Netvisor gem', :log_level => :debug) end def self.logger init_logger if (@logger.nil? || @logger == 1) @logger end end
Fix bug where Database ignored :impala_mem_limit option
require 'facets/hash/revalue' module ConceptQL class Database attr :db, :opts def initialize(db, opts={}) @db = db db_type = :impala if db db.extension :date_arithmetic db.extension :error_sql db_type = db.database_type.to_sym end @opts = opts.revalue { |v| v ? v.to_sym : v } @opts[:data_model] ||= :omopv4 @opts[:database_type] ||= db_type if db_type == :impala opts = { runtime_filter_mode: "OFF" } if mem_limit = ENV['IMPALA_MEM_LIMIT'] opts.merge!(mem_limit: mem_limit) end db.set(opts) end end def query(statement, opts={}) Query.new(db, statement, @opts.merge(opts)) end end end
require 'facets/hash/revalue' module ConceptQL class Database attr :db, :opts def initialize(db, opts={}) @db = db db_type = :impala if db db.extension :date_arithmetic db.extension :error_sql db_type = db.database_type.to_sym end @opts = opts.revalue { |v| v ? v.to_sym : v } @opts[:data_model] ||= :omopv4 @opts[:database_type] ||= db_type if db_type == :impala db_opts = { runtime_filter_mode: "OFF" } if mem_limit = (@opts[:impala_mem_limit] || ENV['IMPALA_MEM_LIMIT']) db_opts.merge!(mem_limit: mem_limit) end db.set(db_opts) end end def query(statement, opts={}) Query.new(db, statement, @opts.merge(opts)) end end end
Disable app initialization during precompile
# This code is free software; you can redistribute it and/or modify it under # the terms of the new BSD License. # # Copyright (c) 2012, Sebastian Staudt require File.expand_path('../boot', __FILE__) require 'action_controller/railtie' require 'sprockets/railtie' Bundler.require :default, :assets, Rails.env module Braumeister class Application < Rails::Application config.assets.enabled = true config.assets.version = '1.0' config.encoding = "utf-8" def self.tmp_path @@tmp_path ||= File.join Rails.root, 'tmp' end end end
# This code is free software; you can redistribute it and/or modify it under # the terms of the new BSD License. # # Copyright (c) 2012, Sebastian Staudt require File.expand_path('../boot', __FILE__) require 'action_controller/railtie' require 'sprockets/railtie' Bundler.require :default, :assets, Rails.env module Braumeister class Application < Rails::Application config.assets.enabled = true config.assets.initialize_on_precompile = false config.assets.version = '1.0' config.encoding = "utf-8" def self.tmp_path @@tmp_path ||= File.join Rails.root, 'tmp' end end end
Fix dependency error on unsupported super_exception_notifier 3.0.x.
# Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.10' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Specify gems that this application depends on and have them installed with rake gems:install config.gem 'aasm', :version => '2.2.0' config.gem 'authlogic', :version => '2.1.6' config.gem 'super_exception_notifier', :version => '3.0.13', :lib => "exception_notification" config.gem 'json', :version => '1.5.1' if ['development', 'test'].include? RAILS_ENV config.gem 'factory_girl', :version => '1.3.3', :lib => false config.gem 'rspec-rails', :version => '1.3.3', :lib => false end # Libraries require 'digest/md5' # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'UTC' # Load custom libraries before "config/initializers" run. $LOAD_PATH.unshift("#{RAILS_ROOT}/lib") end
# Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.10' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Specify gems that this application depends on and have them installed with rake gems:install config.gem 'aasm', :version => '2.2.0' config.gem 'authlogic', :version => '2.1.6' config.gem 'super_exception_notifier', :version => '~> 2.0.8', :lib => 'exception_notifier' config.gem 'json', :version => '1.5.1' if ['development', 'test'].include? RAILS_ENV config.gem 'factory_girl', :version => '1.3.3', :lib => false config.gem 'rspec-rails', :version => '1.3.3', :lib => false end # Libraries require 'digest/md5' # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'UTC' # Load custom libraries before "config/initializers" run. $LOAD_PATH.unshift("#{RAILS_ROOT}/lib") end
Add a matcher for the settings resource
# # Cookbook:: maven # Library:: default # # Author:: Seth Chisamore (<schisamo@chef.io>) # Author:: Bryan W. Berry (<bryan.berry@gmail.com>) # # Copyright:: 2010-2016, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if defined?(ChefSpec) def install_maven_artifact(resource) ChefSpec::Matchers::ResourceMatcher.new(:maven, :install, resource) end def put_maven_artifact(resource) ChefSpec::Matchers::ResourceMatcher.new(:maven, :put, resource) end end
# # Cookbook:: maven # Library:: default # # Author:: Seth Chisamore (<schisamo@chef.io>) # Author:: Bryan W. Berry (<bryan.berry@gmail.com>) # # Copyright:: 2010-2016, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if defined?(ChefSpec) def install_maven_artifact(resource) ChefSpec::Matchers::ResourceMatcher.new(:maven, :install, resource) end def put_maven_artifact(resource) ChefSpec::Matchers::ResourceMatcher.new(:maven, :put, resource) end def update_maven_settings(resource) ChefSpec::Matchers::ResourceMatcher.new(:maven, :update, resource) end end
Allow instance admin to manage courses
module System::Admin::InstanceAdminAbilityComponent include AbilityHost::Component def define_permissions if user allow_instance_admin_manage_instance allow_instance_admin_manage_instance_users end super end private def allow_instance_admin_manage_instance can :manage, Instance, instance_user_hash(:administrator) end def allow_instance_admin_manage_instance_users can :manage, InstanceUser, instance_all_instance_users_hash(:administrator) end end
module System::Admin::InstanceAdminAbilityComponent include AbilityHost::Component def define_permissions if user allow_instance_admin_manage_instance allow_instance_admin_manage_instance_users allow_instance_admin_manage_courses end super end private def allow_instance_admin_manage_instance can :manage, Instance, instance_user_hash(:administrator) end def allow_instance_admin_manage_instance_users can :manage, InstanceUser, instance_all_instance_users_hash(:administrator) end def allow_instance_admin_manage_courses can :manage, Course, instance_all_instance_users_hash(:administrator) end end
Update homepage to english page
# -*- Ruby -*- Gem::Specification.new do |spec| spec.name = "rubysdl" spec.version = "2.1.3" spec.summary = "The simple ruby extension library to use SDL" spec.description = <<-EOS Ruby/SDL is an extension library to use SDL(Simple DirectMedia Layer). This library enables you to control audio, keyboard, mouse, joystick, 3D hardware via OpenGL, and 2D video framebuffer. Ruby/SDL is used by games and visual demos. EOS spec.rubyforge_project = "rubysdl" spec.author = "Ohbayashi Ippei" spec.email = "ohai@kmc.gr.jp" spec.homepage = "http://www.kmc.gr.jp/~ohai/" spec.files = `git ls-files`.split(/\n/) spec.test_files = [] spec.extensions = ["extconf.rb"] spec.has_rdoc = false end
# -*- Ruby -*- Gem::Specification.new do |spec| spec.name = "rubysdl" spec.version = "2.1.4" spec.summary = "The simple ruby extension library to use SDL" spec.description = <<-EOS Ruby/SDL is an extension library to use SDL(Simple DirectMedia Layer). This library enables you to control audio, keyboard, mouse, joystick, 3D hardware via OpenGL, and 2D video framebuffer. Ruby/SDL is used by games and visual demos. EOS spec.rubyforge_project = "rubysdl" spec.author = "Ohbayashi Ippei" spec.email = "ohai@kmc.gr.jp" spec.homepage = "http://www.kmc.gr.jp/~ohai/rubysdl.en.html" spec.files = `git ls-files`.split(/\n/) spec.test_files = [] spec.extensions = ["extconf.rb"] spec.has_rdoc = false end
Load the new dummy app
# Configure Rails Envinronment ENV["RAILS_ENV"] = "test" require File.expand_path("../../test/dummy/config/environment.rb", __FILE__) require 'rspec/rails' ENGINE_RAILS_ROOT=File.join(File.dirname(__FILE__), '../') # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[File.join(ENGINE_RAILS_ROOT, "spec/support/**/*.rb")].each {|f| require f } RSpec.configure do |config| config.use_transactional_fixtures = true end
# Configure Rails Envinronment ENV["RAILS_ENV"] = "test" require File.expand_path("../dummy/config/environment.rb", __FILE__) require 'rspec/rails' ENGINE_RAILS_ROOT=File.join(File.dirname(__FILE__), '../') # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[File.join(ENGINE_RAILS_ROOT, "spec/support/**/*.rb")].each {|f| require f } RSpec.configure do |config| config.use_transactional_fixtures = true end
Set Confinicky to a module as opposed to class (typo).
class Confinicky module Version MAJOR = 0 MINOR = 1 PATCH = 5 BUILD = '' STRING = [MAJOR, MINOR, PATCH].compact.join('.') end end
module Confinicky module Version MAJOR = 0 MINOR = 1 PATCH = 5 BUILD = '' STRING = [MAJOR, MINOR, PATCH].compact.join('.') end end
Update pod spec file for future use
Pod::Spec.new do |s| s.name = "RSBarcodes_Swift" s.version = "0.0.3" s.summary = "1D and 2D barcodes reader and generators for iOS 7 with delightful controls. Now Swift. " s.homepage = "https://github.com/yeahdongcn/RSBarcodes_Swift" s.license = { :type => 'MIT', :file => 'LICENSE.md' } s.author = { "R0CKSTAR" => "yeahdongcn@gmail.com" } s.platform = :ios, '7.0' s.source = { :git => 'https://github.com/yeahdongcn/RSBarcodes_Swift.git', :tag => "#{s.version}" } s.source_files = 'Classes/*.swift' s.frameworks = ['CoreImage', 'AVFoundation', 'QuartzCore'] s.requires_arc = true end
Pod::Spec.new do |s| s.name = "RSBarcodes_Swift" s.version = "0.0.3" s.summary = "1D and 2D barcodes reader and generators for iOS 7 with delightful controls. Now Swift. " s.homepage = "https://github.com/yeahdongcn/RSBarcodes_Swift" s.license = { :type => 'MIT', :file => 'LICENSE.md' } s.author = { "R0CKSTAR" => "yeahdongcn@gmail.com" } s.platform = :ios, '7.0' s.source = { :git => 'https://github.com/yeahdongcn/RSBarcodes_Swift.git', :tag => "#{s.version}" } s.source_files = 'Source/*.swift' s.frameworks = ['CoreImage', 'AVFoundation', 'QuartzCore'] s.requires_arc = true end
Switch condition from unless to if
class API::V1::RegisterController < Grape::API resource :register do before do redirect '/' unless authenticated? end desc 'GET /api/v1/register/new' params do end get '/new' do end desc 'POST /api/v1/register/' params do requires :name, type: String, desc: 'name' requires :email, type: String, desc: 'email' requires :password, type: String, desc: 'password' requires :password_confirmation, type: String, desc: 'password_confirmation' requires :payload, type: Hash, desc: 'payload' end post '/' do account = Account.create( name: params[:name], email: params[:email], password: params[:password], password_confirmation: params[:password_confirmation], payload: params[:payload] ) authenticate(account) account end end end
class API::V1::RegisterController < Grape::API resource :register do before do redirect '/' if authenticated? end desc 'GET /api/v1/register/new' params do end get '/new' do end desc 'POST /api/v1/register/' params do requires :name, type: String, desc: 'name' requires :email, type: String, desc: 'email' requires :password, type: String, desc: 'password' requires :password_confirmation, type: String, desc: 'password_confirmation' requires :payload, type: Hash, desc: 'payload' end post '/' do account = Account.create( name: params[:name], email: params[:email], password: params[:password], password_confirmation: params[:password_confirmation], payload: params[:payload] ) authenticate(account) account end end end
Remove old grouping code in favor of hardcoded description
class TagsController < ContentController before_action :auto_discovery_feed, only: [:show, :index] layout :theme_layout def index @tags = Tag.page(params[:page]).per(100) @page_title = controller_name.capitalize @keywords = '' @description = "#{self.class.to_s.sub(/Controller$/, '')} for #{this_blog.blog_name}" end def show @tag = Tag.find_by!(name: params[:id]) @page_title = this_blog.tag_title_template.to_title(@tag, this_blog, params) @description = @tag.description.to_s @articles = @tag. articles.includes(:blog, :user, :tags, :resources, :text_filter). published.page(params[:page]).per(10) respond_to do |format| format.html do if @articles.empty? raise ActiveRecord::RecordNotFound else @keywords = this_blog.meta_keywords render template_name(params[:id]) end end format.atom do @articles = @articles[0, this_blog.limit_rss_display] render 'articles/index_atom_feed', layout: false end format.rss do @articles = @articles[0, this_blog.limit_rss_display] render 'articles/index_rss_feed', layout: false end end end private def template_name(value) template_exists?("tags/#{value}") ? value : :show end end
class TagsController < ContentController before_action :auto_discovery_feed, only: [:show, :index] layout :theme_layout def index @tags = Tag.page(params[:page]).per(100) @page_title = controller_name.capitalize @keywords = '' @description = "Tags for #{this_blog.blog_name}" end def show @tag = Tag.find_by!(name: params[:id]) @page_title = this_blog.tag_title_template.to_title(@tag, this_blog, params) @description = @tag.description.to_s @articles = @tag. articles.includes(:blog, :user, :tags, :resources, :text_filter). published.page(params[:page]).per(10) respond_to do |format| format.html do if @articles.empty? raise ActiveRecord::RecordNotFound else @keywords = this_blog.meta_keywords render template_name(params[:id]) end end format.atom do @articles = @articles[0, this_blog.limit_rss_display] render 'articles/index_atom_feed', layout: false end format.rss do @articles = @articles[0, this_blog.limit_rss_display] render 'articles/index_rss_feed', layout: false end end end private def template_name(value) template_exists?("tags/#{value}") ? value : :show end end
Fix for sprockets deprecated method 'find_assets'
class License < ActiveRecord::Base has_many :artifacts def self.license_types License.all.pluck(:license_type).uniq end # TODO: Maybe move this whole code to attributes in the database? def self.type_image type, small=false name = type # All gpls use the same image if name.match(/gpl/) name = 'gpl' end img = "licenses/#{name}#{small ? '-small' : ''}" extension = 'svg' # find the correct image extension ['svg', 'png', 'jpg'].each do |ext| extension = ext if Rails.application.assets.find_asset("#{img}.#{ext}") end # Return full image path "#{img}.#{extension}" end def self.type_name type type end def image_url small=false License.type_image(short_name, small) end # Override find to use the shortname and then try the ID def self.find(id) where(short_name: id).first || super end end
class License < ActiveRecord::Base has_many :artifacts def self.license_types License.all.pluck(:license_type).uniq end # TODO: Maybe move this whole code to attributes in the database? def self.type_image type, small=false name = type # All gpls use the same image if name.match(/gpl/) name = 'gpl' end img = "licenses/#{name}#{small ? '-small' : ''}" extension = 'svg' # find the correct image extension ['svg', 'png', 'jpg'].each do |ext| extension = ext if license_image_present?("#{img}.#{ext}") end # Return full image path "#{img}.#{extension}" end def self.type_name type type end def image_url small=false License.type_image(short_name, small) end # Override find to use the shortname and then try the ID def self.find(id) where(short_name: id).first || super end private def self.license_image_present? filename if Rails.env.production? Rails.application.assets_manifest.assets[filename] else File.exists?(File.join(Rails.root, 'app/assets/images/', filename)) end end end
Move the constant inside of the page feedback to_csv
class PageFeedback < ActiveRecord::Base belongs_to :page, class: Comfy::Cms::Page validates :page, :session_id, presence: true validates :shared_on, inclusion: { in: %w(Facebook Twitter Email) }, allow_blank: true scope :liked, -> (page_id) { where(page: page_id, liked: true) } scope :disliked, -> (page_id) { where(page: page_id, liked: false) } delegate :slug, to: :page, prefix: true CSV_COLUMNS = ['page_slug', column_names].flatten def self.to_csv(_ = {}) CSV.generate do |csv| csv << CSV_COLUMNS find_each do |page_feedback| csv << CSV_COLUMNS.map { |column| page_feedback.send(column) } end end end end
class PageFeedback < ActiveRecord::Base belongs_to :page, class: Comfy::Cms::Page validates :page, :session_id, presence: true validates :shared_on, inclusion: { in: %w(Facebook Twitter Email) }, allow_blank: true scope :liked, -> (page_id) { where(page: page_id, liked: true) } scope :disliked, -> (page_id) { where(page: page_id, liked: false) } delegate :slug, to: :page, prefix: true def self.to_csv(_ = {}) csv_columns = ['page_slug', column_names].flatten CSV.generate do |csv| csv << csv_columns find_each do |page_feedback| csv << csv_columns.map { |column| page_feedback.send(column) } end end end end
Use 10 loops instead of 25 by default.
require 'colorize' require 'json' require 'net/http' require 'uri' require 'capybara' require 'wbench/version' require 'wbench/benchmark' require 'wbench/results' require 'wbench/timing_hash' require 'wbench/row_formatter' require 'wbench/timings/app' require 'wbench/timings/browser' module WBench CAPYBARA_DRIVER = :wbench_browser DEFAULT_LOOPS = 25 Capybara.register_driver(CAPYBARA_DRIVER) do |app| Capybara::Selenium::Driver.new(app, :browser => :chrome) end end
require 'colorize' require 'json' require 'net/http' require 'uri' require 'capybara' require 'wbench/version' require 'wbench/benchmark' require 'wbench/results' require 'wbench/timing_hash' require 'wbench/row_formatter' require 'wbench/timings/app' require 'wbench/timings/browser' module WBench CAPYBARA_DRIVER = :wbench_browser DEFAULT_LOOPS = 10 Capybara.register_driver(CAPYBARA_DRIVER) do |app| Capybara::Selenium::Driver.new(app, :browser => :chrome) end end
Add missing autoload :Instance for Payload::Unhandled
# Namespace for {Metasploit::Cache::Payload::Unhandled::Class class metadata} that is generated from one payload # {Metasploit::Cache::Direct::Class#ancestor ancestor's Metasploit Module}. module Metasploit::Cache::Payload::Unhandled extend ActiveSupport::Autoload autoload :Class end
# Namespace for {Metasploit::Cache::Payload::Unhandled::Class class metadata} that is generated from one payload # {Metasploit::Cache::Direct::Class#ancestor ancestor's Metasploit Module}. module Metasploit::Cache::Payload::Unhandled extend ActiveSupport::Autoload autoload :Class autoload :Instance end
Increase capybara wait time to 10s for locating .chat-input.
require 'spec_helper' describe "Login" do before do @user = FactoryGirl.create(:user, :password => "mypassword") @channel = FactoryGirl.create(:channel, :name => "Cool") end it "shows the login form when visiting the site", js: true do visit root_path page.should have_content("Sign In") end it "allows someone to log in and chat", js: true do visit root_path fill_in "Username", :with => @user.username fill_in "Password", :with => "mypassword" click_button "Sign in" page.should have_content(@user.first_name) page.should have_content(@user.last_name) expect(page).to have_css('.chat-input') chat_input = find(:css, ".chat-input") chat_input.set "Hello there" click_button "Post" within("#channel-activities-1") do page.should have_content("Hello there") end chat_input.set "Hi again" click_button "Post" within("#channel-activities-1") do page.should have_content("Hi again") end end end
require 'spec_helper' describe "Login" do before do @user = FactoryGirl.create(:user, :password => "mypassword") @channel = FactoryGirl.create(:channel, :name => "Cool") end it "shows the login form when visiting the site", js: true do visit root_path page.should have_content("Sign In") end it "allows someone to log in and chat", js: true do visit root_path fill_in "Username", :with => @user.username fill_in "Password", :with => "mypassword" click_button "Sign in" page.should have_content(@user.first_name) page.should have_content(@user.last_name) using_wait_time(10) do expect(page).to have_css('.chat-input') end chat_input = find(:css, ".chat-input") chat_input.set "Hello there" click_button "Post" within("#channel-activities-1") do page.should have_content("Hello there") end chat_input.set "Hi again" click_button "Post" within("#channel-activities-1") do page.should have_content("Hi again") end end end
Add Spec for Ability Model
require 'spec_helper' require 'cancan' require 'cancan/matchers' require_relative '../../app/models/ability.rb' describe Ability do let(:user) { FactoryGirl.create :user } let(:ability) { Ability.new user } describe "Club" do let(:owned_club) { FactoryGirl.create :club, :user_id => user.id } let(:non_owned_club) { FactoryGirl.create :club } context "update" do it "succeeds when the user owns the club" do ability.should be_able_to(:update, owned_club) end it "fails when the user does not own the club" do ability.should_not be_able_to(:update, non_owned_club) end end end describe "Course" do let(:club) { FactoryGirl.create :club, :user_id => user.id } let(:owned_course) { FactoryGirl.create :course, :club_id => club.id } let(:non_owned_course) { FactoryGirl.create :course } context "create" do it "succeeds when the user owns the corresponding club" do ability.should be_able_to(:create, owned_course) end it "fails when the user does not own the corresponding club" do ability.should_not be_able_to(:create, non_owned_course) end end context "edit" do it "succeeds when the user owns the corresponding club" do ability.should be_able_to(:edit, owned_course) end it "fails when the user does not own the corresponding club" do ability.should_not be_able_to(:edit, non_owned_course) end end context "update" do it "succeeds when the user owns the corresponding club" do ability.should be_able_to(:update, owned_course) end it "fails when the user does not own the corresponding club" do ability.should_not be_able_to(:update, non_owned_course) end end end describe "Lesson" do let(:club) { FactoryGirl.create :club, :user_id => user.id } let(:course) { FactoryGirl.create :course, :club_id => club.id } let(:owned_lesson) { FactoryGirl.create :lesson, :course_id => course.id } let(:non_owned_lesson) { FactoryGirl.create :course } context "create" do it "succeeds when the user owns the corresponding club" do ability.should be_able_to(:create, owned_lesson) end it "fails when the user does not own the corresponding club" do ability.should_not be_able_to(:create, non_owned_lesson) end end end end
Configure Airbrake via ENV vars
# This file is overwritten on deploy # Airbrake.configure do |config| # Adding production to the development environments causes Airbrake not # to attempt to send notifications. config.development_environments << "production" config.params_filters += ["current_password", "password-strength-score"] end
Airbrake.configure do |config| if ENV.has_key?("ERRBIT_API_KEY") config.api_key = ENV["ERRBIT_API_KEY"] config.host = "errbit.#{ENV['GOVUK_APP_DOMAIN']}" config.secure = true config.environment_name = ENV["ERRBIT_ENVIRONMENT_NAME"] else # Adding production to the development environments causes Airbrake not # to attempt to send notifications. config.development_environments << "production" end config.params_filters += ["current_password", "password-strength-score"] end
Add summary to gemspec file.
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'currency_finance_ua/version' Gem::Specification.new do |spec| spec.name = "currency_finance_ua" spec.version = CurrencyFinanceUA::VERSION spec.authors = ["ruslanpa"] spec.email = ["ruslan.pavlutskiy@gmail.com"] spec.description = %q{It's a simple wrapper under <http://content.finance.ua/ru/xml/currency-cash>} spec.homepage = "https://github.com/ruslanpa/currency_finance_ua" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.5" spec.add_development_dependency "rake" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'currency_finance_ua/version' Gem::Specification.new do |spec| spec.name = "currency_finance_ua" spec.version = CurrencyFinanceUA::VERSION spec.authors = ["ruslanpa"] spec.email = ["ruslan.pavlutskiy@gmail.com"] spec.description = %q{It's a simple wrapper under <http://content.finance.ua/ru/xml/currency-cash>} spec.summary = %q{It's a simple wrapper under <http://content.finance.ua/ru/xml/currency-cash>} spec.homepage = "https://github.com/ruslanpa/currency_finance_ua" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.5" spec.add_development_dependency "rake" end
Add minitest and guard-minitest gems.
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'jekyll/invoice/version' Gem::Specification.new do |spec| spec.name = "jekyll-invoice" spec.version = Jekyll::Invoice::VERSION spec.authors = ['Mark H. Wilkinson'] spec.email = ['mhw@dangerous-techniques.com'] spec.summary = %q{Produce invoices with Jekyll} spec.description = %q{Plugins for Jekyll to produce nice HTML invoices.} spec.homepage = '' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '~> 1.5' spec.add_development_dependency 'rake' end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'jekyll/invoice/version' Gem::Specification.new do |spec| spec.name = "jekyll-invoice" spec.version = Jekyll::Invoice::VERSION spec.authors = ['Mark H. Wilkinson'] spec.email = ['mhw@dangerous-techniques.com'] spec.summary = %q{Produce invoices with Jekyll} spec.description = %q{Plugins for Jekyll to produce nice HTML invoices.} spec.homepage = '' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '~> 1.5' spec.add_development_dependency 'rake' spec.add_development_dependency 'minitest', '~> 5.0' spec.add_development_dependency 'guard-minitest' end
Use the default admin set constant
namespace :hyrax do namespace :migrate do task move_all_works_to_admin_set: :environment do require 'hyrax/move_all_works_to_admin_set' MoveAllWorksToAdminSet.run(AdminSet.find(Hyrax::DefaultAdminSetActor::DEFAULT_ID)) end end end
namespace :hyrax do namespace :migrate do task move_all_works_to_admin_set: :environment do require 'hyrax/move_all_works_to_admin_set' MoveAllWorksToAdminSet.run(AdminSet.find(AdminSet::DEFAULT_ID)) end end end
Read latest version from LATEST_RELEASE file
require 'nokogiri' require 'open-uri' module Chromedriver class Helper class GoogleCodeParser BUCKET_URL = 'https://chromedriver.storage.googleapis.com' attr_reader :source, :platform def initialize(platform, open_uri_provider=OpenURI) @platform = platform @source = open_uri_provider.open_uri(BUCKET_URL) end def downloads @downloads ||= begin doc = Nokogiri::XML.parse(source) items = doc.css("Contents Key").collect {|k| k.text } items.reject! {|k| !(/chromedriver_#{platform}/===k) } items.map {|k| "#{BUCKET_URL}/#{k}"} end end def newest_download_version @newest_download_version ||= downloads.map { |download| version_of(download) }.max end def version_download_url(version) gem_version = Gem::Version.new(version) downloads.find { |download_url| version_of(download_url) == gem_version } end private def version_of url Gem::Version.new grab_version_string_from(url) end def grab_version_string_from url # assumes url is of form similar to http://chromedriver.storage.googleapis.com/2.3/chromedriver_mac32.zip url.split("/")[3] end end end end
require 'nokogiri' require 'open-uri' require 'uri' module Chromedriver class Helper class GoogleCodeParser BUCKET_URL = 'https://chromedriver.storage.googleapis.com' attr_reader :source, :platform, :newest_download_version def initialize(platform, open_uri_provider=OpenURI) @platform = platform @source = open_uri_provider.open_uri(BUCKET_URL) @newest_download_version = open_uri_provider.open_uri(URI.join(BUCKET_URL, 'LATEST_RELEASE')).read end def downloads @downloads ||= begin doc = Nokogiri::XML.parse(source) items = doc.css("Contents Key").collect {|k| k.text } items.reject! {|k| !(/chromedriver_#{platform}/===k) } items.map {|k| "#{BUCKET_URL}/#{k}"} end end def version_download_url(version) gem_version = Gem::Version.new(version) downloads.find { |download_url| version_of(download_url) == gem_version } end private def version_of url Gem::Version.new grab_version_string_from(url) end def grab_version_string_from url # assumes url is of form similar to http://chromedriver.storage.googleapis.com/2.3/chromedriver_mac32.zip url.split("/")[3] end end end end
Define facts in init spec test
require 'spec_helper' describe 'patchwork' do context 'with defaults for all parameters' do it { should contain_class('patchwork') } end end
require 'spec_helper' describe 'patchwork', :type => 'class' do context 'with defaults for all parameters' do let (:facts) do { :osfamily => 'RedHat', :operatingsystem => 'CentOS', } end it { should contain_class('patchwork') } it { should contain_package('git').with_ensure('installed') } it do should contain_vcsrepo('/opt/patchwork').with( 'ensure' => 'present', 'provider' => 'git', 'source' => 'git://github.com/getpatchwork/patchwork', ) end end end
Allow mentions to be filtered by mentionable
class MentionSerializer include TalkSerializer all_attributes can_include :comment can_filter_by :section can_sort_by :created_at self.default_sort = '-created_at' end
class MentionSerializer include TalkSerializer all_attributes can_include :comment can_filter_by :section, :mentionable_id, :mentionable_type can_sort_by :created_at self.default_sort = '-created_at' end
Remove www from homepage url for Anypass.
class Anypass < Cask url 'http://icyblaze.com/anypass/anypass_mac_1.0.zip' homepage 'http://www.icyblaze.com/anypass' version '1.0.0' sha256 '364d108736eddfdb6e7db56430806d790b79e9f8561aedc544fc78d7e41bac54' link 'Anypass.app' end
class Anypass < Cask url 'http://icyblaze.com/anypass/anypass_mac_1.0.zip' homepage 'http://icyblaze.com/anypass' version '1.0.0' sha256 '364d108736eddfdb6e7db56430806d790b79e9f8561aedc544fc78d7e41bac54' link 'Anypass.app' end
Add cask for Textual 2.1.1
class Textual < Cask url 'http://www.codeux.com/textual/private/downloads/builds/Textual_Demo_12536.zip' homepage 'http://www.codeux.com/textual/' version '2.1.1' sha1 'af057d11e3578afa3b80f4f26093978389982ca2' end
Update podspec to be multi-platform
Pod::Spec.new do |s| s.name = "EDSemver" s.version = "0.2.2" s.summary = "Semantic versioning for Objective-C." s.homepage = "https://github.com/thisandagain/semver" s.license = "MIT" s.authors = { "Andrew Sliwinski" => "andrewsliwinski@acm.org", "Sam Soffes" => "sam@soff.es" } s.source = { :git => "https://github.com/thisandagain/semver.git", :tag => "v0.2.2" } s.platform = :ios, '5.0' s.source_files = 'EDSemver' s.requires_arc = true end
Pod::Spec.new do |s| s.name = "EDSemver" s.version = "0.2.2" s.summary = "Semantic versioning for Objective-C." s.homepage = "https://github.com/thisandagain/semver" s.license = "MIT" s.authors = { "Andrew Sliwinski" => "andrewsliwinski@acm.org", "Sam Soffes" => "sam@soff.es" } s.source = { :git => "https://github.com/thisandagain/semver.git", :tag => "v0.2.2" } s.ios.deployment_target = '5.0' s.osx.deployment_target = '10.8' s.source_files = 'EDSemver' s.requires_arc = true end
Use proxy settings from Chef configs
define :cygwin_package, :action => "install" do ## FIXME: add support for uninstall, upgrades, etc. if node['cygwin']['proxy'].nil? proxycmd = "" else proxycmd = "--proxy #{node['cygwin']['proxy']}" end execute "setup-cygwin-packages.exe" do # FIXME: how do we do this idempotently? #not_if {File.exists?("/etc/passwd")} not_if { `cygcheck -c #{params[:name]}`.include? "OK" } cwd node['cygwin']['download_path'] command "setup.exe -q -O -R #{node['cygwin']['home']} -s #{node['cygwin']['site']} #{proxycmd} -P #{params[:name]}" action :run end end
define :cygwin_package, :action => "install" do ## FIXME: add support for uninstall, upgrades, etc. # FIXME: we should ditch this parameter and just use Chef's if Chef::Config.has_key? :http_proxy proxycmd = "--proxy #{node['cygwin']['proxy']}" else proxycmd = "" end log("Looking at cygwin package #{params[:name]}") execute "setup-cygwin-packages.exe" do # FIXME: how do we do this idempotently? #not_if {File.exists?("/etc/passwd")} not_if { `#{node['cygwin']['home']}/bin/cygcheck -c #{params[:name]}`.include? "OK" } cwd node['cygwin']['download_path'] command "setup.exe -q -O -R #{node['cygwin']['home']} -s #{node['cygwin']['site']} #{proxycmd} -P #{params[:name]}" action :run end end
Convert all images to jpegs on upload for consistency and less risk of complexity down the line when adding new image manipulation.
class Drawing < ActiveRecord::Base enum status: %i(pending complete) enum gender: %i(not_specified female male other) validates :image, presence: true validates :status, presence: true with_options if: :complete? do |complete| complete.validates :description, presence: true complete.validates :subject_matter, presence: true complete.validates :mood_rating, presence: true complete.validates :country, presence: true end validates :age, numericality: { only_integer: true }, allow_nil: true validates :mood_rating, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 10 }, allow_nil: true has_attached_file :image, styles: { medium: "640x", thumb: "100x100#" } validates_attachment_content_type :image, content_type: %r{\Aimage\/(jpeg|png|gif|tiff|bmp)\z}, message: "Accepted image formats are: jpg/jpeg, png, tiff, gif, bmp" belongs_to :user scope :desc, -> { order("drawings.created_at DESC") } def viewer_can_change?(viewer) viewer.organisation == user.organisation end end
class Drawing < ActiveRecord::Base enum status: %i(pending complete) enum gender: %i(not_specified female male other) validates :image, presence: true validates :status, presence: true with_options if: :complete? do |complete| complete.validates :description, presence: true complete.validates :subject_matter, presence: true complete.validates :mood_rating, presence: true complete.validates :country, presence: true end validates :age, numericality: { only_integer: true }, allow_nil: true validates :mood_rating, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 10 }, allow_nil: true has_attached_file :image, styles: { medium: ["640x", :jpg], thumb: ["100x100#", :jpg], original: ["100%", :jpg] } validates_attachment_content_type :image, content_type: %r{\Aimage\/(jpeg|png|gif|tiff|bmp)\z}, message: "Accepted image formats are: jpg/jpeg, png, tiff, gif, bmp" belongs_to :user scope :desc, -> { order("drawings.created_at DESC") } def viewer_can_change?(viewer) viewer.organisation == user.organisation end end
Add first notebook creation and redirection after user logs in.
# Mixed pages for users that are not logged in (including welcome page, contact, help etc.) class PagesController < ApplicationController def index if user_signed_in? @notebooks = current_user.notebooks render "index_logged_in", layout: "logged_in" end end end
# Mixed pages for users that are not logged in (including welcome page, contact, help etc.) class PagesController < ApplicationController def index if user_signed_in? @notebooks = current_user.notebooks if @notebooks.size == 0 notebook = Notebook.new(name: "First Notebook", user: current_user) notebook.save @notebooks.reload end redirect_to notebook_path(@notebooks.first) #render "index_logged_in", layout: "logged_in" end end end
Create private method that gathers all of the required/permitted parameters for the user form
class UsersController < ApplicationController def new @user = User.new end def create end end
class UsersController < ApplicationController def new @user = User.new end def create end private def user_params params.require(:user).permit(:username, :email, :password) end end
Transform hash correctly for ruby 2.0
require 'json' require 'oakdex/pokedex/type' require 'oakdex/pokedex/nature' module Oakdex # Class that handles Pokedex Requests module Pokedex class << self def types @types ||= map_json_data('type', Type) end def find_type(name) types[name] end def natures @natures ||= map_json_data('nature', Nature) end def find_nature(name) natures[name] end private def map_json_data(type, klass) Dir["data/#{type}/*.json"].map do |file_name| data = JSON.parse(File.read(file_name)) [data['names']['en'], klass.new(data)] end.to_h end end end end
require 'json' require 'oakdex/pokedex/type' require 'oakdex/pokedex/nature' module Oakdex # Class that handles Pokedex Requests module Pokedex class << self def types @types ||= map_json_data('type', Type) end def find_type(name) types[name] end def natures @natures ||= map_json_data('nature', Nature) end def find_nature(name) natures[name] end private def map_json_data(type, klass) Hash[Dir["data/#{type}/*.json"].map do |file_name| data = JSON.parse(File.read(file_name)) [data['names']['en'], klass.new(data)] end] end end end end
Remove JS_URL and CSS_URL constants
require 'administrate/field/base' require 'leaflet-rails' require 'rails' module Administrate module Field class LatLng < Base class Engine < ::Rails::Engine config.assets.precompile << %w(lat_lng.js lat_lng.css) if config.respond_to? :assets if defined?(Administrate::Engine) Administrate::Engine.add_javascript 'lat_lng.js' Administrate::Engine.add_stylesheet 'lat_lng.css' end end JS_URL = "//cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.js" CSS_URL = "//cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css" # True if the :lat option has been provided, or field is called :lat def lat? options.fetch(:lat, attribute == :lat) end # True if the :lng option has been provided, or field is called :lng def lng? options.fetch(:lng, attribute == :lng) end # Returns :lat or :lng depending on which type this is def which lat? ? :lat : :lng end # Returns the initial co-ordinates of blank maps (defaults to Leeds, UK) def initial options.fetch(:initial, [53.8003,-1.5519]) end # Returns the initial zoom level for maps (defaults to 11) def zoom options.fetch(:zoom, 11) end def to_s data end end end end
require 'administrate/field/base' require 'leaflet-rails' require 'rails' module Administrate module Field class LatLng < Base class Engine < ::Rails::Engine config.assets.precompile << %w(lat_lng.js lat_lng.css) if config.respond_to? :assets if defined?(Administrate::Engine) Administrate::Engine.add_javascript 'lat_lng.js' Administrate::Engine.add_stylesheet 'lat_lng.css' end end # True if the :lat option has been provided, or field is called :lat def lat? options.fetch(:lat, attribute == :lat) end # True if the :lng option has been provided, or field is called :lng def lng? options.fetch(:lng, attribute == :lng) end # Returns :lat or :lng depending on which type this is def which lat? ? :lat : :lng end # Returns the initial co-ordinates of blank maps (defaults to Leeds, UK) def initial options.fetch(:initial, [53.8003,-1.5519]) end # Returns the initial zoom level for maps (defaults to 11) def zoom options.fetch(:zoom, 11) end def to_s data end end end end
Fix mismatch between client and server variants (ordering issue)
object @product attributes :id, :name, :price, :variant_unit, :variant_unit_scale, :variant_unit_name, :on_demand # Infinity is not a valid JSON object, but Rails encodes it anyway node( :on_hand ) { |p| p.on_hand.to_f.finite? ? p.on_hand : "On demand" } node( :available_on ) { |p| p.available_on.blank? ? "" : p.available_on.strftime("%F %T") } node( :permalink_live ) { |p| p.permalink } node( :supplier ) do |p| partial 'spree/api/enterprises/bulk_show', :object => p.supplier end node( :variants ) do |p| partial 'spree/api/variants/bulk_index', :object => p.variants.order('id ASC') end node( :master ) do |p| partial 'spree/api/variants/bulk_show', :object => p.master end
object @product attributes :id, :name, :price, :variant_unit, :variant_unit_scale, :variant_unit_name, :on_demand # Infinity is not a valid JSON object, but Rails encodes it anyway node( :on_hand ) { |p| p.on_hand.to_f.finite? ? p.on_hand : "On demand" } node( :available_on ) { |p| p.available_on.blank? ? "" : p.available_on.strftime("%F %T") } node( :permalink_live ) { |p| p.permalink } node( :supplier ) do |p| partial 'spree/api/enterprises/bulk_show', :object => p.supplier end node( :variants ) do |p| partial 'spree/api/variants/bulk_index', :object => p.variants.reorder('spree_variants.id ASC') end node( :master ) do |p| partial 'spree/api/variants/bulk_show', :object => p.master end
Add a test for DateTime to Time conversion
require "helper" class DatetimeConversionTest < IntegrityTest setup do assert !Object.const_defined?(:ActiveSupport), 'activesupport should not be loaded' end it 'converts DateTime.now to Time' do dt = DateTime.now time = Integrity.datetime_to_time(dt) assert time.is_a?(Time) end it 'converts DateTime with 0 offset to Time' do dt = DateTime.now dt = dt.new_offset(0) assert_equal 0, dt.offset time = Integrity.datetime_to_time(dt) assert time.is_a?(Time) end it 'converts DateTime with non-0 offset to Time' do dt = DateTime.now dt = dt.new_offset(Rational(-5, 24)) assert_equal Rational(-5, 24), dt.offset time = Integrity.datetime_to_time(dt) assert time.is_a?(Time) end end
Add condition to mx_indices table
class CreateMxIndices < ActiveRecord::Migration def change create_table :mx_indices do |t| t.timestamps t.integer :table_id, null: false t.string :name, null: false t.boolean :unique, null: false, default: false end add_index :mx_indices, [:table_id, :name], unique: true, name: 'mx_indices_uk1' end end
class CreateMxIndices < ActiveRecord::Migration def change create_table :mx_indices do |t| t.timestamps t.integer :table_id, null: false t.string :name, null: false t.boolean :unique, null: false, default: false t.string :condition end add_index :mx_indices, [:table_id, :name], unique: true, name: 'mx_indices_uk1' end end
Remove dependent destroy on page-tag
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable devise :omniauthable has_and_belongs_to_many :roles has_many :pages, dependent: :destroy has_many :tags, through: :pages, dependent: :destroy has_many :follower_tag_relationships, foreign_key: "follower_id", dependent: :destroy has_many :followed_tags, through: :follower_tag_relationships, source: :tag , dependent: :destroy def role?(role) return !!self.roles.find_by_name(role.to_s) end def make_admin self.roles << Role.admin end def revoke_admin self.roles.delete(Role.admin) end def admin? role?(:admin) end def self.find_for_facebook_oauth(access_token, signed_in_resource=nil) data = access_token['info'] if user = User.find_by_email(data["email"]) user else # Create a user with a stub password. User.create!(:email => data["email"], :password => Devise.friendly_token[0,20], :name => data[:name]) end end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable devise :omniauthable has_and_belongs_to_many :roles has_many :pages, dependent: :destroy has_many :tags, through: :page has_many :follower_tag_relationships, foreign_key: "follower_id", dependent: :destroy has_many :followed_tags, through: :follower_tag_relationships, source: :tag , dependent: :destroy def role?(role) return !!self.roles.find_by_name(role.to_s) end def make_admin self.roles << Role.admin end def revoke_admin self.roles.delete(Role.admin) end def admin? role?(:admin) end def self.find_for_facebook_oauth(access_token, signed_in_resource=nil) data = access_token['info'] if user = User.find_by_email(data["email"]) user else # Create a user with a stub password. User.create!(:email => data["email"], :password => Devise.friendly_token[0,20], :name => data[:name]) end end end
Add helper to include closure base.js when calcdeps.py is not used.
module GoogleClosureHelper def closure_include_tag(file_path) out = '' unless ActionController::Base.perform_caching closure_base_path = File.join(GoogleClosureCompiler.closure_library_path, 'goog') out << "<script src='#{File.join('/javascripts', closure_base_path, 'base.js')}' type='text/javascript'></script>" end out << javascript_include_tag(file_path, :cache => "cache/closure/#{file_path.delete('.js')}") out end end
Add AndroidDockerImage class for generating tags from yaml file
class AndroidDockerImage attr_reader :repo, :build_tools, :target_api PLACEHOLDER_BUILD_TOOLS = "%{build_tools}" PLACEHOLDER_TARGET_API = "%{target_api}" def initialize(repo:, build_tools:, target_api:, tag_format:) @repo = repo @build_tools = build_tools @target_api = target_api @tag_format = tag_format end def tag @tag_format .gsub(PLACEHOLDER_BUILD_TOOLS, build_tools) .gsub(PLACEHOLDER_TARGET_API, target_api) end def fullname "#{repo}:#{tag}" end class << self KEY_BUILD_TOOLS = "build-tools" KEY_TARGET_API = "target-api" KEY_REPO = "repo" KEY_TAG_FORMAT = "tag" def load(opts = { build_tools: [], target_api: [] }) repo = opts[KEY_REPO] tag_format = opts[KEY_TAG_FORMAT] patterns(opts).map do |(build_tools, target_api)| AndroidDockerImage.new( repo: repo, build_tools: build_tools, target_api: target_api, tag_format: tag_format ) end end private def patterns(opts) opts[KEY_BUILD_TOOLS].product( opts[KEY_TARGET_API] ) end end end
Replace Mendeley with correct SNPedia
RSpec.describe 'Arriving as user' do let(:snp) { double('snp', name: 'rs1234', snpedia_papers: [snpedia_paper]) } let!(:user) { create(:user, name: 'Potato Bill', snps: [snp]) } let(:snpedia_paper) do double(:snpedia_paper, url: 'http://www.snpedia.com/index.php/Rs1234(A;C)', summary: 'Green hair', snp_variation: 'AC', created_at: '1969-07-20 20:17:40', id: 1) end context 'as a signed-in user' do before do sign_in(user) end scenario 'the user arrives on landing page' do visit root_path expect(page).to have_content('Hello Potato!') expect(page).to have_content('rs1234') # Test Your last 30 updated SNPs feed expect(page).to have_content('Received new data from Mendeley') end end end
RSpec.describe 'Arriving as user' do let(:snp) { double('snp', name: 'rs1234', snpedia_papers: [snpedia_paper]) } let!(:user) { create(:user, name: 'Potato Bill', snps: [snp]) } let(:snpedia_paper) do double(:snpedia_paper, url: 'http://www.snpedia.com/index.php/Rs1234(A;C)', summary: 'Green hair', snp_variation: 'AC', created_at: '1969-07-20 20:17:40', id: 1) end context 'as a signed-in user' do before do sign_in(user) end scenario 'the user arrives on landing page' do visit root_path expect(page).to have_content('Hello Potato!') expect(page).to have_content('rs1234') # Test Your last 30 updated SNPs feed expect(page).to have_content('Received new data from SNPedia') end end end