Skip to content

Instantly share code, notes, and snippets.

View ryanlecompte's full-sized avatar

Ryan LeCompte ryanlecompte

View GitHub Profile
ruby-1.9.2-head :001 > class C
ruby-1.9.2-head :002?> def ==(o)
ruby-1.9.2-head :003?> puts "==(0)"
ruby-1.9.2-head :004?> super
ruby-1.9.2-head :005?> end
ruby-1.9.2-head :006?> def eql?(o)
ruby-1.9.2-head :007?> puts "eql?(o)"
ruby-1.9.2-head :008?> super
ruby-1.9.2-head :009?> end
ruby-1.9.2-head :010?> def hash
@ryanlecompte
ryanlecompte / gist:983460
Created May 20, 2011 18:15
example of overriding a method in class via mixin
class C
def initialize(*args)
puts "hi from C"
end
end
module M
def self.included(clazz)
clazz.class_eval do
alias_method :old_initialize, :initialize
@ryanlecompte
ryanlecompte / gist:952316
Created May 2, 2011 20:40
Example of flattening scopes
module M
def self.included(base)
base.class_eval do
singleton_class = (class << self; self; end)
singleton_class.send(:define_method, :foo) do
puts "in foo! base is #{base}"
end
end
end
end
ruby-1.9.2-head :001 > module M1
ruby-1.9.2-head :002?> def self.m1
ruby-1.9.2-head :003?> "self.m1 in M1"
ruby-1.9.2-head :004?> end
ruby-1.9.2-head :005?> end
=> nil
ruby-1.9.2-head :006 > module M2
ruby-1.9.2-head :007?> include M1
ruby-1.9.2-head :008?> def self.m2
ruby-1.9.2-head :009?> m1
def m1
commands = {:exit => Proc.new { break }}
loop do
commands[:exit].call
end
puts "Done!"
end
m1
@ryanlecompte
ryanlecompte / gist:904220
Created April 5, 2011 18:42
simple image retriever example
require 'open-uri'
url = 'http://www.hobotraveler.com/uploaded_images/207-249-tiger-nut-efio-togo-food-798405.jpg'
f = File.open('image.jpg', 'w')
open(url) { |io| f.puts(io.read) }
f.close
>> module M
>> x = 100
>> define_method(:x=) {|v| x = v }
>> define_method(:x) { x }
>> end
=> #<Proc:0x0000010102dfd0@(irb):4 (lambda)>
>> class A
>> include M
>> end
=> A
@ryanlecompte
ryanlecompte / gist:891728
Created March 29, 2011 02:52
BUG with Ruby 1.9.2 (MRI)
# The following fails with a failure to call "x=" private method
String.send(:attr_accessor, :x)
s = ""
s.x = 100
# The following works:
class String
self.send(:attr_accessor, :x)
end
s = ""