Skip to content

Instantly share code, notes, and snippets.

View anthonylewis's full-sized avatar

Anthony Lewis anthonylewis

View GitHub Profile
@anthonylewis
anthonylewis / features.rb
Last active December 19, 2015 22:19
An example using method_missing to add user features
require 'set'
class User
def initialize
@features = Set.new
end
def method_missing(meth, *args)
if meth.to_s =~ /^can_(.*)\?$/
@features.include? $1.to_s
@anthonylewis
anthonylewis / decorator.rb
Created July 18, 2013 04:18
An example of a method decorator in Ruby
module TrackMethods
def track(meth)
self.class_eval do
alias_method "old_#{meth}", meth
define_method meth do |*args|
puts "Calling #{meth} with #{args.join(', ')}"
self.send "old_#{meth}", *args
end
end
@anthonylewis
anthonylewis / callbacks.rb
Created July 18, 2013 04:17
An example using class instance variables
class Record
def self.before_save(*methods)
@callbacks ||= []
@callbacks += methods
end
def self.callbacks
@callbacks
end
@anthonylewis
anthonylewis / memoize.rb
Created July 18, 2013 04:16
An example of memoization using Ruby 2's module prepend.
module Memoize
def calc(n)
@@memo ||= {}
@@memo[n] ||= super
end
end
class Fibonacci
prepend Memoize
for i in 1..25
puts g.next
end
@anthonylewis
anthonylewis / gist:2257
Created July 24, 2008 19:22
A Ruby Generator for prime numbers
require 'generator'
g = Generator.new do |g|
n = 2
p = []
while true
if p.all? { |f| n % f != 0 }
g.yield n
p << n