> I'm more curious what you intend to do with this. There may be a more
> ruby way of doing what you want rather than just making something work
> the way it does in another language. What is the use case for this
> sort of thing? When you have the ability to do what you want, what
> does that get you?
Isn't it obvious?
No, it isn't.
It gets you knowledge of the calling layer from an
instance perspective and it typically makes callback oriented code more
trivial. It makes the object self aware of its calling environment.
For abstraction purposes, when I create ab4355 for myself and that
object talks to a log file, the network, or some foreign callback
environment it can identify itself as such "built in". This is
sometimes far more important than whatever glamor the object might have
as a standalone, especially when you have 1000's of simple short lived
objects.
If you want to track object creation you could do something along these
lines:
class Tracker
module CreationStackAccess
attr_reader :__created__
end
def initialize
@stacks = Hash.new {|h, k| k.each(&:freeze); k.freeze; h[k] = k}
end
def new(clazz, *a, &b)
stack = @stacks[caller]
clazz.new(*a, &b).tap do |obj|
obj.instance_variable_set('@__created__', stack)
obj.extend CreationStackAccess
end
end
end
class Foo
def initialize
yield 123 if block_given?
end
end
$TRACKER = Tracker.new
f = $TRACKER.new Foo
p f.__created__
foos = 10.times.map { $TRACKER.new Foo }
foos.each do |f|
printf "%10s %p\n", f.__created__.object_id, f.__created__
end
Of course you can also integrate that functionality into Class instances if
you find Foo.new_tracked or even Foo.new nicer than the method on another
instance. The main idea remains: you explicitly track creation of specific
"interesting" objects and record their creation call stack. The code
additionally stores only one instance per different call stack to keep the
memory overhead under control.
However, generally I'd say if objects need to be identifiable in some way
for logging purposes you should add fields that record information that you
reasonably want to log. Automatically tracking all creations of instances
is more like a debugging feature which should not be present in production
code because of the overhead. My two cents.
Cheers
robert
···
On Sat, Mar 8, 2014 at 5:07 AM, Kape Kape <lists@ruby-forum.com> wrote:
--
[guy, jim].each {|him| remember.him do |as, often| as.you_can - without end}
http://blog.rubybestpractices.com/