[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Thought I'd share my alias

Trans

11/10/2007 11:28:00 AM


class Module

# As with alias_method, but alias both reader and writer.
#
# attr_accessor :x
# self.x = 1
# alias_accessor :y, :x
# y #=> 1
# self.y = 2
# x #=> 2

def alias_accessor(*args)
orig = args.last
args = args - [orig]
args.each do |name|
alias_method(name, orig)
alias_method("#{name}=", "#{orig}=")
end
end

def alias_reader(*args)
orig = args.last
args = args - [orig]
args.each do |name|
alias_method(name, orig)
end
end

def alias_writer(*args)
orig = args.last
args = args - [orig]
args.each do |name|
alias_method("#{name}=", "#{orig}=")
end
end

end


1 Answer

Dumaiu

12/9/2007 2:41:00 PM

0

On Nov 10, 6:28 am, Trans <transf...@gmail.com> wrote:
> class Module
>
> # As with alias_method, butaliasboth reader and writer.
> #
> # attr_accessor :x
> # self.x = 1
> # alias_accessor :y, :x
> # y #=> 1
> # self.y = 2
> # x #=> 2
>
> def alias_accessor(*args)
> orig = args.last
> args = args - [orig]
> args.each do |name|
> alias_method(name, orig)
> alias_method("#{name}=", "#{orig}=")
> end
> end
>
> def alias_reader(*args)
> orig = args.last
> args = args - [orig]
> args.each do |name|
> alias_method(name, orig)
> end
> end
>
> def alias_writer(*args)
> orig = args.last
> args = args - [orig]
> args.each do |name|
> alias_method("#{name}=", "#{orig}=")
> end
> end
>
> end

Okay. I'd say shorten

> orig = args.last
> args = args - [orig]

to 'orig = args.pop'.

Actually, if I were using this myself I would write

def alias_accessor(orig, first_alias, *aliases)
aliases.unshift(first_alias)
aliases.each ...

which is more idiomatic, I think, for variadic methods. I don't think
imitation of alias_method()'s parameter order is worth the decrease in
elegance.