Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Refactor test to redirect to new experiment path
require 'rails_helper' describe 'Experiment' do feature 'Post a New Experiment' do it 'is able to display a new experiment form' do visit '/experiment/index' click_on 'Post A New Experiment' expect(page).to have_content "Post A New Experiment" end it 'is able to fill out the new experi...
require 'rails_helper' describe 'Experiment' do feature 'Post a New Experiment' do it 'is able to display a new experiment form' do visit '/experiment/index' click_on 'Post A New Experiment' expect(page).to have_current_path new_experiment_path end it 'is able to fill out the new exper...
Create route to searched stories view
Rails.application.routes.draw do mount RedactorRails::Engine => '/redactor_rails' resources :snippets get '/signup', to: 'users#new' post '/signup', to: 'users#create', as: 'new_sign_up' patch 'stories/:id/upvote', to: 'votes#upvote', as: 'vote_up' delete '/vote/:id', to: 'votes#destroy', as: 'vote_delete...
Rails.application.routes.draw do mount RedactorRails::Engine => '/redactor_rails' resources :snippets get '/signup', to: 'users#new' post '/signup', to: 'users#create', as: 'new_sign_up' patch 'stories/:id/upvote', to: 'votes#upvote', as: 'vote_up' delete '/vote/:id', to: 'votes#destroy', as: 'vote_delete...
Use rails 4 route syntax
Refinery::Core::Engine.routes.draw do # Frontend routes namespace :elasticsearch, :path => '' do match "/search", :to => 'search#show', :as => 'search' end end
Refinery::Core::Engine.routes.draw do # Frontend routes namespace :elasticsearch, :path => '' do get '/search', to: 'search#show', as: 'search' end end
Fix logging in validation for user
class SessionsController < ApplicationController def new @user = User.new end def create @user = User.find_by(email: user_params[:email]) if @user.password == params[:password] session[:user_id] = @user.id redirect_to root_path else flash[:notice] = "Invalid Username or Passwor...
class SessionsController < ApplicationController def new @user = User.new end def create user = User.find_by(username: user_params[:username]) if user && user.authenticate(user_params[:password]) session[:user_id] = user.id redirect_to root_path else flash[:notice] = "Invalid U...
Use `eq` instead of `be ==`
require 'spec_helper' describe "Traders" do Trader.all.each do |short_name, trader| it short_name, :vcr do trader.fetch expect(trader.rates).not_to be_empty expect(trader.rates).to be == expected_rates(short_name) end end def expected_rates(short_name) expected_rates_file_path = ...
require 'spec_helper' describe "Traders" do Trader.all.each do |short_name, trader| it short_name, :vcr do trader.fetch expect(trader.rates).not_to be_empty expect(trader.rates).to eq(expected_rates(short_name)) end end def expected_rates(short_name) expected_rates_file_path = "s...
Add a better failing test
require 'spec_helper' describe TicTacToe do it 'has a version number' do expect(TicTacToe::VERSION).not_to be nil end it 'does something useful' do expect(false).to eq(true) end end
require 'spec_helper' describe TicTacToe do it 'has a version number' do expect(TicTacToe::VERSION).not_to be nil end it 'has a game' do game = TicTacToe::Game.new end end
Use a path for the bundle install
omnibus_path = File.join(node['delivery_builder']['repo'], 'omnibus-delivery-cli') execute "bundle install --binstubs=#{omnibus_path}/bin" do cwd omnibus_path end execute "#{omnibus_path}/bin/omnibus build delivery-cli" do cwd omnibus_path end # Here is where you would put your asset upload
omnibus_path = File.join(node['delivery_builder']['repo'], 'omnibus-delivery-cli') execute "bundle install --binstubs=#{omnibus_path}/bin --path=#{File.join(node['delivery_builder']['cache'], 'gems')}" do cwd omnibus_path end execute "#{omnibus_path}/bin/omnibus build delivery-cli" do cwd omnibus_path end # Here...
Simplify shared User SSH key steps
module SharedUser include Spinach::DSL step 'User "John Doe" exists' do user_exists("John Doe", { username: "john_doe" }) end step 'User "Mary Jane" exists' do user_exists("Mary Jane", { username: "mary_jane" }) end step 'gitlab user "Mike"' do create(:user, name: "Mike") end protected ...
module SharedUser include Spinach::DSL step 'User "John Doe" exists' do user_exists("John Doe", { username: "john_doe" }) end step 'User "Mary Jane" exists' do user_exists("Mary Jane", { username: "mary_jane" }) end step 'gitlab user "Mike"' do create(:user, name: "Mike") end protected ...
Remove the do not redistribute clause in the zookeeper cookbook. There's nothing webtrends specific in this
# # Cookbook Name:: zookeeper # Attributes:: default # # Copyright 2012, Webtrends Inc. # # All rights reserved - Do Not Redistribute # default[:zookeeper][:version] = "3.3.6" default[:zookeeper][:download_url] = "http://mirror.uoregon.edu/apache/zookeeper/zookeeper-#{node[:zookeeper][:version]}/zookeeper-#{node[:zook...
# # Cookbook Name:: zookeeper # Attributes:: default # # Copyright 2012, Webtrends Inc. # default[:zookeeper][:version] = "3.3.6" default[:zookeeper][:download_url] = "http://mirror.uoregon.edu/apache/zookeeper/zookeeper-#{node[:zookeeper][:version]}/zookeeper-#{node[:zookeeper][:version]}.tar.gz" default[:zookeeper]...
Add changing the root password to the CentOS recipe
#Make sure that this recipe only runs on ubuntu systems if platform?("centos") #Base recipes necessary for a functioning system include_recipe "sudo" #include_recipe "ad-likewise" include_recipe "openssh" include_recipe "ntp" #User experience and tools recipes include_recipe "vim" include_recipe "man" include_recipe ...
#Make sure that this recipe only runs on ubuntu systems if platform?("centos") #Base recipes necessary for a functioning system include_recipe "sudo" #include_recipe "ad-likewise" include_recipe "openssh" include_recipe "ntp" #User experience and tools recipes include_recipe "vim" include_recipe "man" include_recipe ...
Load app/{crawler,processor}.rb when run crawler/processor
require "thor" require "daimon_skycrawlers" require "daimon_skycrawlers/crawler" module DaimonSkycrawlers module Commands class Runner < Thor namespace "exec" desc "crawler", "Execute crawler" def crawler load_init Dir.glob("app/crawlers/**/*.rb") do |path| require(Fi...
require "thor" require "daimon_skycrawlers" require "daimon_skycrawlers/crawler" module DaimonSkycrawlers module Commands class Runner < Thor namespace "exec" desc "crawler", "Execute crawler" def crawler load_init Dir.glob("app/crawlers/**/*.rb") do |path| require(Fi...
Remove home page for now
require 'spec_helper' describe HomeController do describe 'GET #index' do def make_request get :index end it 'should render the home/index template' do make_request response.should render_template("home/index") end end end
require 'spec_helper' describe HomeController do describe 'GET #index' do def make_request get :index end end end
Use localhost to do SMTP forward delivery in mailcatcher
class MailCatcher::DeliveryService attr_reader :message mattr_accessor :address mattr_accessor :port mattr_accessor :domain mattr_accessor :user_name mattr_accessor :password mattr_accessor :recipient mattr_accessor :authentication # authentication is currently hard-coded @@authentication = 'login' ...
class MailCatcher::DeliveryService attr_reader :message mattr_accessor :address mattr_accessor :port mattr_accessor :domain mattr_accessor :user_name mattr_accessor :password mattr_accessor :recipient mattr_accessor :authentication # authentication is currently hard-coded @@authentication = 'login' ...
Fix serializer to properly serialize relationship for castings
class FullMangaSerializer < MangaSerializer embed :ids, include: true attributes :cover_image, :cover_image_top_offset, :featured_castings has_one :manga_library_entry def manga_library_entry scope && MangaLibraryEntry.where(user_id: scope.id, manga_id: object.id).first end ...
class FullMangaSerializer < MangaSerializer embed :ids, include: true attributes :cover_image, :cover_image_top_offset has_one :manga_library_entry has_many :featured_castings, root: :castings def manga_library_entry scope && MangaLibraryEntry.where(user_id: scope.id, manga_id: object.id)....
Add root_account_id to Lti::LineItems table
# # Copyright (C) 2020 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas is distributed in the ...
Add ruby shebang to test and chmod +x
utf = IO.read("index.html") em = utf.scan(/<em[^>]*>&#([^;]*);<\/em>/) dd = utf.scan(/<dd>&#38;#([^;]*);<\/dd>/) em = em.drop(3).map{|i| i[0].to_i} dd = dd.drop(2).map{|i| i[0].to_i} order = em.sort is_same = em == dd is_order = em == order puts "Are actual entities and shown codes the same?: #{is_same}" if !is_sam...
#!/usr/bin/env ruby utf = IO.read("index.html") em = utf.scan(/<em[^>]*>&#([^;]*);<\/em>/) dd = utf.scan(/<dd>&#38;#([^;]*);<\/dd>/) em = em.drop(3).map{|i| i[0].to_i} dd = dd.drop(2).map{|i| i[0].to_i} order = em.sort is_same = em == dd is_order = em == order puts "Are actual entities and shown codes the same?: #...
Fix uber service nil bug
class UberApiService attr_accessor :token BASE_URL = "https://api.uber.com/v1.2" def initialize(token) @token = token end # Returns a TFF url based on passed params def estimates_price_url(to, from) BASE_URL + "/estimates/price?start_latitude=#{from[0]}&start_longitude=#{from[1]}&end_latitude=#{...
class UberApiService attr_accessor :token BASE_URL = "https://api.uber.com/v1.2" def initialize(token) @token = token end # Returns a TFF url based on passed params def estimates_price_url(to, from) BASE_URL + "/estimates/price?start_latitude=#{from[0]}&start_longitude=#{from[1]}&end_latitude=#{...
Use a .com domain that belongs to us for localhost resolution.
Given /^the application is set up$/ do # Using lvh.me to give us automatic resolution to localhost # N.B. This means some Cucumber scenarios will fail if your machine # isn't connected to the internet. We shoud probably fix this. # # Port needs to be saved for Selenium tests (because our app code considers ...
Given /^the application is set up$/ do # Using ocolocalhost.com to give us automatic resolution to localhost # N.B. This means some Cucumber scenarios will fail if your machine # isn't connected to the internet. We shoud probably fix this. # # Port needs to be saved for Selenium tests (because our app code c...
Fix typo in before action
class RestaurantsController < ApplicationController before_action :set_post, except: %i(index create) def index @restaurants = policy_scope(Restaurant) render json: @restaurants end def show authorize @restaurant render json: @restaurant end def create @restaurant = Restaurant.new(r...
class RestaurantsController < ApplicationController before_action :set_restaurant, except: %i(index create) def index @restaurants = policy_scope(Restaurant) render json: @restaurants end def show authorize @restaurant render json: @restaurant end def create @restaurant = Restaurant...
Test wants this built at instantiation
module MessageQueue class Listener def initialize(topic:, channel:, processor: nil, consumer: nil) @topic = topic @channel = channel @processor = processor || DEFAULT_PROCESSOR @consumer = consumer end def go Signal.trap('INT') do shutdown end Sig...
module MessageQueue class Listener def initialize(topic:, channel:, processor: nil, consumer: nil) @topic = topic @channel = channel @processor = processor || DEFAULT_PROCESSOR @consumer = consumer || MessageQueue::Consumer.new(consumer_params) end def go Signal.trap...
Fix up the asset disposition service to limit to a specific organization and set the default fiscal year to the current planning year.
#------------------------------------------------------------------------------ # # AssetService # # # #------------------------------------------------------------------------------ class AssetDispositionService #------------------------------------------------------------------------------ # # Disposition List...
#------------------------------------------------------------------------------ # # AssetDispositionService # # Contains business logic associated with managing the disposition of assets # # #------------------------------------------------------------------------------ class AssetDispositionService #---------------...
Send error messages to STDERR
class Hotspots module Exit #:nodoc: all class Error attr_reader :code, :message def initialize(options) @message = options[:message] @code = options[:code] end def perform puts @message exit @code end end class Safe attr_reader :cod...
class Hotspots module Exit #:nodoc: all class Error attr_reader :code, :message def initialize(options) @message = options[:message] @code = options[:code] end def perform $stderr.puts @message exit @code end end class Safe attr_rea...
Archive all Published Worldwide Priorities
reason = "This information has been archived. See [what the UK government is doing around the world](https://www.gov.uk/government/world)." WorldwidePriority.where(state: "published").each do |wp| edition = wp.latest_edition puts "Archiving #{edition.title} - edition #{edition.id}" edition.build_unpublishing(exp...
Fix typo in active? method.
class Request < ActiveRecord::Base before_create :defaultly_unfulfilled has_many :messages has_many :transactions belongs_to :requester, class_name: 'User' belongs_to :responder, class_name: 'User' belongs_to :group validates :content, :requester, :group, presence: true validates :is_fulfilled, inclu...
class Request < ActiveRecord::Base before_create :defaultly_unfulfilled has_many :messages has_many :transactions belongs_to :requester, class_name: 'User' belongs_to :responder, class_name: 'User' belongs_to :group validates :content, :requester, :group, presence: true validates :is_fulfilled, inclu...
Add default spec acceptance helper
require 'beaker-rspec' hosts.each do |host| # Install Puppet on host, install_puppet end RSpec.configure do |c| module_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) c.formatter = :documentation # Configure all nodes in nodeset c.before :suite do # Install module puppet_module_...
Remove remaining calls to authenticate
module Twitter class Client module FriendsAndFollowers # TODO: Optional merge user into options if user is nil def friend_ids(*args) authenticate options = args.last.is_a?(Hash) ? args.pop : {} user = args.first merge_user_into_options!(user, options) response =...
module Twitter class Client module FriendsAndFollowers # TODO: Optional merge user into options if user is nil def friend_ids(*args) options = args.last.is_a?(Hash) ? args.pop : {} user = args.first merge_user_into_options!(user, options) response = get('friends/ids', o...
Use hexdigest so we get the checksum when we use S3
module JaduXml class FilePresenter < XmlPresenter property :filename, as: "Filename", exec_context: :decorator property :checksum, as: "Checksum", exec_context: :decorator def filename File.basename(represented.to_s) end def checksum Digest::MD5.file(represented.path).hexdigest e...
module JaduXml class FilePresenter < XmlPresenter property :filename, as: "Filename", exec_context: :decorator property :checksum, as: "Checksum", exec_context: :decorator def filename File.basename(represented.to_s) end def checksum Digest::MD5.hexdigest(represented.read) end ...
Add after Twitter login logic
Dir.glob('./app/**/*.rb').each { |file| require file } module CherryTomato class Application < Sinatra::Base use AssetLoader get '/' do erb :timer end # Twitter auth use OmniAuth::Builder do provider :twitter, 'key', 'secret' end configure do enable :sessions end ...
Dir.glob('./app/**/*.rb').each { |file| require file } module CherryTomato class Application < Sinatra::Base use AssetsHelper use SessionsHelper helpers SessionsHelper::UserSession # Twitter auth use OmniAuth::Builder do provider :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET'] end...
Remove Klarna warning message from Shipments
Deface::Override.new( virtual_path: "spree/admin/orders/edit", insert_top: "[data-hook='admin_order_edit_header']", name: "add_klarna_error_message", partial: "spree/admin/orders/error_message" ) Deface::Override.new( virtual_path: "spree/admin/orders/customer_details/_form", insert_top: "[data-hook='admin...
Deface::Override.new( virtual_path: "spree/admin/orders/customer_details/_form", insert_top: "[data-hook='admin_customer_detail_form_fields']", name: "add_klarna_error_message", partial: "spree/admin/orders/error_message" )
Add other notes attributes to returned JSON
json.array!(@notes) do |note| # json.extract! note, :id, :title, :body_text, :body_html, :created_at, :updated_at json.id note.id json.title note.title json.url api_v1_note_url(note, format: :json, api_key: params[:api_key]) end
json.array!(@notes) do |note| # json.extract! note, :id, :title, :body_text, :body_html, :created_at, :updated_at json.id note.id json.title note.title json.body_text note.body_text json.body_html note.body_html json.created_at note.created_at json.url api_v1_note_url(note, format: :json, api_key: params[...
Fix --exclude argument order to work on OS X. Allow exlude_dir to be an Array
namespace :copy do archive_name = "archive.tar.gz" include_dir = fetch(:include_dir) || "*" exclude_dir = fetch(:exclude_dir) || "" desc "Archive files to #{archive_name}" file archive_name => FileList[include_dir].exclude(archive_name) do |t| sh "tar -cvzf #{t.name} #{t.prerequisites.join(" ")}" + (e...
namespace :copy do archive_name = "archive.tar.gz" include_dir = fetch(:include_dir) || "*" exclude_dir = Array(fetch(:exclude_dir)) exclude_args = exclude_dir.map { |dir| "--exclude '#{dir}'"} desc "Archive files to #{archive_name}" file archive_name => FileList[include_dir].exclude(archive_name) do |...
Add has many relationship between unit and campus sets
class UnitActivitySet < ActiveRecord::Base belongs_to :unit belongs_to :activity_type # Always check for presence of whole model instead of id # So validate presence of unit not unit_id # This ensures that id provided is also valid, so there exists an unit with that id validates :activity_type, presence: t...
class UnitActivitySet < ActiveRecord::Base belongs_to :unit belongs_to :activity_type has_many :campus_activity_sets # Always check for presence of whole model instead of id # So validate presence of unit not unit_id # This ensures that id provided is also valid, so there exists an unit with that id val...
Add ElasticSearch mappings, to fix intermittent errors
module CropSearch extend ActiveSupport::Concern included do #################################### # Elastic search configuration searchkick word_start: %i(name alternate_names scientific_names), case_sensitive: false # Special scope to control if it's in the search index scope :search_import, -...
module CropSearch extend ActiveSupport::Concern included do #################################### # Elastic search configuration searchkick word_start: %i(name alternate_names scientific_names), case_sensitive: false, merge_mappings: true, mappings: { ...
Make the guid match what is in the feed, also return episode id and original/override guid as read only
# encoding: utf-8 class Api::EpisodeRepresenter < Api::BaseRepresenter property :guid property :original_guid property :prx_uri property :created_at property :updated_at property :published_at property :released_at property :url property :image_url property :title property :subtitle property ...
# encoding: utf-8 class Api::EpisodeRepresenter < Api::BaseRepresenter # the guid that shows up in the rss feed property :item_guid, as: :guid # the guid generated by feeder, used in API requests property :guid, as: :id # an original guid for an imported feed, overrides the feeder generated guid property...
Add missing bracket to last line of code
freeway = { red_nissan: { people: ['Susan', 'John'], no_of_cupholders: 4, destination: 'Marin Headlands' }, blue_bmw: { people: ['Eric'], no_of_cupholders: 2, destination: 'The Mission' }, white_honda: { people: ['Roxanne', 'Josh', 'Freddy'], no_of_cupholders: 4, destina...
freeway = { red_nissan: { people: ['Susan', 'John'], no_of_cupholders: 4, destination: 'Marin Headlands' }, blue_bmw: { people: ['Eric'], no_of_cupholders: 2, destination: 'The Mission' }, white_honda: { people: ['Roxanne', 'Josh', 'Freddy'], no_of_cupholders: 4, destina...
Remove seeding of /performance route.
###################################### # # This file is run on every deploy. # Ensure any changes account for this. # ###################################### unless ENV['GOVUK_APP_DOMAIN'].present? abort "GOVUK_APP_DOMAIN is not set. Maybe you need to run under govuk_setenv..." end backends = [ 'canary-frontend',...
###################################### # # This file is run on every deploy. # Ensure any changes account for this. # ###################################### unless ENV['GOVUK_APP_DOMAIN'].present? abort "GOVUK_APP_DOMAIN is not set. Maybe you need to run under govuk_setenv..." end backends = [ 'canary-frontend',...
Add not found message to polling place method
require 'net/http' require 'json' class ZipcodesController < ApplicationController def show @zipcode = session[:zip] @polling_place = get_polling_place(@zipcode) end def self.get_polling_place(address) uri = URI.parse("https://www.googleapis.com/civicinfo/v2/voterinfo?key=#{ENV['API_KEY']}&address=#{...
require 'net/http' require 'json' class ZipcodesController < ApplicationController def show @zipcode = session[:zip] @polling_place = get_polling_place(address) end def self.get_polling_place(address) uri = URI.parse("https://www.googleapis.com/civicinfo/v2/voterinfo?key=#{ENV['API_KEY']}&address=#{a...
Add script to aggregate-process heap file output.
#! /usr/bin/ruby require 'csv' PROFILE = ARGF.argv.shift HEAP_INTERVAL = 250 aggregate = Hash.new {} CSV.foreach(PROFILE, {:headers => true}) do |row| key =[[row["query"], row["sf"], row["prof_type"]]] unless aggregate.member? key aggregate[key] = {} end job = row["job"] unless aggregate[key].member?...
Make sure the metadata object is always present on Identity resources
module Layer # Managing user identity is also possible: # # @example # user = Layer::User.find('user_id') # user.identity # Returns user identity # user.identity.create({ first_name: 'Frodo', last_name: 'Baggins'}) # Creates new identity # user.identity.delete # Removes identity # # @see https...
module Layer # Managing user identity is also possible: # # @example # user = Layer::User.find('user_id') # user.identity # Returns user identity # user.identity.create({ first_name: 'Frodo', last_name: 'Baggins'}) # Creates new identity # user.identity.delete # Removes identity # # @see https...
Add title extraction for non-trivial HTML pages
module ManBook class Parser class << self def parse(html_file) # # The way we extract the title is highly dependent of the concrete HTML. Yet, I found no other way # to extract the title of a man page ín a reliable way. # # TODO For git, less, gunzip: # <h2>NA...
module ManBook class Parser class << self def parse(html_file) # # The way we extract the title is highly dependent of the concrete HTML. Yet, I found no other way # to extract the title of a man page ín a reliable way. # # TODO For git, less, gunzip: # <h2>NA...
Add backend JS to precompile list
module SolidusPaypalBraintree class Engine < Rails::Engine isolate_namespace SolidusPaypalBraintree engine_name 'solidus_paypal_braintree' # use rspec for tests config.generators do |g| g.test_framework :rspec end initializer "register_solidus_paypal_braintree_gateway", after: "spree.r...
module SolidusPaypalBraintree class Engine < Rails::Engine isolate_namespace SolidusPaypalBraintree engine_name 'solidus_paypal_braintree' # use rspec for tests config.generators do |g| g.test_framework :rspec end initializer "register_solidus_paypal_braintree_gateway", after: "spree.r...
Define intializer to set RakutenWebService configuration.
RakutenWebService.configuration do |c| c.application_id = ENV['RWS_APPLICATION_ID'] c.affiliate_id = ENV['RWS_AFFILIATE_ID'] end
Add json crud routes to wants controller
class WantsController < ApplicationController def index end def show end def new end def create end def edit end def update end def destroy end end
class WantsController < ApplicationController before_action :wants_find, only: [:index, :show, :edit, :destroy, :update] def index render json: @wants end def show render json: @want end def new @want = Want.new end def create @want = Want.new(user_id: params[:user_id], product_id: p...
Upgrade ruby rake dependency (security).
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'net-http2/version' Gem::Specification.new do |spec| spec.name = "net-http2" spec.version = NetHttp2::VERSION spec.licenses = ['MIT'] spec.autho...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'net-http2/version' Gem::Specification.new do |spec| spec.name = "net-http2" spec.version = NetHttp2::VERSION spec.licenses = ['MIT'] spec.autho...
Add support for Extensions to define Transformers
module Awestruct module Extensions class Pipeline attr_reader :before_extensions attr_reader :extensions attr_reader :after_extensions attr_reader :helpers attr_reader :transformers def initialize(&block) @extensions = [] @helpers = [] @transformer...
module Awestruct module Extensions class Pipeline attr_reader :before_extensions attr_reader :extensions attr_reader :after_extensions attr_reader :helpers attr_reader :transformers def initialize(&block) @extensions = [] @helpers = [] @transformer...
Add option parameter to `cache_all`
require 'redis_cacheable' # Specialized for ActiveRecord module RedisCacheable module ActiveRecord extend ActiveSupport::Concern include ::RedisCacheable module ClassMethods # @param [Object] key # @return [ActiveRecord::Base] ActiveRecord instantiated object def find_from_redis(key) ...
require 'redis_cacheable' # Specialized for ActiveRecord module RedisCacheable module ActiveRecord extend ActiveSupport::Concern include ::RedisCacheable module ClassMethods # @param [Object] key # @return [ActiveRecord::Base] ActiveRecord instantiated object def find_from_redis(key) ...
Remove Rails 5 deprecation on reloading the settings_changes.
module Vmdb class Settings class DatabaseSource include Vmdb::Logging attr_reader :resource def initialize(resource) @resource = resource end def load return if resource.nil? resource.settings_changes(true).each_with_object({}) do |c, h| h.store_...
module Vmdb class Settings class DatabaseSource include Vmdb::Logging attr_reader :resource def initialize(resource) @resource = resource end def load return if resource.nil? resource.settings_changes.reload.each_with_object({}) do |c, h| h.store...
Add introspection method for filtering violations by type
require 'standalone_validator/validation_result_builder' require 'hamster/list' class StandaloneValidator class ValidationResult def self.build_for(object, &block) builder = ValidationResultBuilder.new builder.validated_object = object if block.arity == 1 block.call(builder) else...
require 'standalone_validator/validation_result_builder' require 'hamster/list' class StandaloneValidator class ValidationResult def self.build_for(object, &block) builder = ValidationResultBuilder.new builder.validated_object = object if block.arity == 1 block.call(builder) else...
Allow feature descriptions to be blank
class CreateFeatures < ActiveRecord::Migration def change create_table :features do |t| t.integer :page_id, :null => false, :on_delete => :cascade t.integer :primary_asset_id, :null => true, :on_delete => :set_null, :references => :assets t.integer :secondary_asset_id, :null => ...
class CreateFeatures < ActiveRecord::Migration def change create_table :features do |t| t.integer :page_id, :null => false, :on_delete => :cascade t.integer :primary_asset_id, :null => true, :on_delete => :set_null, :references => :assets t.integer :secondary_asset_id, :null => ...
Reorganize sign in page test
require 'spec_helper' describe "Authentication" do subject { page } describe "signin page" do before { visit signin_path } let(:submit) { "Sign in" } it { should have_h1('Sign in') } describe "with invalid credentials" do before { click_button submit } it { should have_h1('Sign...
require 'spec_helper' describe "Authentication" do subject { page } describe "signin" do before { visit signin_path } let(:submit) { "Sign in" } describe "page" do it { should have_h1('Sign in') } end describe "with invalid credentials" do before { click_button submit } ...
Add type and time to Transaction
module Ravelin class Transaction < RavelinObject attr_accessor :transaction_id, :email, :currency, :debit, :credit, :gateway, :custom, :success, :auth_code, :decline_code, :gateway_reference, :avs_result_code, :cvv_result_code attr_requi...
module Ravelin class Transaction < RavelinObject attr_accessor :transaction_id, :email, :currency, :debit, :credit, :gateway, :custom, :success, :auth_code, :decline_code, :gateway_reference, :avs_result_code, :cvv_result_code, :type, ...
Return true in Limiter shebang methods
module Ultima module Core class Limiter def initialize(limit_rate) @limit_rate = limit_rate reset! end def reset! @acted_at = nil end def act! @acted_at = Gosu::milliseconds end def may_act? @acted_at.nil? || Gosu::milliseconds -...
module Ultima module Core class Limiter def initialize(limit_rate) @limit_rate = limit_rate reset! end def reset! @acted_at = nil true end def act! @acted_at = Gosu::milliseconds true end def may_act? @acted_at.ni...
Test for legislator search by lat / long
require 'sunlight/congress' require 'webmock/minitest' class TestIntegrationCongress < MiniTest::Unit::TestCase def setup Sunlight::Congress.api_key = "thisismykey" end def test_legislators_by_zipcode stub_request(:get, "http://congress.api.sunlightfoundation.com/legislators/locate?apikey=thisismykey&zi...
require 'sunlight/congress' require 'webmock/minitest' class TestIntegrationCongress < MiniTest::Unit::TestCase def setup Sunlight::Congress.api_key = "thisismykey" end def test_legislators_by_zipcode stub_request(:get, "http://congress.api.sunlightfoundation.com/legislators/locate?apikey=thisismykey&zi...
Include Store when editing Item
class ItemsController < ApplicationController def index end def show end def new @list = List.find_by(id: params[:list_id]) @item = @list.items.build @store = Store.new end def edit @list = List.find_by(id: params[:list_id]) @item = Item.find_by(id: params[:id]) render :edit e...
class ItemsController < ApplicationController def index end def show end def new @list = List.find_by(id: params[:list_id]) @item = @list.items.build @store = Store.new end def edit @list = List.find_by(id: params[:list_id]) @item = Item.find_by(id: params[:id]) @store = @item.s...
Allow symbols in request query
require 'net/https' module Scrobbler module REST class Connection def initialize(base_url, args = {}) @base_url = base_url @username = args[:username] @password = args[:password] end def get(resource, args = nil) request(resource, "get", args) end def post(resource, args ...
require 'net/https' module Scrobbler module REST class Connection def initialize(base_url, args = {}) @base_url = base_url @username = args[:username] @password = args[:password] end def get(resource, args = nil) request(resource, "get", args) end def post(resource, args ...
Add Validation to Question for Specs Testing
class Question < ActiveRecord::Base belongs_to :user has_many :responses end
class Question < ActiveRecord::Base belongs_to :user has_many :responses validates :image_path, presence: true end
Fix typo in setup env docs
module Flipper module Middleware class SetupEnv # Public: Initializes an instance of the SetEnv middleware. Allows for # lazy initialization of the flipper instance being set in the env by # providing a block. # # app - The app this middleware is included in. # flipper_or_block...
module Flipper module Middleware class SetupEnv # Public: Initializes an instance of the SetupEnv middleware. Allows for # lazy initialization of the flipper instance being set in the env by # providing a block. # # app - The app this middleware is included in. # flipper_or_blo...
Build taskwarrior with a bash block.
git "#{Chef::Config[:file_cache_path]}/task.git" do repository node["taskwarrior"]["source"]["git_repository"] reference node["taskwarrior"]["source"]["git_revision"] action :sync end
git "#{Chef::Config[:file_cache_path]}/task.git" do repository node["taskwarrior"]["source"]["git_repository"] reference node["taskwarrior"]["source"]["git_revision"] action :sync end bash "Install taskwarrior" do user "root" cwd "#{Chef::Config[:file_cache_path]}/task.git" code <<-EOH cmake . make m...
Remove attachment styles and unnecessary content type
class Document < ActiveRecord::Base belongs_to :user has_attached_file :doc_pdf, styles: {:thumb => "100x100#", :small => "150x150>", :medium => "200x200" } validates_attachment_content_type :doc_pdf, content_type: ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'] end
class Document < ActiveRecord::Base belongs_to :user has_attached_file :doc_pdf validates_attachment_content_type :doc_pdf, content_type: "application/pdf" end
Remove nonsense from XMPP tests
require File.dirname(__FILE__) + "/test_helper" context "Connecting to an XMPP Server" do include XMPPTestHelper before(:all) { require '' } before :each do end after :each do XMPP.stop end after do XMPP.stop end end BEGIN { module XMPPTestHelper end }
require File.dirname(__FILE__) + "/test_helper" context "Connecting to an XMPP Server" do include XMPPTestHelper before(:all) { } # TODO: Actually test something after do XMPP.stop end end BEGIN { module XMPPTestHelper end }
Move profils controller spec to factory_girl.
# -*- encoding : utf-8 -*- require 'rails_helper' describe ProfilesController do setup(:activate_authlogic) context "an user logged in station in demo mode" do before(:each) do login(Station.make!(:demo => true)) end describe "GET :edit" do before(:each) do get :edit end ...
# -*- encoding : utf-8 -*- require 'rails_helper' describe ProfilesController do setup(:activate_authlogic) context "an user logged in station in demo mode" do before(:each) do login(create(:station, :demo => true)) end describe "GET :edit" do before(:each) do get :edit e...
Test for session controller pass, 100% coverage
require 'rails_helper' describe SessionsController do it 'renders the login page' do get :new expect(response).to have_http_status(:ok) expect(response).to render_template(:new) end it 'assigns an empty login form' do get :new expect(assigns(:login)).to be_a(LoginForm) end describe '#d...
require 'rails_helper' describe SessionsController do it 'renders the login page' do get :new expect(response).to have_http_status(:ok) expect(response).to render_template(:new) end it 'assigns an empty login form' do get :new expect(assigns(:login)).to be_a(LoginForm) end describe '#d...
Use the hanna rdoc template
require 'fileutils' include FileUtils require 'rubygems' %w[rake hoe newgem rubigen].each do |req_gem| begin require req_gem rescue LoadError puts "This Rakefile requires the '#{req_gem}' RubyGem." puts "Installation: gem install #{req_gem} -y" exit end end $:.unshift(File.join(File.dirname(__FI...
require 'fileutils' include FileUtils require 'rubygems' %w[hanna/rdoctask rake hoe newgem rubigen].each do |req_gem| begin require req_gem rescue LoadError puts "This Rakefile requires the '#{req_gem}' RubyGem." puts "Installation: gem install #{req_gem} -y" exit end end $:.unshift(File.join(Fi...
Change snippet max_results: 3 -> 10
require 'haml' require 'honyomi/database' require 'sinatra' require 'sinatra/reloader' if ENV['SINATRA_RELOADER'] include Honyomi set :haml, :format => :html5 configure do $database = Database.new end get '/' do @database = $database results = @database.search(@params[:query]) page_entries = results.pagina...
require 'haml' require 'honyomi/database' require 'sinatra' require 'sinatra/reloader' if ENV['SINATRA_RELOADER'] include Honyomi set :haml, :format => :html5 configure do $database = Database.new end get '/' do @database = $database results = @database.search(@params[:query]) page_entries = results.pagina...
Remove active resource require because we are not using it
# encoding: utf-8 require 'rspec' require 'rspec_tag_matchers' RSpec.configure do |config| config.include RspecTagMatchers config.include CustomMacros config.mock_with :rspec end require "action_controller/railtie" require "active_resource/railtie" require 'active_model' # Create a simple rails application for...
# encoding: utf-8 require 'rspec' require 'rspec_tag_matchers' RSpec.configure do |config| config.include RspecTagMatchers config.include CustomMacros config.mock_with :rspec end require "action_controller/railtie" require 'active_model' # Create a simple rails application for use in testing the viewhelper mod...
Raise an RecordNotFound error on Stop.find_legacy
class Stop < ActiveRecord::Base acts_as_mappable(lat_column_name: :latitude, lng_column_name: :longitude) has_many :stop_times has_many :trips, through: :stop_times has_many :routes, -> { uniq }, through: :trips belongs_to :agency include PgSearch pg_search_scope :search, against: [:name, :code] DIREC...
class Stop < ActiveRecord::Base acts_as_mappable(lat_column_name: :latitude, lng_column_name: :longitude) has_many :stop_times has_many :trips, through: :stop_times has_many :routes, -> { uniq }, through: :trips belongs_to :agency include PgSearch pg_search_scope :search, against: [:name, :code] DIREC...
Trim out devise options comment
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, :lockable and :timeoutable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :token_authenticateable, :confirmable...
class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :token_authenticateable, :confirmable, :lockable attr_accessor :login attr_accessible :username, :email, :login, :password, :password_confirm...
Add Devise's helpers to View specs as suggested
RSpec.configure do |config| # Add Devise's helpers for controller tests config.include Devise::Test::ControllerHelpers, type: :controller end
RSpec.configure do |config| # Add Devise's helpers for controller and view tests config.include Devise::Test::ControllerHelpers, type: :controller config.include Devise::Test::ControllerHelpers, type: :view end
Switch to shared token parser.
class NewslettersController < ApplicationController skip_before_action :verify_authenticity_token skip_before_action :authorize, only: [:create] def create newsletter = Newsletter.new(params) user = AuthenticationToken.newsletters.active.where(token: newsletter.token).take&.user if user && newsletter...
class NewslettersController < ApplicationController skip_before_action :verify_authenticity_token skip_before_action :authorize, only: [:create] def create newsletter = Newsletter.new(params) user = AuthenticationToken.newsletters.active.where(token: newsletter.token).take&.user if user && newsletter...
Add error classes for not found resources and failed responses.
module Acfs # Acfs base error. # class Error < StandardError; end end
module Acfs # Acfs base error. # class Error < StandardError end # Response error containing the responsible response object. # class ErroneousResponse < Error attr_accessor :response def initialize(response) self.response = response end end # Resource not found error raised on a...
Add Clang as an option to LLVM formula
require 'formula' class Llvm <Formula @url='http://llvm.org/releases/2.6/llvm-2.6.tar.gz' @homepage='http://llvm.org/' @md5='34a11e807add0f4555f691944e1a404a' def install ENV.gcc_4_2 # llvm can't compile itself system "./configure", "--prefix=#{prefix}", "--enable-targets=ho...
require 'formula' class Clang <Formula url 'http://llvm.org/releases/2.6/clang-2.6.tar.gz' homepage 'http://llvm.org/' md5 '09d696bf23bb4a3cf6af3c7341cdd946' end class Llvm <Formula url 'http://llvm.org/releases/2.6/llvm-2.6.tar.gz' homepage 'http://llvm.org/' md5 '34a11e807add0f...
Use the terminology "patterns" wrt to specing Spidr::Rules.
require 'spidr/rules' require 'spec_helper' describe Rules do it "should accept data based on acceptance data" do rules = Rules.new(:accept => [1]) rules.accept?(1).should == true end it "should accept data based on acceptance regexps" do rules = Rules.new(:accept => [/1/]) rules.accept?('1')...
require 'spidr/rules' require 'spec_helper' describe Rules do it "should accept data based on acceptance data" do rules = Rules.new(:accept => [1]) rules.accept?(1).should == true end it "should accept data based on acceptance regexps" do rules = Rules.new(:accept => [/1/]) rules.accept?('1')...
Prepare to release version 1.3
Gem::Specification.new do |gem| gem.name = "delayed_job_web" gem.version = "1.2.10" gem.author = "Erick Schmitt" gem.email = "ejschmitt@gmail.com" gem.homepage = "https://github.com/ejschmitt/delayed_job_web" gem.summary = "Web interface for delayed_job inspired by resque" gem...
Gem::Specification.new do |gem| gem.name = "delayed_job_web" gem.version = "1.3" gem.author = "Erick Schmitt" gem.email = "ejschmitt@gmail.com" gem.homepage = "https://github.com/ejschmitt/delayed_job_web" gem.summary = "Web interface for delayed_job inspired by resque" gem.de...
Switch to use global `$stdin`
module Brightbox command [:users] do |cmd| cmd.desc I18n.t("users.update.desc") cmd.arg_name "user-id..." cmd.command [:update] do |c| c.desc "Path to public ssh key file" c.long_desc "This is the path to the public ssh key that you'd like to use for new servers. You can specify '-' to r...
module Brightbox command [:users] do |cmd| cmd.desc I18n.t("users.update.desc") cmd.arg_name "user-id..." cmd.command [:update] do |c| c.desc "Path to public ssh key file" c.long_desc "This is the path to the public ssh key that you'd like to use for new servers. You can specify '-' to r...
Switch gemspec to Bundler's default format
Gem::Specification.new do |s| s.name = 'scraperwiki' s.version = '2.0.6' s.date = '2013-04-04' s.summary = "ScraperWiki" s.description = "A library for scraping web pages and saving data easily" s.authors = ["Francis irving"] s.email = 'francis@scraperwiki.com' s.files ...
# -*- encoding: utf-8 -*- Gem::Specification.new do |gem| gem.authors = ['Francis irving'] gem.email = 'francis@scraperwiki.com' gem.description = 'A library for scraping web pages and saving data easily' gem.summary = 'ScraperWiki' gem.homepage = 'http://rubygems.org/gems/scraperw...
Fix include syntax in RSpec configuration
require 'config/boot' RSpec.configure do |config| include Rack::Test::Methods def app Acme::Application end end
require 'config/boot' RSpec.configure do |config| config.include Rack::Test::Methods def app Acme::Application end end
Fix Unit tests on CI
# frozen_string_literal: true unless ENV['CI'] require 'simplecov' SimpleCov.start end require 'capybara' require 'capybara/dsl' $LOAD_PATH << './test_site' $LOAD_PATH << './lib' require 'site_prism' require 'test_site' require 'sections/people' require 'sections/blank' require 'sections/container' require 'pag...
# frozen_string_literal: true unless ENV['CI'] require 'simplecov' SimpleCov.start end require 'capybara' require 'capybara/dsl' $LOAD_PATH << './lib' $LOAD_PATH << './features/support' require 'site_prism' require 'sections/all' require 'pages/home' Capybara.default_max_wait_time = 0 RSpec.configure do |conf...
Add explicit support for params wrapper
# Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper # Enable parameter wrapping for JSON. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] if respond_to?(:wrap_parameters) end # To enable root element in JSON for ...
# Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper # Enable parameter wrapping for JSON. ActiveSupport.on_load(:action_controller) do include ActionController::ParamsWrapper wrap_parameters format: [:json] if respond_to?(:wrap_parameters) ...
Make it clear that the later test is skipped for adapters that do not implement it
require 'helper' require 'jobs/hello_job' require 'active_support/core_ext/numeric/time' class QueuingTest < ActiveSupport::TestCase setup do $BUFFER = [] end test 'run queued job' do HelloJob.enqueue assert_equal "David says hello", $BUFFER.pop end test 'run queued job with parameters' do ...
require 'helper' require 'jobs/hello_job' require 'active_support/core_ext/numeric/time' class QueuingTest < ActiveSupport::TestCase setup do $BUFFER = [] end test 'run queued job' do HelloJob.enqueue assert_equal "David says hello", $BUFFER.pop end test 'run queued job with parameters' do ...
Fix PARAMS_REQUIRED const, should be an array, not a hash
module Poke # Map reads an ASCII file and coverts it to an object that can be read and # manipulated by other program objects. class Map include Poke::ReadMap # Params required at initialization. PARAMS_REQUIRED = {:map_file} # Creates a Map object. # # params - A Hash of Symbol options...
module Poke # Map reads an ASCII file and coverts it to an object that can be read and # manipulated by other program objects. class Map include Poke::ReadMap # Params required at initialization. PARAMS_REQUIRED = [:map_file] # Creates a Map object. # # params - A Hash of Symbol options...
Add request headers to JS error report
class ErrorsController < ApplicationController class JavaScriptError < Struct.new(:message) def backtrace [] end end newrelic_ignore if defined?(NewRelic) && respond_to?(:newrelic_ignore) def create if Rails.application.config.whoopsie.enable report = params[:error_report] report...
class ErrorsController < ApplicationController class JavaScriptError < Struct.new(:message) def backtrace [] end end newrelic_ignore if defined?(NewRelic) && respond_to?(:newrelic_ignore) def create if Rails.application.config.whoopsie.enable report = params[:error_report] report...
Use guard clause instead of if else statement
module Spree::Retail module RefundDecorator delegate :pos_order_id, to: :payment delegate :pos_refunded, to: :reimbursement def perform! if reimbursement.present? && pos_refunded? return_all_inventory_unit!(reimbursement) try_set_order_to_return!(reimbursement) update_order ...
module Spree::Retail module RefundDecorator delegate :pos_order_id, to: :payment delegate :pos_refunded, to: :reimbursement def perform! super unless pos_refunded? return_all_inventory_unit!(reimbursement) try_set_order_to_return!(reimbursement) update_order true end ...
Revert "Ensure message as error" (logged_errors method is in the bug)
class Fluentd::Settings::HistoriesController < ApplicationController before_action :login_required before_action :find_fluentd before_action :find_backup_file, only: [:show, :reuse, :configtest] def index @backup_files = @fluentd.agent.backup_files_in_new_order.map do |file_path| Fluentd::SettingArch...
class Fluentd::Settings::HistoriesController < ApplicationController before_action :login_required before_action :find_fluentd before_action :find_backup_file, only: [:show, :reuse, :configtest] def index @backup_files = @fluentd.agent.backup_files_in_new_order.map do |file_path| Fluentd::SettingArch...
Add :with_country trait for Zone factory
FactoryGirl.define do factory :global_zone, class: Spree::Zone do name 'GlobalZone' description { generate(:random_string) } zone_members do |proxy| zone = proxy.instance_eval { @instance } Spree::Country.all.map do |c| zone_member = Spree::ZoneMember.create(zoneable: c, zone: zone) ...
FactoryGirl.define do factory :global_zone, class: Spree::Zone do name 'GlobalZone' description { generate(:random_string) } zone_members do |proxy| zone = proxy.instance_eval { @instance } Spree::Country.all.map do |c| zone_member = Spree::ZoneMember.create(zoneable: c, zone: zone) ...
Test creating an invalid overheard
require_relative 'helper' class TestCreateOverheards < FeatureTest def test_creating_a_valid_overheard random_fake_quote = Faker::Lorem.sentence visit "/" click_on "Add Overheard" fill_in "Body", { :with => random_fake_quote } click_on "Create Overheard" assert_content random_fake_quote en...
require_relative 'helper' class TestCreateOverheards < FeatureTest def test_creating_a_valid_overheard random_fake_quote = Faker::Lorem.sentence visit "/" click_on "Add Overheard" fill_in "Body", { :with => random_fake_quote } click_on "Create Overheard" assert_content random_fake_quote e...
Add simple spec to test webhooks
require "spec_helper" describe "Threasy::Work" do before :each do @work = Threasy::Work.instance end describe "#enqueue" do it "should allow a job object to be enqueued and worked" do job = double("job") expect(job).to receive(:perform).once @work.enqueue job sleep 0.5 end ...
require "spec_helper" describe "Threasy::Work" do before :each do @work = Threasy::Work.instance end describe "#enqueue" do it "should have a method for enqueing" do expect(@work.respond_to?(:enqueue)).to be_true end it "should allow a job object to be enqueued and worked" do job = ...
Update .podspec for 1.0.5 release
Pod::Spec.new do |s| s.name = "HSClusterMapView" s.version = "1.0.4" s.summary = "A GMSMapView subclass which clusters GMSMarkers within close proximity." s.description = "A GMSMapView subclass which clusters groups of GMSMarkers and replaces them with single GMSMarkers, enabl...
Pod::Spec.new do |s| s.name = "HSClusterMapView" s.version = "1.0.5" s.summary = "A GMSMapView subclass which clusters GMSMarkers within close proximity." s.description = "A GMSMapView subclass which clusters groups of GMSMarkers and replaces them with single GMSMarkers, enabl...
Remove the version constraint on Foodcritic
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "thor-foodcritic/version" Gem::Specification.new do |s| s.name = "thor-foodcritic" s.version = ThorFoodCritic::VERSION s.authors = ["Jamie Winsor"] s.email = ["jamie@vials...
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "thor-foodcritic/version" Gem::Specification.new do |s| s.name = "thor-foodcritic" s.version = ThorFoodCritic::VERSION s.authors = ["Jamie Winsor"] s.email = ["jamie@vials...
Fix rename of test_sqlserver_schema_dump_should_honor_nonstandard_primary_keys test.
require 'cases/sqlserver_helper' # NOTE: The existing schema_dumper_test doesn't test the limits of <4 limit things # for adapaters that aren't mysql, sqlite or postgres. We should. It also only tests # non-standard id dumping for mysql. We'll do that too. class SchemaDumperTestSqlserver < ActiveRecord::TestCase ...
require 'cases/sqlserver_helper' # NOTE: The existing schema_dumper_test doesn't test the limits of <4 limit things # for adapaters that aren't mysql, sqlite or postgres. We should. It also only tests # non-standard id dumping for mysql. We'll do that too. class SchemaDumperTestSqlserver < ActiveRecord::TestCase ...
Replace secure option with returning value if it's a Proc
require "rack/dynamic_session_secure/version" module Rack module DynamicSessionSecure # Your code goes here... end end
require "rack/dynamic_session_secure/version" module Rack module DynamicSessionSecure end module Session module Abstract class ID def prepare_session_with_dynamic(env) prepare_session_without_dynamic(env) _options = env[ENV_SESSION_OPTIONS_KEY].dup secure = _opt...
Support running spec for one file.
Dir['algorithms/**/*.md'].each do |file_name| matcher = File.read(file_name).match(/~~~\n(require 'rspec'\n.+?)\n~~~/m) next if matcher.nil? puts "Running #{file_name}" matcher.captures.each do |capture| File.write('_site/spec.rb', capture) system('rspec _site/spec.rb') end end
require 'tempfile' Dir[ARGV[0] || 'algorithms/**/*.md'].each do |filename| matcher = File.read(filename).match(/~~~\n(require 'rspec'\n.+?)\n~~~/m) next if matcher.nil? puts "Running #{filename}" matcher.captures.each do |capture| tempfile = Tempfile.new('spec') tempfile.write(capture) tempfile.c...
Add auto_updates flag to Handbrake
cask 'handbrake' do version '0.10.3' sha256 '5bf327f6d42901668490338c32eab8cc2d4db3e09ea1cb9b8c44573ed8fb5dda' url "http://download.handbrake.fr/releases/#{version}/HandBrake-#{version}-MacOSX.6_GUI_x86_64.dmg" appcast 'https://handbrake.fr/appcast.x86_64.xml', checkpoint: 'fd37c7d6741c19ae69270c1af2...
cask 'handbrake' do version '0.10.3' sha256 '5bf327f6d42901668490338c32eab8cc2d4db3e09ea1cb9b8c44573ed8fb5dda' url "http://download.handbrake.fr/releases/#{version}/HandBrake-#{version}-MacOSX.6_GUI_x86_64.dmg" appcast 'https://handbrake.fr/appcast.x86_64.xml', checkpoint: 'fd37c7d6741c19ae69270c1af2...
Support numeric and boolean literals in query builder.
module CMIS module Utils module_function def build_query_statement(type_id, properties, *queried_properties) QueryStatementBuilder.new(type_id, properties, queried_properties).build end class QueryStatementBuilder def initialize(type_id, properties, queried_properties) @type_id =...
module CMIS module Utils module_function def build_query_statement(type_id, properties, *queried_properties) QueryStatementBuilder.new(type_id, properties, queried_properties).build end class QueryStatementBuilder def initialize(type_id, properties, queried_properties) @type_id =...
Add legal name to organization factories.
FactoryBot.define do factory :organization do customer_id { 1 } address1 { '100 Main St' } city { 'Harrisburg' } state { 'PA' } zip { '17120' } url { 'http://www.example.com' } phone { '9999999999' } grantor_id { 1 } organization_type_id { 1 } sequence(:na...
FactoryBot.define do factory :organization do customer_id { 1 } address1 { '100 Main St' } city { 'Harrisburg' } state { 'PA' } zip { '17120' } url { 'http://www.example.com' } phone { '9999999999' } grantor_id { 1 } organization_type_id { 1 } sequence(:na...
Fix eventmachine crashing by using epoll
require 'em-websocket' require 'json' require 'optparse' address = "0.0.0.0" port = 8080 OptionParser.new do |opts| opts.banner = "Usage: bundle exec server.rb [options]" opts.on("-a", "--address", "Address") do |a| address = a end opts.on("-p", "--port PORT", Integer, "Port") do |p| port = Integer(...
require 'em-websocket' require 'json' require 'optparse' address = "0.0.0.0" port = 8080 OptionParser.new do |opts| opts.banner = "Usage: bundle exec server.rb [options]" opts.on("-a", "--address", "Address") do |a| address = a end opts.on("-p", "--port PORT", Integer, "Port") do |p| port = Integer(...
Fix domain get for non admins, Delete nonsense auth. check
module Identity class DomainsController < ::DashboardController rescue_from "MonsoonOpenstackAuth::Authentication::NotAuthorized", with: :not_member_error authorization_required additional_policy_params: {domain_id: proc {@scoped_domain_id}} def show @user_domain_projects_tree = services.identity....
module Identity class DomainsController < ::DashboardController rescue_from "MonsoonOpenstackAuth::Authentication::NotAuthorized", with: :not_member_error authorization_required additional_policy_params: {domain_id: proc {@scoped_domain_id}} def show @user_domain_projects_tree = services.identity....
Update policy data migration to use prefix route
require 'gds_api/router' router = GdsApi::Router.new(Plek.find('router-api')) slug = 'making-schools-and-colleges-more-accountable-and-giving-them-more-control-over-their-budget' new_slug = 'making-schools-and-colleges-more-accountable-and-funding-them-fairly' # load the policy and the supporting pages policy = Polic...
require 'gds_api/router' router = GdsApi::Router.new(Plek.find('router-api')) slug = 'making-schools-and-colleges-more-accountable-and-giving-them-more-control-over-their-budget' new_slug = 'making-schools-and-colleges-more-accountable-and-funding-them-fairly' # load the policy and the supporting pages policy = Polic...
Use reduce to compute factorials
<<~DOC Use reduce to get the sum of an array DOC a = [1, 2, 3] a.reduce :+ # => 6
# Use reduce to get the sum of an array a = [1, 2, 3] a.reduce :+ # => 6 # Use reduce to get the factorial of a number (1..n).reduce(1, :*)
Remove Compete-specific logic into domain models.
module Rubill class Customer < Base def self.find_by_name(name) record = active.detect do |d| d[:name] == name end raise NotFound unless record new(record) end def contacts CustomerContact.find_by_customer(id) end def create_credit(amount, description="", s...
module Rubill class Customer < Base def self.find_by_name(name) record = active.detect do |d| d[:name] == name end raise NotFound unless record new(record) end def contacts CustomerContact.find_by_customer(id) end def self.remote_class_name "Customer"...
Support the other SCP Databases
require 'nokogiri' require 'mechanize' class SCPArticleLoader def initialize(item_no, option) @item_no = item_no @option = option @agent = Mechanize.new url = "http://#{@option[:locale]}.scp-wiki.net/scp-#{@item_no}" page = @agent.get(url) doc = Nokogiri::HTML(page.content.toutf8) @articl...
require 'nokogiri' require 'mechanize' require_relative 'locale' class SCPArticleLoader def initialize(item_no, option) @item_no = item_no @option = option @agent = Mechanize.new url = "http://#{get_endpoint(@option[:locale])}/scp-#{@item_no}" page = @agent.get(url) doc = Nokogiri::HTML(page....