Permalink
Browse files

Added rubber.rb

  • Loading branch information...
1 parent 4e277e5 commit abc43c4882be38f71258b4707c53d5cfb5c16122 @alexdowad committed Jan 22, 2012
Showing with 45 additions and 0 deletions.
  1. +45 −0 rubber.rb
View
@@ -0,0 +1,45 @@
+# The name of this file refers to the way that highly dynamic languages
+# like Ruby can "bend like rubber" (through the use of metaprogramming
+# techniques)
+# It is a collection of various fun and interesting things I have done
+# with Ruby using metaprogramming
+# (I am planning to expand this over time)
+#*********************************************************************
+
+# Make object which fronts for two (or three, or four...)
+
+class Tee
+ def initialize(*objs); @objs = objs; end
+ def method_missing(m,*args,&b)
+ @objs.each { |o| o.__send__(m,*args,&b) }
+ end
+end
+
+# With that, you can do things like:
+# tee = Tee.new($stdout, File.new("log","w"))
+# tee.puts "Hello world AND log file!"
+
+#*********************************************************************
+
+# This was originally made for ActiveRecord...
+# With AR, you can have multiple in-memory objects which represent the
+# same DB record
+# This allows all the objects which represent the same record to share
+# other, transient "instance variables"
+
+require 'thread'
+
+class Class
+ def shared_attr(*attrs, options={})
+ attrs.each do |attr|
+ hash = Hash.new(options[:default])
+ mutex = Mutex.new
+ define_method(attr) do
+ mutex.synchronize { hash[self.id] }
+ end
+ define_method((attr.to_s+"=").to_sym) do |value|
+ mutex.synchronize { hash[self.id] = value }
+ end
+ end
+ end
+end

0 comments on commit abc43c4

Please sign in to comment.