alias callback

T

Trans

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.
 
M

micathom

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
 
G

George Ogata

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
 
T

Trans

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,245
Latest member
Evelyne64L

Latest Threads

Top