Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Use space as error delimiter, for usable links in Jenkins
class Reporter def blank_old_url(row) end def invalid_old_url(row) output [ row['old url'], 'invalid old url', row['source'], row['row_number'] ] end def invalid_new_url(row, new_url) output [ new_url, 'invalid new url', row['source'], row['row_nu...
class Reporter def blank_old_url(row) end def invalid_old_url(row) output [ row['old url'], 'invalid old url', row['source'], row['row_number'] ] end def invalid_new_url(row, new_url) output [ new_url, 'invalid new url', row['source'], row['row_nu...
Add multi json as dependency.
# -*- encoding: utf-8 -*- $:.push File.expand_path('../lib', __FILE__) require 'guard/jasmine/version' Gem::Specification.new do |s| s.name = 'guard-jasmine' s.version = Guard::JasmineVersion::VERSION s.platform = Gem::Platform::RUBY s.authors = ['Michael Kessler'] s.email = ['michi@n...
# -*- encoding: utf-8 -*- $:.push File.expand_path('../lib', __FILE__) require 'guard/jasmine/version' Gem::Specification.new do |s| s.name = 'guard-jasmine' s.version = Guard::JasmineVersion::VERSION s.platform = Gem::Platform::RUBY s.authors = ['Michael Kessler'] s.email = ['michi@n...
Fix last rspec deprecation notice.
# This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # Require this file using `require "spec_helper"` to ensure that it is only # loaded once. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration requi...
# This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # Require this file using `require "spec_helper"` to ensure that it is only # loaded once. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration requi...
Add the correct github url.
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'icapps/translations/version' Gem::Specification.new do |spec| spec.name = "icapps-translations" spec.version = Icapps::Translations::VERSION spec.authors = ["Jelle Vand...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'icapps/translations/version' Gem::Specification.new do |spec| spec.name = "icapps-translations" spec.version = Icapps::Translations::VERSION spec.authors = ["Jelle Vand...
Remove CollectionProxy methods from Resource
class SkroutzApi::Resource include SkroutzApi::Parsing attr_accessor :attributes, :client def initialize(attributes, client) @attributes = attributes @client = client end def find(id, options = {}) response = client.get("#{resource_prefix}/#{id}") return parse_body(response) unless block_g...
class SkroutzApi::Resource include SkroutzApi::Parsing attr_accessor :attributes, :client def initialize(attributes, client) @attributes = attributes @client = client end def resource_prefix @resource_prefix ||= self.class.to_s.demodulize.downcase.pluralize end protected def respond_to?...
Add possibility to both use guest and password authentication to TC
require 'dotenv' Dotenv.load require 'dashing' configure do set :auth_token, 'YOUR_AUTH_TOKEN' helpers do def protected! # Put any authentication code you want in here. # This method is run before accessing any resource. end end end map Sinatra::Application.assets_prefix do run Sinatra::Ap...
require 'dotenv' Dotenv.load require 'dashing' configure do set :auth_token, 'YOUR_AUTH_TOKEN' helpers do def protected! # Put any authentication code you want in here. # This method is run before accessing any resource. end end end map Sinatra::Application.assets_prefix do run Sinatra::Ap...
Rename log file to wink.log, which makes more sense
require 'rubygems' require 'sinatra' Sinatra::Application.default_options.merge!( :run => false, :env => ENV['RACK_ENV'], :raise_errors => true, :views => File.join(File.dirname(__FILE__), 'views') ) log = File.new("sinatra.log", "a") STDOUT.reopen(log) STDERR.reopen(log) root_dir = File.dirname(__FILE__) $:....
require 'rubygems' require 'sinatra' Sinatra::Application.default_options.merge!( :run => false, :env => ENV['RACK_ENV'], :raise_errors => true, :views => File.join(File.dirname(__FILE__), 'views') ) log = File.new("wink.log", "a") STDOUT.reopen(log) STDERR.reopen(log) root_dir = File.dirname(__FILE__) $:.uns...
Add unit tests for group_sets_api
require 'test_helper' class GroupSetsApiTest < ActiveSupport::TestCase include Rack::Test::Methods include TestHelpers::AuthHelper include TestHelpers::JsonHelper include TestHelpers::TestFileHelper def app Rails.application end end
Use SpecInfra command to check directory exists
require 'serverkit/resources/base' module Serverkit module Resources class Goget < Base attribute :url, required: true, type: String # @note Override def apply run_command("go get -u #{url}") end # @note Override def check Dir.exists?("#{ENV['GOPATH']}/src/#{...
require 'serverkit/resources/base' module Serverkit module Resources class Goget < Base attribute :url, required: true, type: String # @note Override def apply run_command("go get -u #{url}") end # @note Override def check go_package_dir_path = "#{ENV['GOPATH...
Add lib/portability to search path
require 'bundler/setup' require 'turnip/rspec' require 'reportability' Dir.glob("spec/lib/**/*_steps.rb") { |f| load f, true } $LOAD_PATH << File.expand_path('../../lib', __FILE__) # the gem's lib dir
require 'bundler/setup' require 'turnip/rspec' require 'reportability' Dir.glob("spec/lib/**/*_steps.rb") { |f| load f, true } $LOAD_PATH << File.expand_path('../../lib', __FILE__) # the gem's lib dir $LOAD_PATH << File.expand_path('../../lib/reportability', __FILE__) # the gem's lib dir
Call DataMapper.finalize after model definition
require 'dm-core/spec/setup' require 'dm-core/spec/lib/adapter_helpers' require 'dm-validations' require 'dm-types' require 'dm-migrations' SPEC_ROOT = Pathname(__FILE__).dirname Pathname.glob((SPEC_ROOT + 'fixtures/**/*.rb').to_s).each { |file| require file } Pathname.glob((SPEC_ROOT + 'integration/shared/**/*.rb')....
require 'dm-core/spec/setup' require 'dm-core/spec/lib/adapter_helpers' require 'dm-validations' require 'dm-types' require 'dm-migrations' SPEC_ROOT = Pathname(__FILE__).dirname Pathname.glob((SPEC_ROOT + 'fixtures/**/*.rb').to_s).each { |file| require file } Pathname.glob((SPEC_ROOT + 'integration/shared/**/*.rb')....
Enable both `should` and `expect` in RSpec
require 'griddler/testing' require 'griddler/sendgrid' require 'action_dispatch' RSpec.configure do |config| config.treat_symbols_as_metadata_keys_with_true_values = true config.run_all_when_everything_filtered = true config.order = 'random' config.include Griddler::Testing end
require 'griddler/testing' require 'griddler/sendgrid' require 'action_dispatch' RSpec.configure do |config| config.treat_symbols_as_metadata_keys_with_true_values = true config.run_all_when_everything_filtered = true config.order = 'random' config.include Griddler::Testing config.expect_with(:rspec) do |c| ...
Remove seemingly unused options hash.
require 'mtgox/version' module MtGox module Configuration # An array of valid keys in the options hash when configuring a {MtGox::Client} VALID_OPTIONS_KEYS = [ :commission, :key, :secret, ] DEFAULT_COMMISSION = 0.0065.freeze attr_accessor *VALID_OPTIONS_KEYS # When this ...
require 'mtgox/version' module MtGox module Configuration # An array of valid keys in the options hash when configuring a {MtGox::Client} VALID_OPTIONS_KEYS = [ :commission, :key, :secret, ] DEFAULT_COMMISSION = 0.0065.freeze attr_accessor *VALID_OPTIONS_KEYS # When this ...
Write migration code for songs table
class CreateSongs < ActiveRecord::Migration def change end end
class CreateSongs < ActiveRecord::Migration def change create_table :songs do |t| t.references :user t.string :title, null: false, limit: 256 t.text :content, null: false t.timestamps null: false end end end
Add .pre for next release
# This file is maintained by a herd of rabid monkeys with Rakes. module EY class CloudClient VERSION = '1.0.12' end end # Please be aware that the monkeys like tho throw poo sometimes.
# This file is maintained by a herd of rabid monkeys with Rakes. module EY class CloudClient VERSION = '1.0.13.pre' end end # Please be aware that the monkeys like tho throw poo sometimes.
Allow 'in' queries is passing an array of values
module ContentfulModel module ChainableQueries def self.included(base) base.extend ClassMethods base.class_eval do attr_accessor :query end end module ClassMethods def all raise ArgumentError, "You need to set self.content_type in your model class" if @content_type...
module ContentfulModel module ChainableQueries def self.included(base) base.extend ClassMethods base.class_eval do attr_accessor :query end end module ClassMethods def all raise ArgumentError, "You need to set self.content_type in your model class" if @content_type...
Test for equality with embedded NUL chars
require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/fixtures/classes.rb' require File.dirname(__FILE__) + '/shared/equal_value.rb' describe "String#==" do it_behaves_like(:string_equal_value, :==) end describe "String#==" do it "returns false if obj does not respond to to_str"...
require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/fixtures/classes.rb' require File.dirname(__FILE__) + '/shared/equal_value.rb' describe "String#==" do it_behaves_like(:string_equal_value, :==) end describe "String#==" do it "returns false if obj does not respond to to_str"...
Delete pictures, when galleries are deleted.
class Gallery < ActiveRecord::Base has_many :pictures after_initialize do if new_record? self.slug ||= Base64.encode64(UUIDTools::UUID.random_create)[0..7] end end end
class Gallery < ActiveRecord::Base has_many :pictures, dependent: :destroy after_initialize do if new_record? self.slug ||= Base64.encode64(UUIDTools::UUID.random_create)[0..7] end end end
Add methods to check which environment we are running in
require "instana/version" require 'instana/logger' require "instana/util" module Instana class << self attr_accessor :agent attr_accessor :collectors attr_accessor :tracer attr_accessor :processor attr_accessor :config attr_accessor :logger attr_accessor :pid ## # setup # ...
require "instana/version" require 'instana/logger' require "instana/util" module Instana class << self attr_accessor :agent attr_accessor :collectors attr_accessor :tracer attr_accessor :processor attr_accessor :config attr_accessor :logger attr_accessor :pid ## # setup # ...
Update ownCloud detector to also cover 6.*
module Versionator module Detector # Detects {ownCloud}[http://owncloud.org/]. class Owncloud < Base set :app_name, "ownCloud" set :project_url, "https://owncloud.org/" set :project_download_url, "https://owncloud.org/install/" set :detect_dirs, %w{3rdparty apps core lib settings} ...
module Versionator module Detector # Detects {ownCloud}[http://owncloud.org/]. class Owncloud < Base set :app_name, "ownCloud" set :project_url, "https://owncloud.org/" set :project_download_url, "https://owncloud.org/install/" set :detect_dirs, %w{3rdparty apps core lib settings} ...
Add a real gem description
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'mlb_gameday/version' Gem::Specification.new do |spec| spec.name = "mlb_gameday" spec.version = MLBGameday::VERSION spec.authors = ["Steven Hoffman"] spec.email ...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'mlb_gameday/version' Gem::Specification.new do |spec| spec.name = "mlb_gameday" spec.version = MLBGameday::VERSION spec.authors = ["Steven Hoffman"] spec.email ...
Access node attributes in a consistent manner
# # Cookbook Name:: drupal-codeception # Attributes:: default # # Copyright (C) 2014 Alex Knoll Alex@AlexKnoll.com # # 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.or...
# # Cookbook Name:: drupal-codeception # Attributes:: default # # Copyright (C) 2014 Alex Knoll Alex@AlexKnoll.com # # 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.or...
Fix up feedback table name in migration 067.
class RemoveBlogIds < ActiveRecord::Migration class Content < ActiveRecord::Base set_inheritance_column :bogustype end class Feedback < ActiveRecord::Base end class Sidebar < ActiveRecord::Base end def self.up if adapter_name == 'PostgreSQL' indexes(:contents).each do |index| if i...
class RemoveBlogIds < ActiveRecord::Migration class Content < ActiveRecord::Base set_inheritance_column :bogustype end class Feedback < ActiveRecord::Base set_table_name "feedback" end class Sidebar < ActiveRecord::Base end def self.up if adapter_name == 'PostgreSQL' indexes(:contents...
Add param to control rescheduling the same job
class ReleaseEpisodesJob < ActiveJob::Base queue_as :feeder_default def perform ActiveRecord::Base.connection_pool.with_connection do begin podcasts_to_release.tap do |podcasts| podcasts.each { |p| p.publish! } end ensure ReleaseEpisodesJob.set(wait: release_check...
class ReleaseEpisodesJob < ActiveJob::Base queue_as :feeder_default def perform(reschedule = false) ActiveRecord::Base.connection_pool.with_connection do begin podcasts_to_release.tap do |podcasts| podcasts.each { |p| p.publish! } end ensure if reschedule ...
Add the necessary profile steps
Given /^the following profiles? (?:are|is) defined:$/ do |profiles| create_file('cucumber.yml', profiles) end Then /^the (.*) profile should be used$/ do |profile| last_stdout.should =~ /Using the #{profile} profile/ end Then /^exactly these files should be loaded:\s*(.*)$/ do |files| last_stdout.scan(/^ \* (....
Work around Dir.mktmpdir problems on Windows
require "minitest_helper" require "airbrussh/log_file_formatter" require "tempfile" class Airbrussh::LogFileFormatterTest < Minitest::Test def setup @file = Tempfile.new("airbrussh-test-") @file.puts("Existing data") @file.close @formatter = Airbrussh::LogFileFormatter.new(@file.path) end def te...
require "minitest_helper" require "airbrussh/log_file_formatter" require "fileutils" require "tempfile" class Airbrussh::LogFileFormatterTest < Minitest::Test def setup @file = Tempfile.new("airbrussh-test-") @file.puts("Existing data") @file.close @formatter = Airbrussh::LogFileFormatter.new(@file.p...
Remove default text to display in parameters
module Volunteermatch module API module SearchOrganizations def search_organizations(parameters = {}) raise ArgumentError, 'location needs to be defined' if parameters[:location].nil? || parameters[:location].empty? parameters[:location] = parameters[:location] || nil parameters[:fie...
module Volunteermatch module API module SearchOrganizations def search_organizations(parameters = {}) raise ArgumentError, 'location needs to be defined' if parameters[:location].nil? || parameters[:location].empty? parameters[:location] = parameters[:location] || nil call(:searchOrg...
Make sure that $ORBIT_KEY is set
# Apache 2.0 License # # Copyright (c) 2016 Sebastian Katzer, appPlant GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to...
# Apache 2.0 License # # Copyright (c) 2016 Sebastian Katzer, appPlant GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to...
Include all Errnos as failures
class Notifier < Struct.new(:url, :host_with_port, :rubygem, :version, :api_key) def payload rubygem.payload(version, host_with_port).to_json end def authorization Digest::SHA2.hexdigest(rubygem.name + version.number + api_key) end def perform timeout(5) do RestClient.post url, ...
class Notifier < Struct.new(:url, :host_with_port, :rubygem, :version, :api_key) def payload rubygem.payload(version, host_with_port).to_json end def authorization Digest::SHA2.hexdigest(rubygem.name + version.number + api_key) end def perform timeout(5) do RestClient.post url, ...
Set sanitizer_vendor to correct constant.
require "rails/deprecated_sanitizer/version" require "rails/deprecated_sanitizer/html-scanner" require "active_support/lazy_load_hooks" module Rails module DeprecatedSanitizer def full_sanitizer HTML::FullSanitizer end def link_sanitizer HTML::LinkSanitizer end def white_list_saniti...
require "rails/deprecated_sanitizer/version" require "rails/deprecated_sanitizer/html-scanner" require "active_support/lazy_load_hooks" module Rails module DeprecatedSanitizer def full_sanitizer HTML::FullSanitizer end def link_sanitizer HTML::LinkSanitizer end def white_list_saniti...
Add data migration to fix first_published_at values
Document.where( id: Edition.where(state: :scheduled).select(:document_id) ).all.each do |document| next unless document.published_edition.nil? puts "Saving draft for #{document.id} (content_id: #{document.content_id})" Whitehall::PublishingApi.save_draft(document.pre_publication_edition) end
Stop displaying errors for code blocks with no language.
module ApplicationHelper def body_class %|#{controller.controller_name} #{controller.controller_name}-#{controller.action_name} #{@body_class}| end class HTMLwithPygments < Redcarpet::Render::HTML def block_code(code, language) if Pygments::Lexer.find_by_alias(language) sha = Digest::SHA1.h...
module ApplicationHelper def body_class %|#{controller.controller_name} #{controller.controller_name}-#{controller.action_name} #{@body_class}| end class HTMLwithPygments < Redcarpet::Render::HTML def block_code(code, language) sha = Digest::SHA1.hexdigest(code) Rails.cache.fetch ["code", lan...
Allow superusers to access private questions w/ a group
class QuestionPermission < Prequel::Record column :id, :integer column :secret, :string column :question_id, :integer column :user_id, :integer belongs_to :question belongs_to :user validates_presence_of :question_id def after_initialize return unless question = Question.find(:secret => secret) ...
class QuestionPermission < Prequel::Record column :id, :integer column :secret, :string column :question_id, :integer column :user_id, :integer belongs_to :question belongs_to :user validates_presence_of :question_id def after_initialize return unless question = Question.find(:secret => secret) ...
Add License information to gemspec
# -*- encoding: utf-8 -*- require File.expand_path('../lib/aloha/rails/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ['Kurakin Alexander'] gem.email = 'kuraga333@mail.ru' gem.description = 'Aloha Editor in Rails' gem.summary = 'Provides the Aloha Editor for your Rails ...
# -*- encoding: utf-8 -*- require File.expand_path('../lib/aloha/rails/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ['Kurakin Alexander'] gem.email = 'kuraga333@mail.ru' gem.description = 'Aloha Editor in Rails' gem.summary = 'Provides the Aloha Editor for your Rails ...
Make console integration spec more specific
require "spec_helper" describe "A request sent to CloudStack for console access", :vcr do let(:config_hash) do { url: CONFIG['url'], api_key: CONFIG['api_key'], secret_key: CONFIG['secret_key'] } end let(:client) do StackerBee::Client.new(config_hash) end let(:vm) { ...
require "spec_helper" describe "A request sent to CloudStack for console access", :vcr do let(:config_hash) do { url: CONFIG['url'], api_key: CONFIG['api_key'], secret_key: CONFIG['secret_key'] } end let(:client) do StackerBee::Client.new(config_hash) end let(:vm) { ...
Use Device provided `before_action :authenticate_user!` instead of `user_signed_in?` from the Authentication concern.
class ProfileController < ArticlesController before_action :require_sign_in def edit end def update current_user.update_goal!(params[:goal_statement], params[:goal_deadline]) flash[:success] = I18n.t('profile.update.save_success_message') render :edit end private def require_sign_in r...
class ProfileController < ArticlesController before_action :authenticate_user! def edit end def update current_user.update_goal!(params[:goal_statement], params[:goal_deadline]) flash[:success] = I18n.t('profile.update.save_success_message') render :edit end end
Test the functionality of the DocumentQueue.
require "test_helper" require "elasticsearch/document_queue" require "elasticsearch/bulk_index_worker" class DocumentQueueTest < MiniTest::Unit::TestCase def sample_document_hashes %w(foo bar baz).map do |slug| {:link => "/#{slug}", :title => slug.capitalize} end end def test_can_queue_documents_i...
Use multipackage installs in the test recipe
apt_update 'update' case node['platform_family'] when 'debian' %w(libxml2 libxml2-dev libxslt1-dev).each do |pkg| package pkg do action :install end end when 'rhel' %w(gcc make ruby-devel libxml2 libxml2-devel libxslt libxslt-devel).each do |pkg| package pkg do action :install end e...
apt_update 'update' case node['platform_family'] when 'debian' package %w(libxml2 libxml2-dev libxslt1-dev) when 'rhel' package %w(gcc make ruby-devel libxml2 libxml2-devel libxslt libxslt-devel) end package 'curl'
Add multi_select prompt pagination of disabled items example
# frozen_string_literal: true require_relative "../lib/tty-prompt" prompt = TTY::Prompt.new numbers = [ {name: '1', disabled: 'out'}, '2', {name: '3', disabled: 'out'}, '4', '5', {name: '6', disabled: 'out'}, '7', '8', '9', {name: '10', disabled: 'out'} ] answer = prompt.multi_select('Which lett...
Add compare param to diff routes
require 'sinatra/base' require 'sinatra/respond_with' require 'llt/review' class Api < Sinatra::Base register Sinatra::RespondWith get '/:type/diff' do gold = Array(params[:gold]) rev = Array(params[:reviewable]) klass = params[:type] # return an error if klass is neither treebank nor Alignment ...
require 'sinatra/base' require 'sinatra/respond_with' require 'llt/review' class Api < Sinatra::Base register Sinatra::RespondWith get '/:type/diff' do gold = Array(params[:gold]) rev = Array(params[:reviewable]) comp_param = params[:compare] comparables = comp_param ? Array(comp_param).map(&:to...
Save site object in Navigator class for subclassing use.
module Mill class Navigator class Item attr_accessor :uri attr_accessor :title def initialize(uri:, title: nil) @uri = Addressable::URI.parse(uri) @title = title end end def initialize(items: []) @items = Hash[ items.map do |uri, title| ...
module Mill class Navigator class Item attr_accessor :uri attr_accessor :title def initialize(uri:, title: nil) @uri = Addressable::URI.parse(uri) @title = title end end def initialize(items: [], site: nil) @items = Hash[ items.map do |uri, title...
Add two dependencies for RSpec
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'fourchan_kit/version' Gem::Specification.new do |spec| spec.name = "fourchan_kit" spec.version = FourchanKit::VERSION spec.authors = ["lauritzsh"] spec.email ...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'fourchan_kit/version' Gem::Specification.new do |spec| spec.name = "fourchan_kit" spec.version = FourchanKit::VERSION spec.authors = ["lauritzsh"] spec.email ...
Change sudo su to sudo -u.
# Deploy the code by copying it up to the server so the target servers don't need # to have access to the git repo set :deploy_via, :copy set :copy_strategy, :export set :copy_cache, false _cset(:sake_path) { "./framework/sake" } # The migrate task takes care of doing the dev/build namespace :deploy do task :migrat...
# Deploy the code by copying it up to the server so the target servers don't need # to have access to the git repo set :deploy_via, :copy set :copy_strategy, :export set :copy_cache, false _cset(:sake_path) { "./framework/sake" } # The migrate task takes care of doing the dev/build namespace :deploy do task :migrat...
Add units to teaching period serializer
class TeachingPeriodSerializer < ActiveModel::Serializer attributes :id, :period, :year, :start_date, :end_date, :active_until, :active, :breaks def active object.active_until > DateTime.now end end
class TeachingPeriodSerializer < ActiveModel::Serializer attributes :id, :period, :year, :start_date, :end_date, :active_until, :active, :breaks, :units def active object.active_until > DateTime.now end end
Add ssh_username variable when execute terraform
module CloudConductor class Terraform class Parent attr_accessor :modules attr_reader :output def initialize(cloud) @cloud = cloud @modules = [] case cloud.type when 'aws' @variables = %w(bootstrap_expect aws_access_key aws_secret_key aws_region ssh_ke...
module CloudConductor class Terraform class Parent attr_accessor :modules attr_reader :output def initialize(cloud) @cloud = cloud @modules = [] case cloud.type when 'aws' @variables = %w(bootstrap_expect aws_access_key aws_secret_key aws_region ssh_ke...
Fix for SimpleCov require minitest after simplecov
$:.unshift(File.join(File.dirname(__FILE__),'..','lib')) require 'rubygems' require 'bundler' require 'minitest/autorun' Bundler.require(:default, :development) unless RUBY_VERSION =~ /^1\.8/ SimpleCov.start end FakeWeb.allow_net_connect = false def register_fixture(api_call, fixture_name=nil) if fixture_name...
$:.unshift(File.join(File.dirname(__FILE__),'..','lib')) require 'rubygems' require 'bundler' Bundler.require(:default, :development) require 'minitest/autorun' unless RUBY_VERSION =~ /^1\.8/ SimpleCov.start end FakeWeb.allow_net_connect = false def register_fixture(api_call, fixture_name=nil) if fixture_name....
Add Surf as a CI source
# http://github.com/surf-build/surf module Danger module CISource class Surf < CI def self.validates?(env) return ['SURF_REPO', 'SURF_NWO'].all? {|x| env[x]} end def supported_request_sources @supported_request_sources ||= [Danger::RequestSources::GitHub] end def i...
Fix ItemsHelper spec for latest changes.
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') include ItemsHelper describe ItemsHelper do before(:each) do Member.destroy_all end describe "item_tell_types" do it "should show comma-separated list of tell types" do item = Item.make(:best_in_slot => true, :rot => true) ...
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') include ItemsHelper describe ItemsHelper do before(:each) do Member.destroy_all end describe "item_tell_types" do it "should list multiple tell types" do item = Item.make(:best_in_slot => true, :rot => true) item_...
Remove symbolick links and replace for the path.
class RailsBackend::InstallGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) def create copy_applications_file '_navigation.html.erb' copy_applications_file '_footer.html.erb' copy_layout 'application.html.erb' copy_assets end private def copy_appli...
class RailsBackend::InstallGenerator < Rails::Generators::Base source_root File.expand_path('../../../../../app', __FILE__) def create copy_applications_file '_navigation.html.erb' copy_applications_file '_footer.html.erb' copy_layout 'application.html.erb' copy_assets end private def copy...
Use task name as recipe name in output
require 'chef' module Rake module DSL private def recipe(id, &block) namespace :chef do namespace :recipe do desc "Run chef rake task #{id}" task id do ::Chef::Config[:solo] = true @chef_client = ::Chef::Client.new @chef_client.run_ohai ...
require 'chef' module Rake module DSL private def recipe(id, &block) namespace :chef do namespace :recipe do desc "Run chef rake task #{id}" task id do ::Chef::Config[:solo] = true @chef_client = ::Chef::Client.new @chef_client.run_ohai ...
Fix bug with showing create merge request button while merge request are disabled in project settings
module CompareHelper def compare_to_mr_button? params[:from].present? && params[:to].present? && @repository.branch_names.include?(params[:from]) && @repository.branch_names.include?(params[:to]) && params[:from] != params[:to] && !@refs_are_same end def compare_mr_path new_projec...
module CompareHelper def compare_to_mr_button? @project.merge_requests_enabled && params[:from].present? && params[:to].present? && @repository.branch_names.include?(params[:from]) && @repository.branch_names.include?(params[:to]) && params[:from] != params[:to] && !@refs_are_...
Remove unused borrower generate functions
def generate_title_number title_number = Pxeger.new('^([A-Z]{0,3}[1-9][0-9]{0,5}|[0-9]{1,6}[ZT])$') title_number.generate end def generate_new_borrower_no_middle { forename: 'James', surname: 'Bond' } end def generate_new_borrower_with_middle { forename: 'James', middle_name: 'Hello', su...
def generate_title_number title_number = Pxeger.new('^([A-Z]{0,3}[1-9][0-9]{0,5}|[0-9]{1,6}[ZT])$') title_number.generate end def generate_new_borrower_no_middle { forename: 'James', surname: 'Bond' } end def generate_new_borrower_with_middle { forename: 'James', middle_name: 'Hello', su...
Add TomDoc documentation to the Interactor::Organizer module
module Interactor module Organizer def self.included(base) base.class_eval do include Interactor extend ClassMethods include InstanceMethods end end module ClassMethods def organize(*interactors) @organized = interactors.flatten end def orga...
module Interactor # Public: Interactor::Organizer methods. Because Interactor::Organizer is a # module, custom Interactor::Organizer classes should include # Interactor::Organizer rather than inherit from it. # # Examples # # class MyOrganizer # include Interactor::Organizer # # organizer ...
Change instructions on actions in README.
class <%= class_name %>Table < TableCloth::Base # Define columns with the #column method # column :name, :email # Columns can be provided a block # # column :name do |object| # object.downcase # end # # Columns can also have conditionals if you want. # The conditions are checked against the table...
class <%= class_name %>Table < TableCloth::Base # To include actions on this table, uncomment this line # include TableCloth::Extensions::Actions # Define columns with the #column method # column :name, :email # Columns can be provided a block # # column :name do |object| # object.downcase # end ...
Add updated schema to specs
require 'spec_helper' require 'rspec_api_documentation/dsl' resource "Root" do header "Accept", "application/hal+json" get "/" do example "Getting the root resource" do do_request response_body.should be_json_eql({ :_links => { :orders => { :href => "/orders" } }, ...
require 'spec_helper' require 'rspec_api_documentation/dsl' resource "Root" do header "Accept", "application/hal+json" get "/" do example "Getting the root resource" do do_request response_body.should be_json_eql({ :_links => { :orders => { :href => "/orders" } }, ...
Add spec for orders resources
require 'rails_helper' RSpec.describe 'Orders', type: :request do describe 'GET /orders' do it 'successful request' do get '/api/orders' expect(response).to have_http_status(200) end end describe 'GET /orders/:id' do it 'successful request' do customer = Customer.create(first_name:...
Add some tests for setting group preferences.
require "spec_helper" describe "Group prefs" do def get_field(name) find_field(I18n.t("formtastic.labels.group_pref.#{name}")) end context "as a group member" do include_context "signed in as a group member" describe "editing the group preferences" do it "should refuse" do visit edit...
Fix for a bug in Google Authenticator OTP check
require 'test_helper' class GoogleAuthenticatorTest < ActionDispatch::IntegrationTest test "should not be able to authenticate without otp" do u = Factory.build(:user) u.require_ga_otp = true u.generate_ga_otp_secret u.save! # Authenticating without OTP will fail post user_session_path, :use...
Add rake to dev deps
Gem::Specification.new do |s| s.name = "sprockets" s.version = "2.0.0.beta.6" s.summary = "Rack-based asset packaging system" s.description = "Sprockets is a Rack-based asset packaging system that concatenates and serves JavaScript, CoffeeScript, CSS, LESS, Sass, and SCSS." s.files = Dir["README.md", "LICENS...
Gem::Specification.new do |s| s.name = "sprockets" s.version = "2.0.0.beta.6" s.summary = "Rack-based asset packaging system" s.description = "Sprockets is a Rack-based asset packaging system that concatenates and serves JavaScript, CoffeeScript, CSS, LESS, Sass, and SCSS." s.files = Dir["README.md", "LICENS...
Fix class name for Devise::Authenticatable
require 'devise/strategies/authenticatable' module Devise module Strategies class LdapAuthenticatable < Autheneticatable # Tests whether the returned resource exists in the database and the # credentials are valid. If the resource is in the database and the credentials # are valid, the user i...
require 'devise/strategies/authenticatable' module Devise module Strategies class LdapAuthenticatable < Authenticatable # Tests whether the returned resource exists in the database and the # credentials are valid. If the resource is in the database and the credentials # are valid, the user is...
Add sort by teacher name alphabetically on teacher show page
class TeachersController < ApplicationController def index @teachers = Teacher.all end def show @teacher = Teacher.find(params[:id]) end def destroy @teacher = Teacher.find(params[:id]) @teacher.destroy redirect_to teachers_path end def edit @teacher = Teacher.find(params[:i...
class TeachersController < ApplicationController def index @teachers = Teacher.all.sort_by &:full_name end def show @teacher = Teacher.find(params[:id]) end def destroy @teacher = Teacher.find(params[:id]) @teacher.destroy redirect_to teachers_path end def edit @teacher = Te...
Move the desc one level up
namespace :dev do task :cache do desc 'Toggle development mode caching on/off' if File.exist? 'tmp/caching-dev.txt' File.delete 'tmp/caching-dev.txt' puts 'Development mode is no longer being cached.' else FileUtils.touch 'tmp/caching-dev.txt' puts 'Development mode is now being c...
namespace :dev do desc 'Toggle development mode caching on/off' task :cache do if File.exist? 'tmp/caching-dev.txt' File.delete 'tmp/caching-dev.txt' puts 'Development mode is no longer being cached.' else FileUtils.touch 'tmp/caching-dev.txt' puts 'Development mode is now being cach...
Allow sonarqube addon on external PRs
module Travis module Scheduler module Serialize class Worker module Config class Addons < Struct.new(:config) SAFE = %i( apt apt_packages apt_sources browserstack firefox hostname ...
module Travis module Scheduler module Serialize class Worker module Config class Addons < Struct.new(:config) SAFE = %i( apt apt_packages apt_sources browserstack firefox hostname ...
Stop require resource model and fix namespace
require 'api/job_instance_resource' class Kuroko2::Api::JobInstancesController < Kuroko2::Api::ApplicationController include Garage::RestfulActions validates :create do hash :env, description: 'Env variables to launch an instance' do |env| env.all? { |_, v| v.is_a?(String) } end end private d...
class Kuroko2::Api::JobInstancesController < Kuroko2::Api::ApplicationController include Garage::RestfulActions validates :create do hash :env, description: 'Env variables to launch an instance' do |env| env.all? { |_, v| v.is_a?(String) } end end private def require_resources protect_res...
Remove usage of RubyGems in newly added SQLServer adapter
require DataMapper.root / 'lib' / 'dm-core' / 'adapters' / 'data_objects_adapter' gem 'do_sqlserver', '~>0.0.1' require 'do_sqlserver' module DataMapper module Adapters class SqlserverAdapter < DataObjectsAdapter module SQL #:nodoc: private # TODO: document # @api private ...
require DataMapper.root / 'lib' / 'dm-core' / 'adapters' / 'data_objects_adapter' require 'do_sqlserver' module DataMapper module Adapters class SqlserverAdapter < DataObjectsAdapter module SQL #:nodoc: private # TODO: document # @api private def supports_default_values? #...
Add task for disabling system comments
# encoding: utf-8 #-- # Copyright (C) 2013 Gitorious AS # # This program 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, either version 3 of the License, or # (at your option) any later versio...
Use factory to create test member
require 'spec_helper' describe MembersController do describe "GET 'index'" do it "returns http success" do get 'index' response.should be_success end end describe "GET 'show'" do it "returns http success" do get 'show', :id => 1 response.should be_success end end end
require 'spec_helper' describe MembersController do describe "GET 'index'" do it "returns http success" do get 'index' response.should be_success end end describe "GET 'show'" do it "returns http success" do @member = FactoryGirl.create :member get 'show', :id => @member.mem...
Change render from login to new
class SessionsController < ApplicationController def new render :login end def create @user = User.find_by(email: params[:email]) if @user && @user.authenticate(params[:password]) login @user redirect_to root_path else flash[:notice] = "Invalid email or password" redi...
class SessionsController < ApplicationController def new render :new end def create @user = User.find_by(email: params[:email]) if @user && @user.authenticate(params[:password]) login @user redirect_to root_path else flash[:notice] = "Invalid email or password" redire...
Sort upgrades by server name in upgrades/index
class UpgradesController < InheritedResources::Base respond_to :html, :js include SortHelpers protected def sort_column_prefix "upgrades." end helper_method :sort_column, :sort_direction, :sort_column_prefix end
class UpgradesController < InheritedResources::Base respond_to :html, :js include SortHelpers protected def sort_column_prefix "upgrades." end helper_method :sort_column, :sort_direction, :sort_column_prefix def collection @upgrades ||= end_of_association_chain.includes(:server).order("servers...
Improve robustness of warden password strategy
Dir.glob(File.dirname(__FILE__) + '/warden_plugin/**/*.rb').each { |f| require f } module SinatraMore module WardenPlugin def self.registered(app) app.use Warden::Manager do |manager| manager.default_strategies :password manager.failure_app = app end app.helpers SinatraMore::Wa...
Dir.glob(File.dirname(__FILE__) + '/warden_plugin/**/*.rb').each { |f| require f } module SinatraMore module WardenPlugin def self.registered(app) app.use Warden::Manager do |manager| manager.default_strategies :password manager.failure_app = app end app.helpers SinatraMore::Wa...
Read bing api key from ENV to be Heroku friendly
require 'yaml' module WhosDatedWho class BingClient API_KEY = YAML.load_file( File.expand_path('~/.whos_dated_who.yml'))[:bing_api_key] def initialize(api_key=API_KEY) @api_key = api_key @client = Bing.new(@api_key, 10, 'Web') end def search(query) @client.search(query) end e...
require 'yaml' module WhosDatedWho class BingClient API_KEY = ENV['BING_API_KEY'] || YAML.load_file( File.expand_path('~/.whos_dated_who.yml'))[:bing_api_key] def initialize(api_key=API_KEY) @api_key = api_key @client = Bing.new(@api_key, 10, 'Web') end def search(query) @cli...
Fix to work in Rails 4.x
module S3MultipartUpload class File attr_accessor :url, :file_size, :mime_type def part(starts, ends) end def split_into_parts(part_size) boundaries = Range.new(0, file_size).step(part_size).tap do |_| _.push(file_size) unless _.last == file_size end starts = boundaries[0....
module S3MultipartUpload class File attr_accessor :url, :file_size, :mime_type def part(starts, ends) end def split_into_parts(part_size) boundaries = Range.new(0, file_size).step(part_size).to_a.tap do |_| _.push(file_size) unless _.last == file_size end starts = boundari...
Extend attachment cleanup to all objects
namespace :attachments do desc "Clean attachments older than 2 years" task :cleanup => :environment do Invoice.where("pdf_updated_at < ?", 2.years.ago).each do |i| i.pdf.clear i.save end end end
namespace :attachments do desc "Clean attachments older than 2 years" task :cleanup => :environment do delay = 2.years.ago Invoice.where("pdf_updated_at < ?", delay).each { |i| i.pdf.clear; i.save } Subscription.where("pdf_updated_at < ?", delay).each { |i| i.pdf.clear; i.save } CachedDocument.whe...
Manage case for nomenclature change output default value
module ParsePgArray def parse_array(attribute) # byebug attr = read_attribute(attribute) return [] unless attr.present? attr.map(&:to_s) end end
module ParsePgArray def parse_array(attribute) attr = read_attribute(attribute) # --- []\n is the default value for tag_list in NomenclatureChange::Output return [] unless attr.present? return [] if attr.is_a?(String) && attr.match(/--- \[\]\n/).present? attr.map(&:to_s) end end
Add simple test for finding items by role
# frozen_string_literal: true require_relative '../test_helper' require 'atspi_app_driver' describe 'test driving a dummy application' do before do @driver = AtspiAppDriver.new('dummy', app_file: 'test/bin/dummy') @driver.boot end it 'starts and can be quit with Ctrl-q' do @driver.press_ctrl_q ...
# frozen_string_literal: true require_relative '../test_helper' require 'atspi_app_driver' describe 'test driving a dummy application' do before do @driver = AtspiAppDriver.new('dummy', app_file: 'test/bin/dummy') @driver.boot end it 'starts and can be quit with Ctrl-q' do @driver.press_ctrl_q ...
Add owner_id and owner_name to playlists table
class CreatePlaylists < ActiveRecord::Migration[4.2] def self.up create_table :playlists, id: :uuid, default: "uuid_generate_v4()", force: true do |t| t.string :provider , null: false t.string :identifier , null: false t.string :url , null: false t.string :title , nul...
class CreatePlaylists < ActiveRecord::Migration[4.2] def self.up create_table :playlists, id: :uuid, default: "uuid_generate_v4()", force: true do |t| t.string :provider , null: false t.string :identifier , null: false t.string :owner_id t.string :owner_name t.string :url ...
Enable simplecov for rom gem specs
require 'pathname' SPEC_ROOT = root = Pathname(__FILE__).dirname require 'rom/core' Dir[root.join('support/*.rb').to_s].each do |f| require f end Dir[root.join('shared/*.rb').to_s].each do |f| require f end # Namespace holding all objects created during specs module Test def self.remove_constants constant...
require 'pathname' SPEC_ROOT = root = Pathname(__FILE__).dirname if RUBY_ENGINE == 'ruby' && ENV['COVERAGE'] == 'true' require 'yaml' rubies = YAML.load(File.read(SPEC_ROOT.join('../.travis.yml')))['rvm'] latest_mri = rubies.select { |v| v =~ /\A\d+\.\d+.\d+\z/ }.max if RUBY_VERSION == latest_mri require...
Change SimpleCov behaviour to stop reporting
if ENV['COVERAGE'] require 'simplecov' SimpleCov.profiles.define 'gem' do add_filter '/spec/' add_filter '/vendor/' add_group 'Libraries', '/lib/' end SimpleCov.start 'gem' end $:.unshift File.expand_path("../../lib", __FILE__) require 'rspec' require 'rspec/mocks' require 'json_spec' require '...
# SimpleCov must run _first_ according to its README if ENV['COVERAGE'] require 'simplecov' # monkey-patch to prevent SimpleCov from reporting coverage percentage class SimpleCov::Formatter::HTMLFormatter def output_message(_message) nil end end SimpleCov.profiles.define 'gem' do add_filte...
Use Helper::Exec instead of Helper::Ssh
require 'serverspec' require 'pathname' PROJECT_ROOT = (Pathname.new(File.dirname(__FILE__)) + '..').expand_path Dir[PROJECT_ROOT.join("spec/support/**/*.rb")].each { |file| require(file) } module Serverspec module Backend class Ssh def do_check(cmd) if cmd =~ /invalid/ { :s...
require 'serverspec' require 'pathname' PROJECT_ROOT = (Pathname.new(File.dirname(__FILE__)) + '..').expand_path Dir[PROJECT_ROOT.join("spec/support/**/*.rb")].each { |file| require(file) } module Serverspec module Backend class Exec def do_check(cmd) if cmd =~ /invalid/ { :...
Make sure assets can be deleted.
class Backend::AssetsController < Backend::BaseController before_action :find_model, only: [:edit, :update, :destroy] before_action -> { breadcrumb.add t('b.files'), backend_assets_path } def index @assets = Asset.order('id DESC') end def new @model = Asset.new end def create @model = Asset...
class Backend::AssetsController < Backend::BaseController before_action :find_model, only: [:show, :edit, :update, :destroy] before_action -> { breadcrumb.add t('b.files'), backend_assets_path } def index @assets = Asset.order('id DESC') end def new @model = Asset.new end def create @model ...
Use count instead of reject!..size
# encoding: utf-8 module RuboCop module Cop module Metrics # This cop checks if the length a method exceeds some maximum value. # Comment lines can optionally be ignored. # The maximum allowed length is configurable. class MethodLength < Cop include OnMethodDef include Cod...
# encoding: utf-8 module RuboCop module Cop module Metrics # This cop checks if the length a method exceeds some maximum value. # Comment lines can optionally be ignored. # The maximum allowed length is configurable. class MethodLength < Cop include OnMethodDef include Cod...
Add new detailed guidance categories
class MainstreamCategory < ActiveRecord::Base; end class EditionMainstreamCategory < ActiveRecord::Base; end class Edition < ActiveRecord::Base; end class DetailedGuide < Edition belongs_to :primary_mainstream_category, class_name: "MainstreamCategory" end class UpdateMainstreamCategories < ActiveRecord::Migration ...
Refactor filtering step to look at items
Given(/^a collection of cases exist$/) do stub_case_collection_api_request end Then(/^I can get a list of all merger inquiries$/) do visit finder_path('cma-cases') page.should have_content('2 cases') within '.results .document:nth-child(1)' do page.should have_link('HealthCorp / DrugInc merger inquiry') ...
Given(/^a collection of cases exist$/) do stub_case_collection_api_request end Then(/^I can get a list of all merger inquiries$/) do visit finder_path('cma-cases') page.should have_content('2 cases') page.should have_css('.results .document', count: 2) within '.results .document:nth-child(1)' do page.sh...
Add a spec for __LINE__ in eval
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes', __FILE__) describe "Kernel#eval" do before :each do @cache = tmp("eval_cache.rbc") name = fixture(__FILE__, "eval_cache.rb") KernelSpecs.cache_file name, @cache end after :each do rm_r @cac...
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes', __FILE__) describe "Kernel#eval" do before :each do @cache = tmp("eval_cache.rbc") name = fixture(__FILE__, "eval_cache.rb") KernelSpecs.cache_file name, @cache end after :each do rm_r @cac...
Remove Swift 5.1 from podspec swift versions
Pod::Spec.new do |s| s.name = 'SourceKittenFramework' s.version = `make get_version` s.summary = 'An adorable little framework for interacting with SourceKit.' s.homepage = 'https://github.com/jpsim/SourceKitten' s.source = { git: s.homepage + '.g...
Pod::Spec.new do |s| s.name = 'SourceKittenFramework' s.version = `make get_version` s.summary = 'An adorable little framework for interacting with SourceKit.' s.homepage = 'https://github.com/jpsim/SourceKitten' s.source = { git: s.homepage + '.g...
Fix raise error on test due to bug of rails generator
require File.expand_path("../../test/dummy/config/environment.rb", __FILE__) ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)] require "rails/test_help" # Filter out Minitest backtrace while allowing backtrace from other libraries # to be shown. Minitest.backtrace_fi...
require File.expand_path("../../test/dummy/config/environment.rb", __FILE__) ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)] require "rails/test_help" require "rails/test_unit/reporter" # Filter out Minitest backtrace while allowing backtrace from other libraries #...
Return if no answer type
module SectionsAndQuestionsShared def self.append_features(base) super self.class_eval do def questionnaire self.questionnaire_part.root.questionnaire end def title lang=nil field = lang ? self.send(self.class.to_s.underscore.downcase+"_fields").find_by_language(lang) : ni...
module SectionsAndQuestionsShared def self.append_features(base) super self.class_eval do def questionnaire self.questionnaire_part.root.questionnaire end def title lang=nil field = lang ? self.send(self.class.to_s.underscore.downcase+"_fields").find_by_language(lang) : ni...
Fix error message in Sidekiq.
class AvatarPurgeWorker include Sidekiq::Worker sidekiq_options :queue => :high sidekiq_options :retry => false def perform(record_id,klass) _klass = klass.constantize record = _klass.find(record_id) versions = [] version_types = [:id] version_types << :email if record.respond_to?(...
class AvatarPurgeWorker include Sidekiq::Worker sidekiq_options :queue => :high sidekiq_options :retry => false def perform(record_id,klass) _klass = klass.constantize record = _klass.find(record_id) versions = [] version_types = [:id] version_types << :email if record.respond_to?(...
Update wording in test to match updates in form UI
require 'rails_helper' RSpec.feature 'Admin creates a plot' do context 'when logged in' do let(:user) { create(:user, :admin) } before do sign_in(user) create(:plant) end scenario 'providing valid plot attributes' do visit new_plot_path fill_in('Plot', with: 1) select(...
require 'rails_helper' RSpec.feature 'Admin creates a plot' do context 'when logged in' do let(:user) { create(:user, :admin) } before do sign_in(user) create(:plant) end scenario 'providing valid plot attributes' do visit new_plot_path fill_in('Plot', with: 1) select(...
Set admin attribute if we get it from the server.
require 'omniauth-oauth2' module OmniAuth module Strategies class Doorkeeper < OmniAuth::Strategies::OAuth2 # change the class name and the :name option to match your application name option :name, :adstage option :client_options, { :site => (ENV['ADSTAGE_ENDPOINT'] || "https://www.ads...
require 'omniauth-oauth2' module OmniAuth module Strategies class Adstage < OmniAuth::Strategies::OAuth2 # change the class name and the :name option to match your application name option :name, :adstage option :client_options, { :site => (ENV['ADSTAGE_ENDPOINT'] || "https://www.adstag...
Use ip automatically if public hostname is nil.
require 'net/ssh' require 'net/ssh/gateway' class Aerosol::Connection include Dockly::Util::DSL include Dockly::Util::Logger::Mixin logger_prefix '[aerosol connection]' dsl_attribute :user, :host, :jump, :use_private_ip default_value :use_private_ip, false def with_connection(&block) ensure_present! ...
require 'net/ssh' require 'net/ssh/gateway' class Aerosol::Connection include Dockly::Util::DSL include Dockly::Util::Logger::Mixin logger_prefix '[aerosol connection]' dsl_attribute :user, :host, :jump def with_connection(&block) ensure_present! :user, :host unless host.is_a? String host = ...
Add rake task to refresh oldest promo
namespace :frankiz do task :refresh_promo, [:promo] => :environment do |_, args| fkz = FrankizLdap.new fkz.crawl_promo(args[:promo]) end task :associate_accounts, [:promo] => :environment do |_, args| doubtful = 0 Account.where(frankiz_id: nil, promo: args[:promo], status: [0, 1]).each do |acc| ...
namespace :frankiz do task :refresh_promo, [:promo] => :environment do |_, args| FrankizLdap.new.crawl_promo(args[:promo]) end task refresh_oldest_promo: :environment do promo = User.select(:promo, 'MIN(updated_at) updated_at') .where.not(promo: nil) .group(:promo) .having('COUNT(1) > 1...
Add file to load path
class TictactoeRules attr_reader :desc WIN_COMBOS = [[0,1,2],[3,4,5],[6,7,8], [0,3,6],[1,4,7],[2,5,8], [0,4,8],[2,4,6]] def initialize @desc = { name: "TacTacToe", instructions: "You (X) and the computer (O) will take turns placing a 'X' and 'O' respectivel...
$: << File.dirname(__FILE__) class TictactoeRules attr_reader :desc WIN_COMBOS = [[0,1,2],[3,4,5],[6,7,8], [0,3,6],[1,4,7],[2,5,8], [0,4,8],[2,4,6]] def initialize @desc = { name: "TacTacToe", instructions: "You (X) and the computer (O) will take turns pla...
Check that memcached is running on the frontends
require "serverspec" # Required by serverspec set :backend, :exec describe package("memcached") do it { should be_installed } end describe service("memcached") do it { should be_enabled } it { should be_running } end describe port(11211) do it { should be_listening.with("tcp") } end
Save the scrapped url and its contents to the db
class Plag include Anemon @anemon = Anemon::Scrapper.new def self.scrap(url) @anemon.scrap(url) end def self.compare(file_name) @anemon.compare(url) end end
class Plag < ApplicationRecord include Anemon @anemon = Anemon::Scrapper.new def self.scrap(url) result = @anemon.scrap(url) Plag.create({url: result[:url], content: result[:content]}) if result end def self.compare(file_name) @anemon.compare(url) end end
Remove hacked support for kaminari page name
class Spree::Base < ActiveRecord::Base include Spree::Preferences::Preferable serialize :preferences, Hash include Spree::RansackableAttributes self.belongs_to_required_by_default = false def initialize_preference_defaults if has_attribute?(:preferences) self.preferences = default_preferences.mer...
class Spree::Base < ActiveRecord::Base include Spree::Preferences::Preferable serialize :preferences, Hash include Spree::RansackableAttributes self.belongs_to_required_by_default = false def initialize_preference_defaults if has_attribute?(:preferences) self.preferences = default_preferences.mer...
Include helper module in the controller
class ApplicationController < ActionController::Base # protect_from_forgery with: :exception end
class ApplicationController < ActionController::Base # protect_from_forgery with: :exception include AlexaInterfaceHelper end
Address a problem when a diaper bank doesnt have an email listed. Have it fall back to the email of the first user of the diaperbank.
class DistributionMailer < ApplicationMailer # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.distribution_mailer.partner_mailer.subject # def partner_mailer(current_organization, distribution) @partner = distribution.partner @distribution = distr...
class DistributionMailer < ApplicationMailer # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.distribution_mailer.partner_mailer.subject # def partner_mailer(current_organization, distribution) @partner = distribution.partner @distribution = distr...
Allow hal-client version to float into 3.x series
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rspec/hal/version' Gem::Specification.new do |spec| spec.name = "rspec-hal" spec.version = RSpec::Hal::VERSION spec.authors = ["Peter Williams"] spec.email = ...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rspec/hal/version' Gem::Specification.new do |spec| spec.name = "rspec-hal" spec.version = RSpec::Hal::VERSION spec.authors = ["Peter Williams"] spec.email = ...
Append glowfic-staging to cookies list, hopefully not affecting prod
# Be sure to restart your server when you modify this file. options = if Rails.env.production? {domain: 'glowfic.com', tld_length: 2} elsif Rails.env.development? {domain: 'localhost', tld_length: 2} else {} end Rails.application.config.session_store :cookie_store, key: '_glowfic_constellation_' + Rails.env, **...
# Be sure to restart your server when you modify this file. options = if Rails.env.production? {domain: ['glowfic.com', '.glowfic-staging.herokuapp.com'], tld_length: 2} elsif Rails.env.development? {domain: 'localhost', tld_length: 2} else {} end Rails.application.config.session_store :cookie_store, key: '_glo...