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.
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.
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
On 1/30/07, Trans [email protected] 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
On Jan 31, 6:48 am, “George O.” [email protected] wrote:
On 1/30/07, Trans [email protected] 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.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs