Ruby

Ruby

Made by DeepSource

Bad use of alias detected RB-ST1002

Style
Minor
Autofix

#

Prefer alias when aliasing methods in lexical class scope as the resolution of self in this context is also lexical, and it communicates clearly to the user that the indirection of your alias will not be altered at runtime or by any subclass unless made explicit.

Bad practice

class Westerner
  def first_name
    @names.first
  end

  alias given_name first_name
end

Since alias, like def, is a keyword, prefer bareword arguments over symbols or strings. In other words, do alias foo bar, not alias :foo :bar.

Also be aware of how Ruby handles aliases and inheritance: an alias references the method that was resolved at the time the alias was defined; it is not dispatched dynamically.

Recommended

class Fugitive < Westerner
  def first_name
    'Nobody'
  end
end

In this example, Fugitive#given_name would still call the original Westerner#first_name method, not Fugitive#first_name. To override the behavior of Fugitive#given_name as well, you’d have to redefine it in the derived class.

class Fugitive < Westerner
  def first_name
    'Nobody'
  end

  alias given_name first_name
end

alias_method

Always use alias_method when aliasing methods of modules, classes, or singleton classes at runtime, as the lexical scope of alias leads to unpredictability in these cases.

module Mononymous
  def self.included(other)
    other.class_eval { alias_method :full_name, :given_name }
  end
end

class Sting < Westerner
  include Mononymous
end