Skip to content

Instantly share code, notes, and snippets.

module PartiallyApplicable
def apply_partially(new_name, old_name, *fixed_args)
define_method(new_name) do |*args|
self.send(old_name, *(fixed_args + args))
end
end
end
class MyClass
extend PartiallyApplicable
each_slice = (ary, slice_size) ->
for i in [0...ary.length] by slice_size
ary.slice(i, i + slice_size)
console.log each_slice("abcd", 2)
console.log each_slice("abcde", 2)
console.log each_slice("", 2)
#!/usr/bin/env ruby
require 'benchmark'
require 'ostruct'
unlocked = 100000.times.map { o = OpenStruct.new; o.timestamp = Time.now - Kernel.rand(10000000); o } ; nil
method1 = lambda {
achievements_per_day = Hash.new(0)
unlocked.each do |achievement|
class Module
def hookable(method_name)
return nil if method_defined?("#{method_name}_without_hooks")
alias_method "#{method_name}_without_hooks", method_name
metaclass = class << self; self; end
hooks = []
define_method(method_name) do |*arguments|
hooks.inject(lambda { |*args| send("#{method_name}_without_hooks", *args) }) do |blk, next_blk|
#!/usr/bin/ruby
result = `/usr/bin/osascript <<EOT
tell application "Terminal"
activate
set Input to display dialog "Gimme some text:" with title "Hello" with icon 0 default answer "" buttons {"OK"} default button 1
return text returned of Input as string
end tell
EOT
`
def draw_chart(collection, attribute=nil, &block)
if attribute
grouped = collection.group_by(&attribute)
elsif block
grouped = collection.group_by(&block)
else
raise "Must provide either an attribute or block to group by!"
end
# try to sort them, but if they're not sortable, don't worry about it
# Recursively retrieve nested attributes (or method calls) from an object.
def get_path(obj, *path)
if obj.is_a?(Array)
obj.map { |o| get_path(o, *path) }
else
if path.count > 1
next_obj = obj.send(path.first)
get_path(next_obj, *path.drop(1))
else
obj.send(path.first)
@rf-
rf- / 1.rb
Created December 22, 2011 07:35
[1] pry(main)> def x
[1] pry(main)* puts 'called x'
[1] pry(main)* callcc { |cc| return cc }
[1] pry(main)* end
=> nil
[2] pry(main)> def y
[2] pry(main)* puts 'called y'
[2] pry(main)* x.call
[2] pry(main)* ensure
[2] pry(main)* puts 'ensure block'
require 'pry'
require 'pry-exception_explorer'
require 'pry-exception_explorer/shim_builder'
binary_name = "lib_overrides.#{PryExceptionExplorer::ShimBuilder::Dyname}"
if !File.exists? File.join PryExceptionExplorer::ShimBuilder.dir, binary_name
puts "First run, building shim"
PryExceptionExplorer::ShimBuilder.compile
puts "Hopefully built...!"
@rf-
rf- / validator.rb
Created April 6, 2012 19:57
Demonstrate validation of arbitrary fields (e.g., hstore)
#!/usr/bin/env ruby
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => ':memory:'
)
ActiveRecord::Schema.define do