Including modules => installing modules

I have some modules where I must use ‘alias’
in order to use them. But it tends to be nasty.

I guess its possible to make an install method, which creates
the necessary aliases and then extends the specified class.

Is this possible ?

How should it be done ?

···


Simon Strandgaard

expand -t2 a.rb
module ArrayStuff
def new_push(*ary)
puts “Array#push: enter - #{ary.inspect}”
old_push(*ary)
puts “Array#push: leave”
self
end
def ArrayStuff.install(klass)
# what should I write here ?
end
end

ArrayStuff.install(Array)

class Array
alias :old_push :push # nasty
include ArrayStuff
alias :push :new_push # nasty
end

p [1, 2].push([])
p [1, 2].push(
[4, 5])

ruby a.rb
Array#push: enter -
Array#push: leave
[1, 2]
Array#push: enter - [4, 5]
Array#push: leave
[1, 2, 4, 5]

I guess its possible to make an install method, which creates
the necessary aliases and then extends the specified class.

This is just an example

svg% cat b.rb
#!/usr/bin/ruby
module ArrayStuff
  def new_push(*ary)
    puts "Array#push: enter - #{ary.inspect}"
    old_push(*ary)
    puts "Array#push: leave"
    self
  end

  def self.append_features(klass)
     super
     klass.instance_eval do
        alias_method :old_push, :push
        alias_method :push, :new_push
     end
  end
end

class Array
  include ArrayStuff
end

p [1, 2].push(*)
p [1, 2].push(*[4, 5])
svg%

svg% b.rb
Array#push: enter -
Array#push: leave
[1, 2]
Array#push: enter - [4, 5]
Array#push: leave
[1, 2, 4, 5]
svg%

Guy Decoux

I guess its possible to make an install method, which creates
the necessary aliases and then extends the specified class.

[snip]

def self.append_features(klass)
super
klass.instance_eval do
alias_method :old_push, :push
alias_method :push, :new_push
end
end
[snip]

Wow, this is even nicer. I wasn’t aware of ‘append_features’.
Thanks Guy :wink:

···

On Tue, 24 Jun 2003 02:07:50 +0900, ts wrote:


Simon Strandgaard