Skip to content

Instantly share code, notes, and snippets.

View brainopia's full-sized avatar

Ravil Bayramgalin brainopia

View GitHub Profile
# magic double assignment
a = [[a,1]] # => [[[[nil, 1]], 1]]
# fun with constant resolution
class Magic
def self.const_missing(const)
'for children'
end
end
p Magic::Bunny # => for children
# Module.constants allows you to check all available at point of call constants
module Bar
AvailableUnderNamespace = :constant
end
class Foo
include Bar
p Module.constants.include?(:AvailableUnderNamespace) # => true
end
class Fiber
yield_method = method(:yield)
resume_method = instance_method(:resume)
singleton_class.send(:define_method, :yield) do |*args|
puts "yield #{Fiber.current}"
yield_method.call *args
end
define_method(:resume) do |*args|
# skip initialize
Klass.allocate
__END__
right way depends on use case but it can include
- extraction of current initialize logic to separate class method
- extraction of desired methods into modules which then extended on itself
# famous trick from The Ruby Way to detect whether default value was used or not
def foobar(variable=((default=true);:value))
p variable, default
end
foobar :value # => default = nil
foobar # => default = true
# right way (won't work for nil and false but who cares)
equire 'celluloid'
module Observable
def start_notifier
receive do |it|
if it.is_a? Celluloid::Actor
wait :done
it.signal :notification
end
end
@brainopia
brainopia / gist:1687755
Created January 27, 2012 08:16
benchmark change for rack
require 'benchmark/ips'
class Boo < Hash
def previous_to_hash
{}.replace self
end
def new_to_hash
Hash[self]
end
@brainopia
brainopia / gist:1687067
Created January 27, 2012 04:55
example of customizing ruby docs for yourself
#!/usr/bin/env ruby
files = `find sources -type f`.split
def toplevel(path)
%r{ruby-1.9.3-p0/#{path}}
end
files -= files.grep toplevel %r{bootstraptest|(ext/(-test|curses)|symbian|bcc32|benchmark|def|doc|enc|bin|spec|misc|template|tool|sample|man|test|ext/tk)}
files -= files.grep %r{(win32|lib/rdoc|/\.)}
class @SortableTable
constructor: (table, options) ->
@table = $(table).children('tbody')
@columnSelector = options.columnSelector || 'th'
@iconSelector = options.iconSelector
@rowMapper = options.rowMapper
@afterSort = options.afterSort
@enable()
getColumn: (element) ->