Skip to content

Instantly share code, notes, and snippets.

Avatar

Malcolm Locke malclocke

  • Christchurch, New Zealand
View GitHub Profile
View sequel_add_associated_object_test_case.rb
require 'sequel'
require 'logger'
DB = Sequel.sqlite(loggers: [Logger.new(STDOUT)])
DB.create_table :authors do
primary_key :id
String :name
end
View csv_converter_example.rb
#
# Example of how to convert CSV data on read, in this case parsing
# some JSON in a CSV.
#
require 'csv'
require 'json'
csv = <<EOT
id,json_stuff
1,"{""foo"":""bar""}"
View dates.sh
echo -n "3pm Christmas Day in LA in local timezone: "
date --date 'TZ="America/Los_Angeles" 2016-12-25T15:00'
echo -n "3pm Christmas Day in LA in London: "
TZ="Europe/London" date --date 'TZ="America/Los_Angeles" 2016-12-25T15:00'
View rake_task_integration_spec.rb
# Example integration spec for a Rake task in Rails
#
# cat <<EOT > lib/tasks/myapp.rake
# namespace :myapp do
# task :mytask => :environment do
# puts "Hello"
# end
# end
# EOT
@malclocke
malclocke / papertrail-archive.sh
Last active Nov 25, 2015
Requires `jq` binary
View papertrail-archive.sh
#!/bin/bash
usage() {
cat <<EOT
Usage: PAPERTRAIL_API_TOKEN=abc123 $0 directory
Save all papertrail archives to outdir. Existing files will not be
overwritten if they have the correct filesize.
PAPERTRAIL_API_TOKEN can be found under the 'Me -> Profile' in Papertrail,
View classvars.rb
class Animal
@@noise = nil
def speak
@@noise
end
end
class Dog < Animal
@@noise = 'Woof'
View case_insensitive_hash_writer.rb
require 'delegate'
class CaseInsensitiveHashWriter < SimpleDelegator
def []=(key, value)
return __getobj__[key] unless key.respond_to?(:downcase)
matched_key = keys.detect do |k|
k.respond_to?(:downcase) && k.downcase == key.downcase
end
if matched_key
__getobj__[matched_key] = value
View cleaned_rails_backtrace.rb
# Log an exception with the backtrace cleaned as per the 'Application Trace'
# in the development mode browser exception view.
logger.error(
"some_tag: exception = %s: %s" % [
exception.inspect,
Rails.backtrace_cleaner.clean(exception.backtrace)
]
)
View first_matching_key_value_spec.rb
def value_of_first_matching_key_in_hash(hash, array_of_keys)
end
describe do
it 'searches a hash for an array of keys and returns the value of the first found' do
keys = [:a, :b, :c]
hash = {:c => 3, :b => 2, :a => 1}
expect(value_of_first_matching_key_in_hash(hash, keys)).to eql 1
View validate_models.rake
desc <<-EOT
Display the id and error messages of all invalid instances of each model in
model_classes, which should be a comma separated list of model names. If
model_classes is blank all models will be reported.
EOT
task :validate_models, [:models] => :environment do |t, args|
model_classes = if args[:models]
args[:models].split(',').map(&:constantize)
else
Rails.application.eager_load!