Skip to content

Instantly share code, notes, and snippets.

View ianks's full-sized avatar

Ian Ker-Seymer ianks

View GitHub Profile
function maybePrint(x?: string) {
if (x != null) {
// we know that x will be a string in this scope
console.log(x);
}
}
@ianks
ianks / ts1.ts
Created June 21, 2017 21:57
ts1.ts
interface Named {
name: string;
}
let x: Named;
let y = { name: "John", age: 42 };
// This is OK because Y meets the interface requirements of Named
x = y;
# ...
expectation_mutex = Mutex.new
expect(client).to receive(:fetch_users) do |args|
expectation_mutex.synchronize do
expect(args).to eql(current_page)
end
# ...
end
it 'makes two requests to resolve the users when necessary' do
current_page = 1
expectation_mutex = Mutex.new
expect(client).to receive(:fetch_users).exactly(2).times do |args|
expect(args).to eql(current_page)
current_page += 1
it 'makes two requests to resolve the users when necessary' do
current_page = 1
expectation_mutex = Mutex.new
expect(client).to receive(:fetch_users).exactly(2).times do |args|
expect(args).to eql(current_page)
current_page += 1
class SomeAPI
def fetch_users
prom = if only_need_to_fetch_one_page?
client.fetch_page(1).then { |res| res.fetch('users') }
else
promises = Concurrent::Promise.zip(client.fetch_page(1), client.fetch_page(2))
promises.then do |first_page, second_page|
combine_results(first_page, second_page)
end
@ianks
ianks / ThreadsafeMemoized.rb
Created June 16, 2017 18:59
ThreadsafeMemoized
class ThreadsafeMemoized
def initialize
@memoized = {}
@mutex = Support::ReentrantMutex.new
end
def fetch_or_store(key)
@memoized.fetch(key) do # only first access pays for synchronization
@mutex.synchronize do
@memoized.fetch(key) { @memoized[key] = yield }
@ianks
ianks / kibana.rb
Last active March 14, 2017 19:03
Rails engine for AWS Kibana Auth
# frozen_string_literal: true
require 'aws-sdk'
# This will create an engine mounted at your subdomain of choice.
# If you wanted it to be `kibana.example.com`, set KIBANA_SUBDOMAIN="kibana".
# The engine can be routed in Rails like so:
# Rails.application.routes.draw do
# constraints subdomain: ENV.fetch('KIBANA_SUBDOMAIN') do
# frozen_string_literal: true
begin
require 'bundler/inline'
rescue LoadError => e
$stderr.puts 'Bundler version 1.10 or later is required.'
raise e
end
gemfile(true) do
source 'https://rubygems.org'
@ianks
ianks / has_one_bug.rb
Created October 25, 2016 00:14
ActiveRecord: unable to delete records with a `has_one, through:` relationship
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
gem "activerecord", "5.0.0"
gem "sqlite3"
end
require "active_record"
require "minitest/autorun"