Skip to content

Instantly share code, notes, and snippets.

@delba
Last active December 17, 2015 11:29
Show Gist options
  • Select an option

  • Save delba/5602039 to your computer and use it in GitHub Desktop.

Select an option

Save delba/5602039 to your computer and use it in GitHub Desktop.
Method Objects and Aliasing
class Person
def greet(name)
"Hello, #{name}!"
end
end
Person.instance_method(:greet).bind(Object.new)["World"]
#=> TypeError: bind argument must be an instance of Person
module Greeter
def greet(name)
"Hello, #{name}"
end
end
Greeter.instance_method(:greet).bind(Object.new)["World"]
#=> "Hello, World!"
#-------------------------------------------------------------------------------
module Greeter
def greet(name)
"Hello, #{name}"
end
end
class Person
include Greeter
end
Person.instance_method(:greet).bind(Object.new)["World"]
#=> TypeError: bind argument must be an instance of Person
module Spy
def hello
@name
end
end
class Person
def initialize(name)
@name = name
end
end
delba = Person.new('delba')
spy = Spy.instance_method(:hello)
spy.bind(delba).call #=> delba
module Trashable
def destroy
'hacked destroy'
end
end
class ActiveRecord::Base
def self.acts_as_trashable
alias destroy! destroy #=> :destroy == ActiveRecord::Base.instance_method(:destroy)
# alias_method :destroy!, :destroy => :destroy == ActiveRecord::Base.instance_method(:destroy)
include Trashable
# alias destroy! destroy => :destroy == ActiveRecord::Base.instance_method(:destroy)
# alias_method :destroy!, :destroy => :destroy == Paranoia.instance_method(:destroy)
end
def destroy
'original destroy'
end
end
class HulaHoop < AR
acts_as_trashable
end
hula_hoop = HulaHoop.new
hula_hoop.destroy #=> 'hacked destroy'
hula_hoop.destroy! #=> 'original destroy'
module Trashable
def destroy
'hacked destroy'
end
def destroy!
ActiveRecord::Base.instance_method(:destroy).bind(self).call
end
end
class ActiveRecord::Base
def destroy
'original destroy'
end
end
class HulaHoop < ActiveRecord::Base
include Trashable
end
hula_hoop = HulaHoop.new
hula_hoop.destroy #=> 'hacked destroy'
hula_hoop.destroy! #=> 'original destroy'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment