Skip to content

Instantly share code, notes, and snippets.

@stevecj
stevecj / gist:9ace6a70370f6d1a1511
Last active December 2, 2019 06:34
Ruby will destructure objects that are not arrays, but respond to #to_ary
S=Struct.new(:a,:b)
ss = [S.new(1,2), S.new(3,4)]
p ss.map{|a,b| "#{a} #{b}" }
# => ["#<struct S a=1, b=2> ", "#<struct S a=3, b=4> "]
class S ; def to_ary ; to_a ; end ; end
p ss.map{|a,b| "#{a} #{b}" }
# => ["1 2", "3 4"]
@stevecj
stevecj / ruby_nesting_unmuddling.rb
Created March 16, 2012 18:31
Understanding and unscrambling Ruby's weird module nesting behavior
# Get ourselves a clean, top-level binding.
def main_binding
binding
end
module ModuleUtils
module ModuleMethods ; end
self.extend ModuleMethods
module ModuleMethods
@stevecj
stevecj / flatten-it.rb
Last active March 30, 2016 08:49
Coding exercise: Flatten an array in Ruby w/o using `Array#flatten`
module ArrayUtils
def self.flatten(array, result=[])
array = Array(array)
array.each do |entry|
case entry
when Array
flatten entry, result
else
result << entry
end
@stevecj
stevecj / deferred_uniqueness_validations.rb
Created March 7, 2013 21:32
Allow any ActiveRecord uniqueness validation(s) to be deferred, and only check after a failed save due to uniqueness violation error from the database.
# ./config/initializers/deferred_uniqueness_validations.rb
#
# This initializer adds support for deferred processing of
# ActiveRecord uniqueness validations. When a uniqueness
# validation is deferred using the :deferred => true option, it is
# not checked before save. Instead, if there is a uniqueness
# constraint defined for the column in the database, and if the
# save operation raises an ActiveRecord::RecordNotUnique
# exception, then the validation is performed so that the precise
# cause can be determined and the appropriate error information
@stevecj
stevecj / fiber_demo.rb
Created February 4, 2013 05:53
A demonstration of transfer of control to/from a Fiber in Ruby 1.9.x.
fib = Fiber.new do |val|
puts ' -- 2 --'
puts 'fiber started & got: ' + val
puts 'now yield with "1st yield"'
val = Fiber.yield('fiber yield 1')
puts ' -- 4 --'
puts '1st yield got: ' + val
puts 'now yield with "2nd yield"'
@stevecj
stevecj / sleep_request.rb
Last active December 11, 2015 08:58
Cleanly stoppable beaneater/beanstalkd agent. Waits for currently executing task to complete before stopping for INT (Ctrl+c) or TERM (kill) signals or receipt of an enqueued stop job.
#!/usr/bin/env ruby
require 'rubygems'
require 'bundler'
require 'beaneater'
beanstalk = Beaneater::Pool.new(['localhost:11300'])
sleep_tube = beanstalk.tubes['sleeper-take-a-nap']
sleep_tube.put '-'
@stevecj
stevecj / computes_recursively.rb
Last active November 27, 2015 03:13
Fake tail recursion in Ruby without relying on tail optimization support in the Ruby VM
# This is a mixin module that adds support for tail-recursive
# style programming in Ruby without relying on any true tail
# recursion optimization in the Ruby virtual machine.
#
# Since tail recursion calls are actually deferred until after
# returning from the method that invoked #tail, recursions can
# be "nested" to an unlimited depth without overflowing the
# stack.
#
# The including module can define tail-recursive methods within
@stevecj
stevecj / defines_interface.rb
Created October 11, 2012 13:16
Interfaces for Ruby
# A module for inclusion in a class of objects that delegate to and
# provide restricted interface definitions for underlying "occurrence"
# objects.
#
# This is useful for purposes such as to enforce the same API for a
# unit under test as for mocks and stubs of the same unit used for
# testing other units.
#
# This is a proof of concept demonstration and is not well-tested,
# production-ready code.
@stevecj
stevecj / ruby_module_nesting.rb
Created March 13, 2012 18:03
Ruby module nesting and scope of constant names
# == Module name assignment ==
# A Ruby module's name is determined when it first becomes
# assigned as the value of a top-level constant or of a
# constant in a module that has received a name.
# The module's name represents the hierarchy of containership,
# and is not dependent upon the execution path of the code
# that defined the module (as opposed to the module nesting
# for defined methods -- see below).
p [self, self.class, Module.nesting] # => [main, Object, []]
@stevecj
stevecj / enhanced_attributable.rb
Last active September 30, 2015 20:47
Ruby attr_accessor enhancement
# Include this module in a class to add enhanced attr_accessor
# functionality. With this module included, ...
#
# * You may provide a block to an attr_accessor call that accepts
# a base attribute name and returns a default value for each
# instance attribute.
# * Any attribute name consisting of a base name followed by a
# "?" suffix represents a boolean attribute.
#
# If the including class has its own #initialize method, that