12

I wish to put two aliases for one original method, but i don't see the ability of alias_method to do multiple aliases at once, rather one by one.

So is there a possibility to change from this:

alias_method :aliased_first_method, :first_method
alias_method :aliased_first_method?, :first_method

to something like this:

alias_method [:aliased_first_method, :aliased_first_method?], :first_method

I'm not interested in creating custom methods.

Zippie
  • 6,018
  • 6
  • 31
  • 46
  • I don't see much sense in that, but if you want to have a one-liner, you could do: `[:aliased_first_method, :aliased_first_method?].each {|name| alias_method name, :first_method}` (and put that into another method in `Class`, to give it a name if you want) – tessi Nov 14 '13 at 13:49
  • it makes sense if you have the upper code repeated two times in a row. – Zippie Nov 14 '13 at 13:55

3 Answers3

20

I do not think there is a better way than just using each:

[:aliased_first_method, :aliased_first_method?].each{|ali| alias_method ali, :first_method}

Edit 2021 Ruby 2.7+

%i[aliased_first_method aliased_first_method?].each{ alias_method _1, :first_method]}
Gijs P
  • 1,325
  • 12
  • 28
hirolau
  • 13,451
  • 8
  • 35
  • 47
  • Not what i was looking for, but thank you. I thought maybe Ruby has something built in by default – Zippie Nov 14 '13 at 13:56
  • I understand your desire, but this answer is correct. AFAIK, there is no built-in way to do this. – Phrogz Nov 14 '13 at 14:02
3

Looking at the docs and source of alias_method, I would say that what you want is not possible without a custom method.

(Just had to answer my almost namesake :))

zwippie
  • 15,050
  • 3
  • 39
  • 54
0

For future viewers, we are using this approach for something quite similar:

module HasBulkReplies
  extend ActiveSupport::Concern
  module ClassMethods
    # Defines responses to multiple messages
    # e.g. reply_with false, to: :present?
    #      reply_with "",    to: %i(to_s name description)
    #      reply_with true,  to: %i(empty? nothing? void? nix? nada? meaning?)
    def reply_with(with, to:)
      [to].flatten.each do |message|
        define_method message do
          with
        end
      end
    end
  end
end

This defines a DSL that allows us to:

class Work
  class Codes
    class NilObject
      include HasBulkReplies
      include Singleton

      reply_with true,
        to: :nil?

      reply_with false,
        to: %i(
          archaeology?
          childrens?
          educational_purpose?
          geographical?
          historical?
          interest_age?
David Aldridge
  • 51,479
  • 8
  • 68
  • 96