Thought I'd share my alias

T

Trans

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
 
D

Dumaiu

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.
 

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

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top