[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

alias callback

Trans

1/30/2007 12:50:00 PM

How does one reflect on alias definitions. Using #method_added only
gives you the name of the alias being defined --as if it were a new
method. And it's not possible to override 'alias' b/c it's not a real
method.

Ideas?

Thanks,
T.


3 Answers

ThoML

1/30/2007 2:25:00 PM

0

Module has a method alias_method, which could be overridden. Probably
not quite what you're looking for.

AFAIK alias duplicates the method (not really an alias), hence the
described behaviour.

class A
def a
1
end
alias b a
end

class A
def a
2
end
end

A.new.b
=> 1

George

1/31/2007 11:49:00 AM

0

On 1/30/07, Trans <transfire@gmail.com> wrote:
> How does one reflect on alias definitions. Using #method_added only
> gives you the name of the alias being defined --as if it were a new
> method. And it's not possible to override 'alias' b/c it's not a real
> method.
>
> Ideas?

UnboundMethod#== returns true for aliases, so hopefully:

class Module
def alias?(name)
name = name.to_s
instance_method = instance_method(name)
(instance_methods + private_instance_methods).any? do |n|
n != name && instance_method(n) == instance_method
end
end
end

Bit of a test:

require 'test/unit'
class AliasTest < Test::Unit::TestCase
def test_by_alias
klass = Class.new do
def foo
end
def bar
end
alias baz foo
end
assert klass.alias?(:foo)
assert !klass.alias?(:bar)
assert klass.alias?(:baz)
end
def test_by_alias_method
klass = Class.new do
def foo
end
def bar
end
alias_method :baz, :foo
end
assert klass.alias?(:foo)
assert !klass.alias?(:bar)
assert klass.alias?(:baz)
end
def test_across_inheritance
klass = Class.new{alias foo object_id}
assert klass.alias?(:foo)
assert klass.alias?(:object_id)
end
def test_nonalias
klass = Class.new{def foo; end}
assert !klass.alias?(:foo)
end
def test_builtin
assert Array.alias?(:size)
assert Array.alias?(:length)
assert !Array.alias?(:clear)
end
end

Trans

1/31/2007 7:46:00 PM

0

On Jan 31, 6:48 am, "George Ogata" <george.og...@gmail.com> wrote:
> On 1/30/07, Trans <transf...@gmail.com> wrote:
>
> > How does one reflect on alias definitions. Using #method_added only
> > gives you the name of the alias being defined --as if it were a new
> > method. And it's not possible to override 'alias' b/c it's not a real
> > method.
>
> > Ideas?
>
> UnboundMethod#== returns true for aliases, so hopefully:

Good thinking!

> class Module
> def alias?(name)
> name = name.to_s
> instance_method = instance_method(name)
> (instance_methods + private_instance_methods).any? do |n|
> n != name && instance_method(n) == instance_method
> end
> end
> end

[snip]


Nice. I'll give this a whril and put it in Facets, crediting you.

Super Thanks!!!
T.