Zippie
Zippie

Reputation: 6088

Alias a method multiple times

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.

Upvotes: 12

Views: 6708

Answers (3)

hirolau
hirolau

Reputation: 13921

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]}

Upvotes: 20

David Aldridge
David Aldridge

Reputation: 52396

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?

Upvotes: 0

zwippie
zwippie

Reputation: 15550

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 :))

Upvotes: 3

Related Questions