Skip to content

Instantly share code, notes, and snippets.

View Hampei's full-sized avatar

Henk van der Veen Hampei

View GitHub Profile
# Based on Dave Koelle's Alphanum algorithm
# Henk van der Veen 2022
# Inspired by https://github.com/aiekick/alphanum
# Released under the MIT License - https://opensource.org/licenses/MIT
#
# 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 use, copy, modify, merge, publish, distribute, sublicense,
# block gets key, value of each hash entry whose value is not a Hash or Array,
# should return a new key and value for that entry.
def deep_transform(obj, &block)
case obj
when Hash
obj.map do |key, val|
case val
when Hash, Array
[key, deep_transform(val, &block)]
else
@Hampei
Hampei / recursive_hash.rb
Created October 10, 2018 10:18
quick one-line hash creation with a default of a hash with a default of a hash with a default of a hash ...
my_hash = Hash.new {|h,k| h[k] = Hash.new(&h.default_proc) }
my_hash.dig('foo', 'bar', 'bla')
=> {}
my_hash
=> {"foo"=>{"bar"=>{"bla"=>{}}}}
@Hampei
Hampei / pass_block.rb
Created August 31, 2018 13:25
benchmark for passing a block
require 'benchmark'
def once_yield
yield
end
def call_proc(proc)
proc.call
end
@Hampei
Hampei / preloading_subassociations.rb
Last active August 21, 2018 09:15
How to preload associations of an association that is actually cached in the association_cache
# Using measurement.measured_questionnaires.preload(:questionnaire) would lead to reloading
# both the measured_questionnaires and the questionnaires each time you call it,
# requiring a explicit memoization somewhere which could go out of sync.
# usage: measurement.measured_questionnaires.with_questionnaires.map { ... }
class Measurement < ActiveRecord::Base
has_many :measured_questionnaires, -> { order(:position) } do
def with_questionnaires
ActiveRecord::Associations::Preloader.new.preload(self, :questionnaire)
self
end
@Hampei
Hampei / rsapply.R
Created May 3, 2017 14:52
recursive list apply for R
#' Recursive list apply, given a bunch of vectors and a function, creates lists of lists with the elements as keys
#' and values determined by fn.
#' @param ... vectors to loop over
#' @param fn function to execute for each leaf
#' @examples
#' grip:::rsapply(c('a', 'b'), c('f', 'g'), fn=function(x,y) c(x, y))
#' #> list(a=list(f=c('a', 'f'), g=c('a', 'g')), b=list(f=c('b', 'f'), g=c('b', 'g')))
rsapply <- function(..., fn) {
.rsapply <- function(el=NULL, ..., args=c(), fn) {
if(is.null(el)) return(do.call(fn, as.list(args)))
# default context :create when new, :update when persisted.
# Since rails 4.2 you can define add multipe contexts per validation
# Since rails 5.0 you can specify multiple context when saving/validating.
class Invoice < ApplicationRecord
validate :check_remote, on: [:create, :remote]
validate :check_total, on: [:create]
validate :foo, on: :remote
def check_remote
@Hampei
Hampei / keybase.md
Last active December 18, 2015 13:15
keybase.md

Keybase proof

I hereby claim:

  • I am hampei on github.
  • I am hampei (https://keybase.io/hampei) on keybase.
  • I have a public key whose fingerprint is D25C D55C C648 3FC1 F516 F81F 89B3 3D4C 7A32 A87B

To claim this, I am signing this object:

@Hampei
Hampei / appsignalque.rb
Last active August 29, 2015 14:08
appsignal stats and error handling for que.gem
module AppSignalQue
def _run(*args)
Appsignal.monitor_transaction(
'perform_job.que',
:class => self.class,
:method => 'run',
:attempts => attrs[:error_count],
:queue => attrs[:queue],
:queue_time => (Time.now.to_f - attrs['run_at'].to_f) * 1000,
) do
@Hampei
Hampei / active_interaction_aware_responder.rb
Last active August 29, 2015 14:06
active interaction aware responder
# For json and xml, will render the result if no errors where present.
# otherwise will just render the interaction, containing things like {'errors' => {'attr' => ['invalid']}}
class ActiveInteractionAwareResponder < ActionController::Responder
def to_format
if resource.is_a?(ActiveInteraction::Base)
if resource.errors.empty?
@resource = resource.result
@resources[-1] = @resource
end
end