Skip to content

Instantly share code, notes, and snippets.

@kazu69
Last active October 22, 2021 13:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazu69/a8563d70fdad6d453ffb to your computer and use it in GitHub Desktop.
Save kazu69/a8563d70fdad6d453ffb to your computer and use it in GitHub Desktop.
ruby method overwrite (monkey patch pattern)
class Country
def home
'Japan'
end
end
# -----
module ExtendContry
def new_home
"Fukuoka Japan"
end
end
class Country
include ExtendContry
alias_method :old_home, :home
alias_method :home, :new_home
end
Country.new.home # => Fukuoka Japan
Country.new.old_home # => Japan
Country.ancestors
# => [Country, ExtendContry, Object, PP::ObjectMixin, Kernel, BasicObject]
class Country
def home
'Japan'
end
end
# ----
class DelegateCountry < DelegateClass(Country)
def initialize(country)
super
end
def home
"Fukuoka #{super}"
end
end
contry = DelegateCountry.new(Country.new)
contry.home # => Fukuoka Japan
class Contry
def home
'Japan'
end
end
# -----
module ExtendContry
def home
"Fukuoka #{super}"
end
end
class Country
include ExtendContry
end
Country.new.home # => Japan
Country.ancestors
# => [Country, ExtendContry, Object, PP::ObjectMixin, Kernel, BasicObject]
class Country
def home
'Japan'
end
end
# -----
class Prefecture < Country
alias_method :old_home, :home
def home
"Fukuoka #{super}"
end
end
Prefecture.new.home # => Fukuoka Japan
Prefecture.new.old_home # => Japan
Prefecture.ancestors
# => [Prefecture, Country, Object, PP::ObjectMixin, Kernel, BasicObject]
class Country
def home
'Japan'
end
end
# ----
class Prefecture
def home
method = Country.instance_method(:home)
"Fukuoka #{method.bind(Country.new).call()}"
end
end
Prefecture.new.home # Fukuoka Japan
class Country
def home
'Japan'
end
end
module ExtendCountry
def home
"Fukuoka #{super}"
end
end
class Prefecture < Country
prepend ExtendCountry
end
Prefecture.new.home # => Fukuoka Japan
Country.new.home # => Japan
refecture.ancestors
# => [ExtendCountry, Prefecture, Country, Object, PP::ObjectMixin, Kernel, BasicObject]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment