Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add author to dashboard index serializer
class Api::DashboardSerializer < ActiveModel::Serializer attributes :id, :title, :slug, :summary, :content, :attribution, :published, :user_id, :production, :preproduction, :staging, :tags, :locations belongs_to :partner, serializer: Api::PartnerSerializer end
class Api::DashboardSerializer < ActiveModel::Serializer attributes :id, :title, :slug, :summary, :content, :attribution, :published, :user_id, :production, :preproduction, :staging, :tags, :locations, :author belongs_to :partner, serializer: Api::PartnerSerializer end
Add simple Phonebook data structure
# A directory of names and phone numbers class Phonebook attr_accessor :data def initialize() self.data = {} end # Add a contact to this phone book # @param name [String] The name of the contact # @param number [String] The phone number of the contact def add(name, number) data[name] = number ...
Check for $stderr.puts, instead of Sicuro.warn.
describe Sicuro do context 'helpers' do Sicuro.assert('true', 'true').should == true context 'sandbox_error passed a string' do Sicuro.should_receive(:warn).with("[SANDBOX WARNING] test\n") Sicuro.sandbox_error('test') end context 'sandbox_error passed an array' do Sicuro.should_re...
describe Sicuro do context 'helpers' do Sicuro.assert('true', 'true').should == true context 'sandbox_error passed a string' do $stderr.should_receive(:puts).with("[SANDBOX WARNING] test\n") Sicuro.sandbox_error('test') end context 'sandbox_error passed an array' do $stderr.should_...
Change rspec tests to make better use of subject
require 'rails_helper' RSpec.describe Game, type: :model do context "when I create a new game" do context "with no arguments" do subject(:game) { Game.new } let(:default_starting_score) { 10 } let(:default_starting_word) { "hangman" } describe "#score" do it "should be set" do ...
require 'rails_helper' RSpec.describe Game, type: :model do context "when I create a new game" do context "with no arguments" do subject(:game) { Game.new } let(:default_starting_score) { 10 } let(:default_starting_word) { "hangman" } describe "#score" do subject { game.score } ...
Fix build on xcode 11.4
require 'json' package = JSON.parse(File.read(File.join(__dir__, 'package.json'))) Pod::Spec.new do |s| s.name = package['name'] s.version = package['version'] s.summary = package['description'] s.description = package['description'] s.license = package['license'] s.autho...
require 'json' package = JSON.parse(File.read(File.join(__dir__, 'package.json'))) Pod::Spec.new do |s| s.name = package['name'] s.version = package['version'] s.summary = package['description'] s.description = package['description'] s.license = package['license'] s.autho...
Update podspec to remove conflicting files
Pod::Spec.new do |s| s.name = "coinbase-official" s.version = "2.1.2" s.summary = "Integrate bitcoin into your iOS application." s.description = <<-DESC Integrate bitcoin into your iOS application with Coinbase's fully featured bitcoin payments API. Coin...
Pod::Spec.new do |s| s.name = "coinbase-official" s.version = "2.1.2" s.summary = "Integrate bitcoin into your iOS application." s.description = <<-DESC Integrate bitcoin into your iOS application with Coinbase's fully featured bitcoin payments API. Coin...
Add missing sync release dependency
# frozen_string_literal: true register("config") do Headbanger::Config.new end register("artists.sync") do |model, **options| Artists::Sync.new(model, **options) end register("artists.source") do |**args| Artists::Source.new(**args) end register("artists.metal_archives") do |metal_archives_key| Artists::Met...
# frozen_string_literal: true register("config") do Headbanger::Config.new end register("artists.sync") do |model, **options| Artists::Sync.new(model, **options) end register("artists.source") do |**args| Artists::Source.new(**args) end register("artists.metal_archives") do |metal_archives_key| Artists::Met...
Add specs regarding canceling policy simulation
describe ApplicationController do describe "#assign_policies" do let(:admin_user) { FactoryBot.create(:user, :role => "super_administrator") } let(:host) { FactoryBot.create(:host) } before do EvmSpecHelper.create_guid_miq_server_zone login_as admin_user allow(User).to receive(:c...
describe ApplicationController do describe "#assign_policies" do let(:admin_user) { FactoryBot.create(:user, :role => "super_administrator") } let(:host) { FactoryBot.create(:host) } before do EvmSpecHelper.create_guid_miq_server_zone login_as admin_user allow(User).to receive(:c...
Fix documentation typo on mailer rake task.
namespace :email do desc 'Sends test email to specified address - Example: EMAIL=spree@example.com bundle exec rake test:email' task test: :environment do unless ENV['EMAIL'].present? raise ArgumentError, "Must pass EMAIL environment variable. " \ "Example: EMAIL=spree@example.c...
namespace :email do desc 'Sends test email to specified address - Example: EMAIL=spree@example.com bundle exec rake email:test' task test: :environment do unless ENV['EMAIL'].present? raise ArgumentError, "Must pass EMAIL environment variable. " \ "Example: EMAIL=spree@example.c...
Rework options to more simple unix-way
#!/usr/bin/env ruby require 'rubygems' require 'slop' opts = Slop.new({ :help => true, :banner => [ 'Auto-generates association.csv from column.csv when we have same column names.', 'It`s useful in case of mysql MyISAM tables or another cases, when we lost our relationships.', 'Helper for http://jailer.sour...
#!/usr/bin/env ruby def main(argv) usage if argv.empty? p argv end def usage $stderr.puts [ 'Auto-generates association.csv from column.csv when we have same column names.', 'It`s useful in case of mysql MyISAM tables or another cases, when we lost our relationships.', 'Helper for http://jailer.sourceforge...
Update git tag in podspec.
Pod::Spec.new do |s| s.name = "Injineer" s.version = "1.0.1" s.summary = "A dependency injection framework for Objective-C" s.description = "Injineer is simpler than other DI frameworks for Objective-C but just as powerful. The framework introduces no dependencies in your code, so using it ...
Pod::Spec.new do |s| s.name = "Injineer" s.version = "1.0.1" s.summary = "A dependency injection framework for Objective-C" s.description = "Injineer is simpler than other DI frameworks for Objective-C but just as powerful. The framework introduces no dependencies in your code, so using it ...
Add column headings to git catalog ls
#!/usr/bin/env ruby # -*- encoding: us-ascii -*- desc "ls", "List the catalog file for the archive" option 'archive', :aliases=>'-a', :type=>'string', :desc=>'Archive location' def ls archive = Archive.new(options[:archive]) # TODO Use Array.justify_rows archive.catalog.each do |spec| puts "#{spec[:location]...
#!/usr/bin/env ruby # -*- encoding: us-ascii -*- desc "ls", "List the catalog file for the archive" option 'archive', :aliases=>'-a', :type=>'string', :desc=>'Archive location' def ls archive = Archive.new(:location=>options[:archive]) puts "Location Update File/Directory" archive.catalog.each do |spec| ...
Remove references to time now that we're using assert_migration
require 'rails' require 'spec_helper' require 'generator_spec/test_case' require 'generators/kaleidoscope/kaleidoscope_generator' describe 'TestMigration' do include GeneratorSpec::TestCase tests KaleidoscopeGenerator destination File.expand_path("../tmp", __FILE__) arguments %w(photo) let(:time) { Time.new...
require 'rails' require 'spec_helper' require 'generator_spec/test_case' require 'generators/kaleidoscope/kaleidoscope_generator' describe 'TestMigration' do include GeneratorSpec::TestCase tests KaleidoscopeGenerator destination File.expand_path("../tmp", __FILE__) arguments %w(photo) before do prepare...
Fix absence in DNS error.
require 'socket' require 'runit-man/service_info' require 'runit-man/partials' require 'sinatra/content_for' module Helpers include Rack::Utils include Sinatra::Partials include Sinatra::ContentFor alias_method :h, :escape_html attr_accessor :even_or_odd_state def host_name unless @host...
require 'socket' require 'runit-man/service_info' require 'runit-man/partials' require 'sinatra/content_for' module Helpers include Rack::Utils include Sinatra::Partials include Sinatra::ContentFor alias_method :h, :escape_html attr_accessor :even_or_odd_state def host_name unless @host...
Add Rake tasks for publication/destruction consumers.
namespace :messenger do desc "Run queue consumer" task :listen do Daemonette.run("publisher_metadata_sync") do Rake::Task["environment"].invoke MetadataSync.new.run end end end
namespace :messenger do desc "Run queue consumer" task :listen do Daemonette.run("publisher_metadata_sync") do Rake::Task["environment"].invoke MetadataSync.new.run end Daemonette.run("publisher_publication_listener") do Rake::Task["environment"].invoke PublicationListener.new....
Update the description of one of the ARGF specs.
require File.dirname(__FILE__) + '/../../spec_helper' describe "ARGF" do it "is Enumerable" do ARGF.should be_kind_of(Enumerable) end end
require File.dirname(__FILE__) + '/../../spec_helper' describe "ARGF" do it "is extended by the Enumerable module" do ARGF.should be_kind_of(Enumerable) end end
Update characters info each hour
# frozen_string_literal: true return if defined?(Rails::Console) || Rails.env.test? || File.split($0).last == 'rake' s = Rufus::Scheduler.singleton s.every '1m' do Rails.logger.info "hello, it's #{Time.now}" Rails.logger.flush end
# frozen_string_literal: true return if defined?(Rails::Console) || Rails.env.test? || File.split($0).last == "rake" s = Rufus::Scheduler.singleton s.every "1h" do Rails.logger.info "Update characters" Rails.logger.flush UpdateCharactersJob.perform_later end
Add code wars (6) - stop spinning my words
# http://www.codewars.com/kata/5264d2b162488dc400000001/ # --- iteration 1 --- def spinWords(string) string.split(" ") .reduce([]){ |acc, word| acc << (word.size >= 5 ? word.reverse : word) } .join(" ") end # --- iteration 2 --- def spinWords(str) str.gsub(/\w+/) { |w| w.size < 5 ? w : w.reverse } ...
Use `ActiveSupport.on_load` to hook into Active Record.
require "action_store/version" require "action_store/configuration" require "action_store/engine" require "action_store/model" require "action_store/mixin" module ActionStore class << self def config return @config if defined?(@config) @config = Configuration.new @config end def config...
require "action_store/version" require "action_store/configuration" require "action_store/engine" require "action_store/model" require "action_store/mixin" module ActionStore class << self def config return @config if defined?(@config) @config = Configuration.new @config end def config...
Allow controller overrides by parent app.
module Unity class Engine < ::Rails::Engine isolate_namespace Unity config.generators do |g| g.test_framework :rspec g.fixture_replacement :factory_girl, dir: "spec/factories" end config.to_prepare do Dir.glob(Rails.root + "app/decorators/**/*_decorator*.rb").each do |c| re...
module Unity class Engine < ::Rails::Engine isolate_namespace Unity config.generators do |g| g.test_framework :rspec g.fixture_replacement :factory_girl, dir: "spec/factories" end config.to_prepare do Dir.glob(Rails.root + "app/decorators/**/*_decorator*.rb").each do |c| re...
Make sure Pony gets loaded
require 'sinatra' require 'twilio-ruby' require 'json' NUMBER_MAP = JSON.parse(ENV["ADDRESSES"]) SMTP_URI = URI.parse(ENV["SMTP_URI"]) Pony.options = { from: 'operations@hubbub.co.uk', via: :smtp, via_options: { address: SMTP_URI.hostname, port: SMTP_URI.port || 25, enable_starttls_auto: true, u...
require 'sinatra' require 'twilio-ruby' require 'json' require 'pony' NUMBER_MAP = JSON.parse(ENV["ADDRESSES"]) SMTP_URI = URI.parse(ENV["SMTP_URI"]) Pony.options = { from: 'operations@hubbub.co.uk', via: :smtp, via_options: { address: SMTP_URI.hostname, port: SMTP_URI.port || 25, enable_starttls_au...
Add example of using gem with liblinear
# Document classification example using tokkens and linear SVM require 'tokkens' # `rake install` or `gem install tokkens` require 'liblinear' # `gem install liblinear-ruby` # define the training data TRAINING_DATA = [ ['school', 'The teacher writes a formula on the blackboard, while students are studying for thei...
Use to_i instead of round
require_relative '../color' class ASE class Color class Gray attr_accessor :value def initialize(value=0) @value = value end def read!(file) @value = file.read(4).reverse.unpack('F')[0] end def to_rgb [rgb_value] * 3 end def to_rgba ...
require_relative '../color' class ASE class Color class Gray attr_accessor :value def initialize(value=0) @value = value end def read!(file) @value = file.read(4).reverse.unpack('F')[0] end def to_rgb [rgb_value] * 3 end def to_rgba ...
Add migration to add domain column to api tokens tables
# frozen_string_literal: true class AddDomainColumnToApiTokensTables < ActiveRecord::Migration[6.0] def change add_column :user_api_tokens, :domain, :string add_column :admin_api_tokens, :domain, :string end end
Add missing newline at end of file
require 'spec_helper' describe Vcloud::Fog::ModelInterface do it "should retrive logged in organization" do vm_href, vdc_href = 'https://vmware.net/vapp/vm-1', 'vdc/vdc-1' vm = double(:vm, :href => vm_href) vdc = double(:vdc1, :id => 'vdc-1', :href => vdc_href, ...
require 'spec_helper' describe Vcloud::Fog::ModelInterface do it "should retrive logged in organization" do vm_href, vdc_href = 'https://vmware.net/vapp/vm-1', 'vdc/vdc-1' vm = double(:vm, :href => vm_href) vdc = double(:vdc1, :id => 'vdc-1', :href => vdc_href, ...
Check import_level in rake task
task :enqueue_feed_eater_worker, [:feed_onestop_ids, :import_level] => [:environment] do |t, args| begin if args.feed_onestop_ids.present? array_of_feed_onestop_ids = args.feed_onestop_ids.split(' ') else array_of_feed_onestop_ids = [] end feed_eater_worker = FeedEaterWorker.perform_async(...
task :enqueue_feed_eater_worker, [:feed_onestop_ids, :import_level] => [:environment] do |t, args| begin if args.feed_onestop_ids.present? array_of_feed_onestop_ids = args.feed_onestop_ids.split(' ') else array_of_feed_onestop_ids = [] end # Defalut import level import_level = (args.im...
Add Broadcast With This Tool
cask :v1 => 'butt' do version '0.1.14' sha256 'f12eac6ad2af8bc38717cccde3f7f139d426b6d098ef94f7dcd6ae7d1225f6ad' url "http://downloads.sourceforge.net/sourceforge/butt/butt-#{version}/butt-#{version}.dmg" name 'Broadcast Using This Tool' homepage 'http://butt.sourceforge.net/' license :gpl app 'butt.app...
Make ref return the internal symbol.
require 'set' require 'active_support/core_ext/module/attribute_accessors' module ActionView class Template class Types class Type cattr_accessor :types self.types = Set.new def self.register(*t) types.merge(t.map(&:to_s)) end register :html, :text, :js, ...
require 'set' require 'active_support/core_ext/module/attribute_accessors' module ActionView class Template class Types class Type cattr_accessor :types self.types = Set.new def self.register(*t) types.merge(t.map(&:to_s)) end register :html, :text, :js, ...
Change string characters to %{ } and remove unnecessary trailing slashes
require "proteus/version" require "thor" module Proteus class Kit < Thor include Thor::Actions desc "url", "gets the git url" def url(kit) "git@github.com:thoughtbot/proteus-#{kit}.git" end desc "new", "runs the command to clone a particular kit" def new(kit_name, repo_name = nil) ...
require "proteus/version" require "thor" module Proteus class Kit < Thor include Thor::Actions desc "url", "gets the git url" def url(kit) "git@github.com:thoughtbot/proteus-#{kit}.git" end desc "new", "runs the command to clone a particular kit" def new(kit_name, repo_name = nil) ...
Update initiatives grid to make use of baby_sqeel
class InitiativesGrid include Datagrid scope do Initiative end filter(:id, :string, :multiple => ',') filter(:name, :string) do |value| where.has {name =~ "#{value}%"} end filter(:area, :string, :multiple => ',', :header => 'Area ID') filter(:location, :string) { |value| where('location like ?...
class InitiativesGrid include Datagrid scope do Initiative end filter(:id, :string, :multiple => ',') filter(:name, :string) { |value| where.has { name =~ "#{value}%" } } filter(:area, :string, :multiple => ',', :header => 'Area ID') filter(:location, :string) { |value| where.has { location =~ "#{va...
Make private_profile flag true by default.
class AddPrivateProfileToUsers < ActiveRecord::Migration def change add_column :users, :private_profile, :boolean, index: { where: "(private_profile = true)" }, default: false end end
class AddPrivateProfileToUsers < ActiveRecord::Migration def change add_column :users, :private_profile, :boolean, index: { where: "(private_profile = false)" }, default: true end end
Add syncReference as optional field in credit creation.
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 self.receive_payment(opts) ReceivedPayment.create(opts) end def self.void_received_payment(id...
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 create_credit(amount, description="", syncReference="") data = { customerId: id, amoun...
Add yardoc and remove unnecessary ['abc'].
module Guard class RSpectacle class Humanity def success pick [ 'How cool, all works!', 'Awesome, all passing!', 'Well done, mate!', 'You rock!', 'Good job!', 'Yep!' ] end def failure pick [ 'Try har...
module Guard class RSpectacle # The humanity class helps to bring some randomness # into the so boring and static messages from rspectacle. # class Humanity # Picks a random success message. # # @return [String] a success message # def success pick [ '...
Fix general case of to_json for model objects.
module Bra module Models # Internal: An object in the BRA model. class ModelObject # Public: Allows read access to the object's name. attr_reader :name # Public: Allows read access to the object's short name. attr_reader :short_name def initialize(name, short_name=nil) ...
module Bra module Models # Internal: An object in the BRA model. class ModelObject # Public: Allows read access to the object's name. attr_reader :name # Public: Allows read access to the object's short name. attr_reader :short_name def initialize(name, short_name=nil) ...
Set website locale from Accept-Language header
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :mobile_filter_header def mobile_filter_header @mobile = true end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :mobile_filter_header before_action :set_locale def mobile_filter_header @mobile = true end ...
Remove attribute for Test1 as its nolonger required with the latest application_wlp code
# Cookbook Name:: wlp-samples # Attributes:: default # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# Cookbook Name:: wlp-samples # Attributes:: default # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
Update FreeTDS v0.99 current version.
ICONV_VERSION = ENV['TINYTDS_ICONV_VERSION'] || "1.14" ICONV_SOURCE_URI = "http://ftp.gnu.org/pub/gnu/libiconv/libiconv-#{ICONV_VERSION}.tar.gz" OPENSSL_VERSION = ENV['TINYTDS_OPENSSL_VERSION'] || '1.0.2e' OPENSSL_SOURCE_URI = "http://www.openssl.org/source/openssl-#{OPENSSL_VERSION}.tar.gz" FREETDS_VERSION = ENV['T...
ICONV_VERSION = ENV['TINYTDS_ICONV_VERSION'] || "1.14" ICONV_SOURCE_URI = "http://ftp.gnu.org/pub/gnu/libiconv/libiconv-#{ICONV_VERSION}.tar.gz" OPENSSL_VERSION = ENV['TINYTDS_OPENSSL_VERSION'] || '1.0.2e' OPENSSL_SOURCE_URI = "http://www.openssl.org/source/openssl-#{OPENSSL_VERSION}.tar.gz" FREETDS_VERSION = ENV['T...
Refactor creation of property by using first_or_create instead of condition based creation
module Spree class ProductProperty < Spree::Base acts_as_list scope: :product belongs_to :product, touch: true, class_name: 'Spree::Product', inverse_of: :product_properties belongs_to :property, class_name: 'Spree::Property', inverse_of: :product_properties validates :property, presence: true ...
module Spree class ProductProperty < Spree::Base acts_as_list scope: :product belongs_to :product, touch: true, class_name: 'Spree::Product', inverse_of: :product_properties belongs_to :property, class_name: 'Spree::Property', inverse_of: :product_properties validates :property, presence: true ...
Fix checksum in Google Japanese IME Dev build
cask :v1 => 'google-japanese-ime-dev' do version 'dev' sha256 'd3f786d3462e0294f29bc1f8998163489f812a1ae650661e9a26a92b731c2ef8' url 'https://dl.google.com/japanese-ime/dev/GoogleJapaneseInput.dmg' homepage 'https://www.google.co.jp/ime/' license :unknown pkg 'GoogleJapaneseInput.pkg' uninstall :pkgutil...
cask :v1 => 'google-japanese-ime-dev' do version :latest sha256 :no_check url 'https://dl.google.com/japanese-ime/dev/GoogleJapaneseInput.dmg' homepage 'https://www.google.co.jp/ime/' license :unknown pkg 'GoogleJapaneseInput.pkg' uninstall :pkgutil => 'com.google.pkg.GoogleJapaneseInput', :...
Add unit tests for clean_cocoapods_cache action.
describe Fastlane do describe Fastlane::FastFile do describe "Clean Cocoapods Cache Integration" do it "default use case" do result = Fastlane::FastFile.new.parse("lane :test do clean_cocoapods_cache end").runner.execute(:test) expect(result).to eq("pod cache clean --all")...
Create the test when receive an override parameter
require 'spec_helper' require 'pry' module CorreiosSigep module Builders module XML describe Request do describe '.build_xml' do let(:request) { double(:request, to_xml: '<root><test></root>') } context 'when do not override anything' do it 'builds a Authentication X...
Add single_quad definition for ansible tower jobs
module ManageIQ::Providers::AnsibleTower class AutomationManager::JobDecorator < MiqDecorator def self.fonticon 'ff ff-stack' end end end
module ManageIQ::Providers::AnsibleTower class AutomationManager::JobDecorator < MiqDecorator def self.fonticon 'ff ff-stack' end def single_quad { :fonticon => fonticon } end end end
Use connection validation for pooled connections
require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require 'active_model/railtie' require 'action_controller/railtie' require 'action_mailer/railtie' require 'action_view/railtie' # require 'sprockets/railtie' # require 'active_record/railtie' # require 'rails/test_unit/railtie' # Require t...
require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require 'active_model/railtie' require 'action_controller/railtie' require 'action_mailer/railtie' require 'action_view/railtie' # require 'sprockets/railtie' # require 'active_record/railtie' # require 'rails/test_unit/railtie' # Require t...
Make migration add_search_to_service_version a bit more resilient
class AddSearchToServiceVersion < ActiveRecord::Migration[5.0] def up execute <<-SQL CREATE EXTENSION unaccent; CREATE TEXT SEARCH CONFIGURATION es ( COPY = spanish ); ALTER TEXT SEARCH CONFIGURATION es ALTER MAPPING FOR hword, hword_part, word WITH unaccent, spanish_stem; ALTER TABLE ser...
class AddSearchToServiceVersion < ActiveRecord::Migration[5.0] def up execute <<-SQL CREATE EXTENSION IF NOT EXISTS unaccent; CREATE TEXT SEARCH CONFIGURATION es ( COPY = spanish ); ALTER TEXT SEARCH CONFIGURATION es ALTER MAPPING FOR hword, hword_part, word WITH unaccent, spanish_stem; A...
Change to load necessary locale files
module SpreeI18n class Railtie < ::Rails::Railtie #:nodoc: initializer 'spree-i18n' do |app| SpreeI18n::Railtie.instance_eval do pattern = pattern_from app.config.i18n.available_locales add("config/locales/#{pattern}/*.{rb,yml}") add("config/locales/*.{rb,yml}") end end ...
module SpreeI18n class Railtie < ::Rails::Railtie #:nodoc: initializer 'spree-i18n' do |app| SpreeI18n::Railtie.instance_eval do pattern = pattern_from app.config.i18n.available_locales add("config/locales/#{pattern}/*.{rb,yml}") add("config/locales/#{pattern}.{rb,yml}") end ...
Use attribute = true instead of duplicating that
require "active_support/core_ext/module/delegation" require "active_support/core_ext/time/calculations" require "active_model/type" require "time_for_a_boolean/version" require "time_for_a_boolean/railtie" module TimeForABoolean def time_for_a_boolean(attribute, field="#{attribute}_at") define_method(attribute) ...
require "active_support/core_ext/module/delegation" require "active_support/core_ext/time/calculations" require "active_model/type" require "time_for_a_boolean/version" require "time_for_a_boolean/railtie" module TimeForABoolean def time_for_a_boolean(attribute, field=:"#{attribute}_at") define_method(attribute)...
Remove ACAO; we are accessing from the same server
require "sinatra" require "json" require_relative "src/orders_finder" get "/" do send_file File.join(settings.public_folder, 'index.html') end get "/:email/:order_numbers" do content_type "application/json" response["Access-Control-Allow-Origin"] = "*" { orders: orders }.to_json end private def orders O...
require "sinatra" require "json" require_relative "src/orders_finder" get "/" do send_file File.join(settings.public_folder, 'index.html') end get "/:email/:order_numbers" do content_type "application/json" { orders: orders }.to_json end private def orders OrdersFinder.find(params[:email], params[:order_nu...
Add script for console testing
p1 = Player.create(name: "kieran") p2 = Player.create(name: "pragya") p3 = Player.create(name: "mitch") p4 = Player.create(name: "mikee") # Start a new game - controller action game = Game.create # Add players to the game - controller action? game.players << p1 << p2 << p3 << p4 # Start a new round- controller actio...
Add integration test for serialization with Marshal
# encoding: utf-8 require 'spec_helper' class Serializable include Memoizable def method; end memoize :method end describe 'A serializable object' do let(:serializable) do Serializable.new end it 'is serializable with Marshal' do serializable.method # Call the method to trigger lazy memoization ...
Check for Pling::NoGatewayFound error message in specs
require 'spec_helper' describe Pling::Gateway do subject { Pling::Gateway } let(:message) { Pling::Message.new('Hello from Pling') } let(:device) { Pling::Device.new(:identifier => 'DEVICEIDENTIFIER', :type => :android) } let(:gateway_class) do Class.new(Pling::Gateway::Base).tap do |klass| klass...
require 'spec_helper' describe Pling::Gateway do subject { Pling::Gateway } let(:message) { Pling::Message.new('Hello from Pling') } let(:device) { Pling::Device.new(:identifier => 'DEVICEIDENTIFIER', :type => :android) } let(:gateway_class) do Class.new(Pling::Gateway::Base).tap do |klass| klass...
Add rake task to export content base paths from a taxonomy
require 'csv' namespace :taxonomy do desc <<-DESC Download content base paths from the taxonomy. Provide the content ID of a taxon as a starting point. The script will print to STDOUT base paths for all content tagged to the chosen taxon and all of its children. DESC task :export_base_paths, [:taxon_...
Create model files before collection files
module Backbone class CollectionGenerator < Rails::Generators::NamedBase source_root File.expand_path('../templates', __FILE__) def copy_collection_file template 'collection.js.coffee', "app/assets/javascripts/collections/#{plural_file_name}.js.coffee" end def copy_model_file template 'm...
module Backbone class CollectionGenerator < Rails::Generators::NamedBase source_root File.expand_path('../templates', __FILE__) def copy_model_file template 'model.js.coffee', "app/assets/javascripts/models/#{singular_file_name}.js.coffee" end def copy_collection_file template 'collectio...
Add sequel scope all with default scope bench
require 'bundler/setup' require 'sequel' require_relative 'support/benchmark_sequel' DB = Sequel.connect(ENV.fetch('DATABASE_URL')) DB.create_table!(:users) do primary_key :id String :name, size: 255 String :email, size: 255 TrueClass :admin, null: false DateTime :created_at, null: true DateTime :updated...
Create api token for existing users
class Widget < ActiveRecord::Base after_initialize :default_values belongs_to :user acts_as_api include Api::Widget GEO_FACTORY = RGeo::Cartesian.factory def provider end def providers ['provider1', 'provider2'] end def src #http://wheelmap.org/en/map#/?lat=52.505298303257234&lon=13.42...
class Widget < ActiveRecord::Base after_initialize :default_values belongs_to :user acts_as_api include Api::Widget GEO_FACTORY = RGeo::Cartesian.factory def provider end def providers ['provider1', 'provider2'] end def src #http://wheelmap.org/en/map#/?lat=52.505298303257234&lon=13.42...
Fix check for required options
require 'uri' require 'socket' require 'openssl' module Houston class Connection class << self def open(options = {}) return unless block_given? [:certificate, :passphrase, :host, :port].each do |option| raise ArgumentError, "Missing connection parameter: #{option}" unless option...
require 'uri' require 'socket' require 'openssl' module Houston class Connection class << self def open(options = {}) return unless block_given? [:certificate, :passphrase, :host, :port].each do |option| raise ArgumentError, "Missing connection parameter: #{option}" unless option...
Drop not null constraint for amount in spree line items
class ChangeSpreePriceAmountPrecision < ActiveRecord::Migration def change change_column :spree_prices, :amount, :decimal, :precision => 10, :scale => 2 change_column :spree_line_items, :price, :decimal, :precision => 10, :scale => 2, :null => false change_column :spree_line_items, :cost_price, :decima...
class ChangeSpreePriceAmountPrecision < ActiveRecord::Migration def change change_column :spree_prices, :amount, :decimal, :precision => 10, :scale => 2 change_column :spree_line_items, :price, :decimal, :precision => 10, :scale => 2 change_column :spree_line_items, :cost_price, :decimal, :precision =>...
Add ability to configure a operation timeout for git stat
require_relative 'log_parser' module Gitlab module Git class GitStats attr_accessor :repo, :ref def initialize repo, ref @repo, @ref = repo, ref end def log log = nil Grit::Git.with_timeout(30) do # Limit log to 6k commits to avoid timeout for huge proj...
require_relative 'log_parser' module Gitlab module Git class GitStats attr_accessor :repo, :ref, :timeout def initialize(repo, ref, timeout = 30) @repo, @ref, @timeout = repo, ref, timeout end def log log = nil Grit::Git.with_timeout(timeout) do # Limit...
Use RuboCop::ProcessedSource instead of non-existant SourceParser
require 'pronto' require 'rubocop' module Pronto class Rubocop < Runner def initialize @config_store = ::RuboCop::ConfigStore.new @inspector = ::RuboCop::Runner.new({}, @config_store) end def run(patches, _) return [] unless patches valid_patches = patches.select do |patch| ...
require 'pronto' require 'rubocop' module Pronto class Rubocop < Runner def initialize @config_store = ::RuboCop::ConfigStore.new @inspector = ::RuboCop::Runner.new({}, @config_store) end def run(patches, _) return [] unless patches valid_patches = patches.select do |patch| ...
Add (failing) spec for overriding 'needs' methods.
describe "Fortitude method precedence", :type => :system do it "should have widget methods > need methods > helper methods > tag methods" do helpers_class = Class.new do def foo "helper_foo" end def bar "helper_bar" end def baz "helper_baz" end ...
describe "Fortitude method precedence", :type => :system do it "should have widget methods > need methods > helper methods > tag methods" do helpers_class = Class.new do def foo "helper_foo" end def bar "helper_bar" end def baz "helper_baz" end ...
Remove stupid include of .so file
# before the require 'rbconfig' require 'yell' RbConfig::CONFIG['CFLAGS'] = '' # Transrate is a comprehensive transcriptome assembly # quality assessment tool. module Transrate # Our own set of errors to allow nice custom error handling class TransrateError < StandardError; end class TransrateIOError < Transrat...
# before the require 'rbconfig' require 'yell' RbConfig::CONFIG['CFLAGS'] = '' # Transrate is a comprehensive transcriptome assembly # quality assessment tool. module Transrate # Our own set of errors to allow nice custom error handling class TransrateError < StandardError; end class TransrateIOError < Transrat...
Fix crash when a / is in the search string
class SearchesController < ApplicationController def index @results = get_sphinx_search_results params[:q] @results.context[:panes] << ThinkingSphinx::Panes::ExcerptsPane respond_to do |format| format.html #do nothing, defaults to default template format.json do @results.map! { |resu...
class SearchesController < ApplicationController def index @results = get_sphinx_search_results params[:q] @results.context[:panes] << ThinkingSphinx::Panes::ExcerptsPane respond_to do |format| format.html #do nothing, defaults to default template format.json do @results.map! { |resu...
Add very rudimentary set of benchmarks.
# -*- encoding: utf-8 -*- # :enddoc: # # benchmark_fizzbuzz.rb # # Copyright 2012-2013 Krzysztof Wilczynski # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/lice...
Update rubocop requirement to ~> 0.56.0
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'prius/version' Gem::Specification.new do |spec| spec.name = "prius" spec.version = Prius::VERSION spec.authors = ["Harry Marr"] spec.email = ["engineering@goc...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'prius/version' Gem::Specification.new do |spec| spec.name = "prius" spec.version = Prius::VERSION spec.authors = ["Harry Marr"] spec.email = ["engineering@goc...
Fix the description and gem dep
Gem::Specification.new do |s| s.name = "toadhopper-sinatra" s.version = "0.1" s.extra_rdoc_files = ["Readme.md"] s.summary = "Posting Hoptoad notifications from Sinatra apps" s.description = s.summary s.authors = ["Tim Lucas"] s.email = "t.lucas@toolm...
Gem::Specification.new do |s| s.name = "toadhopper-sinatra" s.version = "0.1" s.extra_rdoc_files = ["Readme.md"] s.summary = "Post Hoptoad notifications from Sinatra" s.description = s.summary s.authors = ["Tim Lucas"] s.email = "t.lucas@toolmantim.co...
Create rake task for clean projects from nobody users
namespace :nobodies do desc 'Remove on projects users that have nobody postion' task remove: :environment do Project.find_each do |project| project.users.nobodies.delete_all end end end
Disable garbage collector during request
# This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) if Rails.env.profile? use Rack::RubyProf, path: '/tmp/profile' end run SciRate::Application
# This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) class Garbage def initialize(app) @app = app end def call(env) GC.disable v = @app.call(env) GC.enable v end end use Garbage if Rails.env.profile? use Sta...
Update to Intellij Community Edition 13.1
case node[:platform] when "centos", "redhat", "debian", "ubuntu" default['intellij_community_edition']['download_url']="http://download.jetbrains.com/idea/ideaIC-13.tar.gz" default['intellij_community_edition']['name']="IntelliJ IDEA 13 CE" when "mac_os_x" default['intellij_community_edition']['download_url']="h...
case node[:platform] when "centos", "redhat", "debian", "ubuntu" default['intellij_community_edition']['download_url']="http://download.jetbrains.com/idea/ideaIC-13.1.tar.gz" default['intellij_community_edition']['name']="IntelliJ IDEA 13 CE" when "mac_os_x" default['intellij_community_edition']['download_url']=...
Add users to the users group in an org if not already there
require 'json' require 'chef_zero/rest_base' module ChefZero module Endpoints # /users/USER/association_requests/ID class UserAssociationRequestEndpoint < RestBase def put(request) username = request.rest_path[1] id = request.rest_path[3] if id !~ /^#{username}-(.+)/ r...
require 'json' require 'chef_zero/rest_base' module ChefZero module Endpoints # /users/USER/association_requests/ID class UserAssociationRequestEndpoint < RestBase def put(request) username = request.rest_path[1] id = request.rest_path[3] if id !~ /^#{username}-(.+)/ r...
Include backtrace in serialized exception payload
module Dat module Science # Internal. The output of running of an observed behavior. class Result attr_reader :duration attr_reader :exception attr_reader :experiment attr_reader :value def initialize(experiment, value, duration, exception) @duration = duration ...
module Dat module Science # Internal. The output of running of an observed behavior. class Result attr_reader :duration attr_reader :exception attr_reader :experiment attr_reader :value def initialize(experiment, value, duration, exception) @duration = duration ...
Add plugin to get absolute urls in feeds
# https://github.com/jessecrouch/jekyll-rss-absolute-urls module Jekyll module RSSURLFilter def relative_urls_to_absolute(input,url) #url = "http://blog.jbfavre.org" input.gsub('src="/', 'src="' + url + '/').gsub('href="/', 'href="' + url + '/') end end end Liquid::Template.register_filter(Jeky...
Remove duplicated 'using' in error message
module Camcorder class Error < StandardError; end class RecordingError < Error attr_reader :key def initialize(key) @key = key end def message "Recording for key #{key} has changed" end end class ProxyRecordingError < Error attr_reader :klass, :name, :args, :side_eff...
module Camcorder class Error < StandardError; end class RecordingError < Error attr_reader :key def initialize(key) @key = key end def message "Recording for key #{key} has changed" end end class ProxyRecordingError < Error attr_reader :klass, :name, :args, :side_eff...
Use set_list_position in update positions for products
# frozen_string_literal: true module Spree module Admin class LookBookImageProductsController < ResourceController def update_positions ActiveRecord::Base.transaction do params[:positions].each do |id, index| model_class.find(id).insert_at(index) end end ...
# frozen_string_literal: true module Spree module Admin class LookBookImageProductsController < ResourceController def update_positions ActiveRecord::Base.transaction do params[:positions].each do |id, index| model_class.find(id).set_list_position(index) end e...
Change gemspec for push to rubygems
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'ael_tracker/version' Gem::Specification.new do |spec| spec.name = "ael_tracker" spec.version = AelTracker::VERSION spec.authors = ["Bradley Sheehan"] spec.email ...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'ael_tracker/version' Gem::Specification.new do |spec| spec.name = "ael_tracker" spec.version = AelTracker::VERSION spec.authors = ["Bradley Sheehan"] spec.email ...
Fix regex that creates migration class
require 'slim_migrations/version' module SlimMigrations class Railtie < Rails::Railtie rake_tasks do load "tasks/slim_migrations_tasks.rake" end end end module Kernel private # initialize migrations with <tt>migration do</tt> instead of <tt>class SomeMigration < ActiveRecord::Migration</tt> d...
require 'slim_migrations/version' module SlimMigrations class Railtie < Rails::Railtie rake_tasks do load "tasks/slim_migrations_tasks.rake" end end end module Kernel private # initialize migrations with <tt>migration do</tt> instead of <tt>class SomeMigration < ActiveRecord::Migration</tt> d...
Support setting the storage not using default_options
module Spree class Digital < ActiveRecord::Base belongs_to :variant has_many :digital_links, dependent: :destroy has_many :drm_records, dependent: :destroy has_attached_file :attachment, path: ":rails_root/private/digitals/:id/:basename.:extension" do_not_validate_attachment_file_type :attachment...
module Spree class Digital < ActiveRecord::Base belongs_to :variant has_many :digital_links, dependent: :destroy has_many :drm_records, dependent: :destroy has_attached_file :attachment, path: ":rails_root/private/digitals/:id/:basename.:extension" do_not_validate_attachment_file_type :attachment...
Add module to transfer ActiveStorage tables from backup db
module ActiveStorageTransfer def self.transfer only_dump=false config = ActiveRecord::Base.connection_config backup_path = Rails.root.join("tmp/active_storage.dump") dump_command = [] dump_command << "PGPASSWORD=#{config[:password]}" if config[:password].present? dump_command << "pg_dump" du...
Add fqdn and default to empty hashes.
require 'elasticsearch/persistence/model' require 'hashie' class Node include Elasticsearch::Persistence::Model attribute :name, String # TODO: limit these two to a list of defaults attribute :ilk, String attribute :status, String attribute :facts, Hashie::Mash, mapping: { type: 'object'...
require 'elasticsearch/persistence/model' require 'hashie' class Node include Elasticsearch::Persistence::Model attribute :name, String attribute :fqdn, String, default: :name # TODO: limit these two to a list of defaults attribute :ilk, String attribute :status, String attribute :f...
Complete node and linked list implementation
class Node attr_accessor :value, :next def initialize(value, next_node = nil) @value = value @next = next_node end def to_s value.to_s end end class LinkedList include Enumerable attr_accessor :head def each #if @head is nil the second half of the && expression won't run @head &...
class Node attr_accessor :value, :next def initialize(value, next_node = nil) @value = value @next = next_node end end class LinkedList attr_accessor :head, :tail # This linked list must be initialized with a node instance def initialize(head) @head = head @tail = head end # Insert...
Solve problem with city and state validation
class CityAndStateValidator < ActiveModel::Validator def validate(record) begin if record.address_city.present? && record.address_state.present? result = Geocoder.search(record.address, params: { countrycodes: "us" }) if result.first.present? record.address_city = result.first.cit...
class CityAndStateValidator < ActiveModel::Validator def validate(record) begin if record.address_city.present? && record.address_state.present? result = Geocoder.search(record.address, params: { countrycodes: "us" }) record.address_city = result.first.city rescue nil record.address...
Add best_answer getter method to Question model
class Question < ActiveRecord::Base include Votable belongs_to :user has_many :answers has_many :comments, as: :commentable has_many :votes, as: :votable validates_presence_of :title, :content, :user_id end
class Question < ActiveRecord::Base include Votable belongs_to :user has_many :answers has_many :comments, as: :commentable has_many :votes, as: :votable validates_presence_of :title, :content, :user_id def best_answer Answer.find_by(id: self.best_answer_id) end end
Remove gemspec dependency on Jekyll
# frozen_string_literal: true $LOAD_PATH.unshift File.expand_path("lib", __dir__) require "jekyll-commonmark/version" Gem::Specification.new do |spec| spec.name = "jekyll-commonmark" spec.summary = "CommonMark generator for Jekyll" spec.version = Jekyll::CommonMark::VERSION spec.authors ...
# frozen_string_literal: true $LOAD_PATH.unshift File.expand_path("lib", __dir__) require "jekyll-commonmark/version" Gem::Specification.new do |spec| spec.name = "jekyll-commonmark" spec.summary = "CommonMark generator for Jekyll" spec.version = Jekyll::CommonMark::VERSION spec.authors ...
Consolidate ensure_leading_slash to 2 lines.
module Jekyll module Filters module URLFilters # Produces an absolute URL based on site.url and site.baseurl. # # input - the URL to make absolute. # # Returns the absolute URL as a String. def absolute_url(input) return if input.nil? site = @context.registers[:...
module Jekyll module Filters module URLFilters # Produces an absolute URL based on site.url and site.baseurl. # # input - the URL to make absolute. # # Returns the absolute URL as a String. def absolute_url(input) return if input.nil? site = @context.registers[:...
Rename rake task migrate_organisation_logos -> migrate_assets
namespace :asset_manager do desc "Migrates Organisation logos to Asset Manager." task migrate_organisation_logos: :environment do MigrateAssetsToAssetManager.new.perform end end
namespace :asset_manager do desc "Migrates Assets to Asset Manager." task migrate_assets: :environment do MigrateAssetsToAssetManager.new.perform end end
Use attr_accessor instead of methods
# Retryable Typheous # Inspiration: https://gist.github.com/kunalmodi/2939288 # Patches the request and hydra to allow requests to get resend when they fail module RetryableTyphoeus require 'typhoeus' include Typhoeus DEFAULT_RETRIES = 10 class Request < Typhoeus::Request def initialize(base_url, option...
# Retryable Typheous # Inspiration: https://gist.github.com/kunalmodi/2939288 # Patches the request and hydra to allow requests to get resend when they fail module RetryableTyphoeus require 'typhoeus' include Typhoeus DEFAULT_RETRIES = 10 class Request < Typhoeus::Request attr_accessor :retries def...
Refactor mdJson writer module for 'dictionary' include minitest modules
# mdJson 2.0 writer - dictionary # History: # Stan Smith 2017-03-11 refactored for mdJson/mdTranslator 2.0 # Josh Bradley original script # TODO Complete tests require 'jbuilder' require_relative 'mdJson_citation' require_relative 'mdJson_responsibleParty' require_relative 'mdJson_locale' require_relative 'mdJso...
# mdJson 2.0 writer - dictionary # History: # Stan Smith 2017-03-11 refactored for mdJson/mdTranslator 2.0 # Josh Bradley original script require 'jbuilder' require_relative 'mdJson_citation' require_relative 'mdJson_responsibleParty' require_relative 'mdJson_locale' require_relative 'mdJson_domain' require_relat...
Add rake to gemfile for Travis
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'qtrix/version' Gem::Specification.new do |gem| gem.name = "qtrix" gem.version = Qtrix::VERSION gem.authors = ["Lance Woodson", "Joshua Flanagan"] gem.email ...
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'qtrix/version' Gem::Specification.new do |gem| gem.name = "qtrix" gem.version = Qtrix::VERSION gem.authors = ["Lance Woodson", "Joshua Flanagan"] gem.email ...
Add Authorization test to Jenkins (GitHub) hook
require File.expand_path('../helper', __FILE__) class JenkinsGitHubTest < Service::TestCase def setup @stubs = Faraday::Adapter::Test::Stubs.new end def test_push @stubs.post "/github-webhook/" do |env| assert_equal 'jenkins.example.com', env[:url].host assert_equal 'application/x-www-form-u...
require File.expand_path('../helper', __FILE__) class JenkinsGitHubTest < Service::TestCase def setup @stubs = Faraday::Adapter::Test::Stubs.new end def test_push @stubs.post "/github-webhook/" do |env| assert_equal 'jenkins.example.com', env[:url].host assert_equal 'Basic bW9ua2V5OnNlY3JldA...
Set RAILS_ENV before loading config/environment
require 'optparse' require 'irb' require "irb/completion" module Rails class Console def self.start new.start end def start options = {} OptionParser.new do |opt| opt.banner = "Usage: console [environment] [options]" opt.on('-s', '--sandbox', 'Rollback database modific...
require 'optparse' require 'irb' require "irb/completion" module Rails class Console ENVIRONMENTS = %w(production development test) def self.start new.start end def start options = {} OptionParser.new do |opt| opt.banner = "Usage: console [environment] [options]" ...
Add svg to image preprocessor
Pakyow::Assets.preprocessor :ico Pakyow::Assets.preprocessor :png, :jpg, :gif, fingerprint: true
Pakyow::Assets.preprocessor :ico Pakyow::Assets.preprocessor :png, :jpg, :gif, :svg, fingerprint: true
Upgrade active_attr to 0.10.2 to support latest Discourse
# name: discourse-nntp-bridge # about: Discourse plugin to keep NNTP & Discourse in sync # version: 0.1.10 # authors: Stuart Olivera # url: https://github.com/sman591/discourse-nntp-bridge enabled_site_setting :nntp_bridge_enabled # install dependencies gem 'active_attr', '0.9.0' gem 'thoughtafter-nntp', '1.0.0.3', r...
# name: discourse-nntp-bridge # about: Discourse plugin to keep NNTP & Discourse in sync # version: 0.1.10 # authors: Stuart Olivera # url: https://github.com/sman591/discourse-nntp-bridge enabled_site_setting :nntp_bridge_enabled # install dependencies gem 'active_attr', '0.10.2' gem 'thoughtafter-nntp', '1.0.0.3', ...
Update mailer to use attachments[] instead of attachment[]
module ImportProducts module UserMailerExt def self.included(base) base.class_eval do def product_import_results(user, error_message = nil) @user = user @error_message = error_message attachment["import_products.log"] = File.read(ImportProductSettings::LOGFILE) if @erro...
module ImportProducts module UserMailerExt def self.included(base) base.class_eval do def product_import_results(user, error_message = nil) @user = user @error_message = error_message attachments["import_products.log"] = File.read(IMPORT_PRODUCT_SETTINGS[:log_to]) if @e...
Make the searches perform a like
class SavedSearch < ActiveRecord::Base before_save :set_available_fields serialize :available_fields serialize :query_parameters serialize :display_fields def set_available_fields attributes = Array.new for attribute in eval(self.model_name).columns attributes << attribute.name end sel...
class SavedSearch < ActiveRecord::Base before_save :set_available_fields serialize :available_fields serialize :query_parameters serialize :display_fields def set_available_fields attributes = Array.new for attribute in eval(self.model_name).columns attributes << attribute.name end sel...
Handle pry no present on CI
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) if ENV["CODECLIMATE_REPO_TOKEN"] # report coverage only for latest mri ruby if RUBY_ENGINE == "ruby" && RUBY_VERSION >= "2.2.0" require "codeclimate-test-reporter" CodeClimate::TestReporter.start end else require "simplecov" SimpleCov.start e...
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) if ENV["CODECLIMATE_REPO_TOKEN"] # report coverage only for latest mri ruby if RUBY_ENGINE == "ruby" && RUBY_VERSION >= "2.2.0" require "codeclimate-test-reporter" CodeClimate::TestReporter.start end else require "simplecov" SimpleCov.start e...
Remove unnecessary mime type declaration
require "emcee/processors/directive_processor" require "emcee/processors/import_processor" require "emcee/processors/script_processor" require "emcee/processors/stylesheet_processor" require "emcee/compressors/html_compressor" module Emcee class Railtie < Rails::Railtie initializer :add_html_processor do |app| ...
require "emcee/processors/directive_processor" require "emcee/processors/import_processor" require "emcee/processors/script_processor" require "emcee/processors/stylesheet_processor" require "emcee/compressors/html_compressor" module Emcee class Railtie < Rails::Railtie initializer :add_html_processor do |app| ...
Fix enumberable implementation for Collection
# frozen_string_literal: true module Brivo class Collection include Enumerable def initialize application, api_path, model @application = application @api_path = api_path @model = model @collection = [] fetch_collection end def each(&block) @collection.each(&bl...
# frozen_string_literal: true module Brivo class Collection include Enumerable def initialize application, api_path, model @application = application @api_path = api_path @model = model @collection = [] fetch_collection end def each(&block) total_count = @total...
Fix issue introduced by using class methods
require 'oj' module JsonKeyTransformerMiddleware class OutgoingJsonFormatter < Middleware def initialize(app) @app = app end def call(env) status, headers, body = @app.call(env) new_body = self.class.build_new_body(body) [status, headers, new_body] end private d...
require 'oj' module JsonKeyTransformerMiddleware class OutgoingJsonFormatter < Middleware def initialize(app) @app = app end def call(env) status, headers, body = @app.call(env) new_body = build_new_body(body) [status, headers, new_body] end private def build_ne...
Improve performance of the Logger middleware by using simpler versions of methods
require 'rails/log_subscriber' module Rails module Rack # Log the request started and flush all loggers after it. class Logger < Rails::LogSubscriber def initialize(app) @app = app end def call(env) before_dispatch(env) @app.call(env) ensure after_disp...
require 'rails/log_subscriber' require 'active_support/core_ext/time/conversions' module Rails module Rack # Log the request started and flush all loggers after it. class Logger < Rails::LogSubscriber def initialize(app) @app = app end def call(env) before_dispatch(env) ...
Include tests in the gemfile (useful for example generation, etc)
version = File.read("VERSION").strip if File.exists?"JENKINS" version += "." version += File.read("JENKINS").strip end buildf = File.open("BUILD_VERSION", 'w') buildf.puts version buildf.close Gem::Specification.new do |s| s.name = 'tritium' s.version = version s.platform = Gem::Platform::RUBY...
version = File.read("VERSION").strip if File.exists?"JENKINS" version += "." version += File.read("JENKINS").strip end buildf = File.open("BUILD_VERSION", 'w') buildf.puts version buildf.close Gem::Specification.new do |s| s.name = 'tritium' s.version = version s.platform = Gem::Platform::RUBY...
FIX issue with unpredictable dates using faker gem
# Auto-generated by Remi. # Add user-customizations to env_app.rb require 'bundler/setup' require 'remi' require 'remi/cucumber' Remi::Settings.log_level = Logger::ERROR Before do # Restart the random number generator prior to each scenario to # ensure we have reproducibility of random output Kernel.srand(3598...
# Auto-generated by Remi. # Add user-customizations to env_app.rb require 'bundler/setup' require 'remi' require 'remi/cucumber' Remi::Settings.log_level = Logger::ERROR Before do # Restart the random number generator prior to each scenario to # ensure we have reproducibility of random output Kernel.srand(3598...
Add presence validations and email format validation
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable belongs_to :organisation def send_welcome_email ...
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable belongs_to :organisation validates :first_name, :la...