Sunday, November 08, 2015

Redefining a Private Method in Ruby

class ActiveRecord

  private

  def hi
    'I am private'
  end
end

class ActiveRecord

  def greet
    hi
  end


  private

  def hi
    'I am redining you'
  end

end

a = ActiveRecord.new

p a.greet

Monkey patching (Coding Horror):

class ActiveRecord

  private

  def hi
    'I am private'
  end
end

class MyActiveRecord < ActiveRecord

  def greet
    hi
  end


  private

  def hi
    'I am redefining you'
  end

end

a = MyActiveRecord.new

p a.greet

Unnecessary Complication:

class Client

  def print
    say
  end

  private
 
  def say
    "hello"
  end
end

# Create a subclass of Client
MyClient = Class.new(Client) do
  define_method(:say) do
    "hello from an overridden private method"
  end
end

puts MyClient.superclass

my_client = MyClient.new
puts my_client.print

Simpler Way to Accomplish the Same Thing:

class Client

  def print
    say
  end

  private
 
  def say
    "hello"
  end
end

class MyClient < Client
  def say
    "hello from an overridden private method"
  end
end

puts MyClient.superclass

my_client = MyClient.new
puts my_client.print