Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby Fundamental - Alias para métodos de classe
# You didn't write this code
class ExternalClass
def self.class_number
123 # Just to exemplify
end
def some_number
456 # Just to exemplify
end
end
# You wrote this code
module SomeModule
def self.included(base)
base.class_eval do
alias_method :class_number_original, :class_number
alias_method :some_number_original, :some_number
def self.class_number
self.class_number_original + 200
end
def some_number
some_number_original + 100
end
end
end
end
ExternalClass.class_number # => 123
ExternalClass.send(:include, SomeModule)
# NameError: undefined method `class_number' for class `ExternalClass'
# from (pry):16:in `alias_method'
# You didn't write this code
class ExternalClass
def self.class_number
123 # Just to exemplify
end
def some_number
456 # Just to exemplify
end
end
# You wrote this code
module SomeModule
def self.included(base)
base.class_eval do
alias_method :some_number_original, :some_number
def some_number
some_number_original + 100
end
class << self
alias_method :class_number_original, :class_number
def class_number
class_number_original + 200
end
end
end
end
end
ExternalClass.class_number # => 123
ExternalClass.send(:include, SomeModule)
ExternalClass.class_number # => 323
# You didn't write this code
class ExternalClass
def self.class_number
123 # Just to exemplify
end
def some_number
456 # Just to exemplify
end
end
# You wrote this code
module SomeModule
def self.included(base)
base.send(:include, InstanceMethods)
base.extend(ClassMethods)
base.class_eval do
alias_method :some_number_original, :some_number
alias_method :some_number, :some_number_new
class << self
alias_method :class_number_original, :class_number
alias_method :class_number, :class_number_new
end
end
end
module InstanceMethods
def some_number_new
some_number_original + 100
end
end
module ClassMethods
def class_number_new
class_number_original + 200
end
end
end
ExternalClass.send(:include, SomeModule)
ExternalClass.class_number # => 323
ExternalClass.class_number_original # => 123
ExternalClass.class_number_new # => 323
ec = ExternalClass.new
ec.some_number # => 556
ec.some_number_original # => 456
ec.some_number_new # => 556
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment