Skip to content

Instantly share code, notes, and snippets.

@reggieb
Last active June 29, 2016 10:07
Show Gist options
  • Save reggieb/3e869939c4b208e14216cda46667cda7 to your computer and use it in GitHub Desktop.
Save reggieb/3e869939c4b208e14216cda46667cda7 to your computer and use it in GitHub Desktop.
How to define method to be over-ridden in child classes
class Parent
def self.to_be_over_ridden
raise "Class method `#{__method__}` must be defined in #{name}"
end
def to_be_over_ridden
raise "Instance method `#{__method__}` must be defined in #{self.class.name}"
end
end
class Child < Parent
def self.to_be_over_ridden
puts "Foo"
end
def to_be_over_ridden
puts "Bar"
end
end
class NaughtyChild < Parent
end
# Outputs: "Bar"
Child.new.to_be_over_ridden
# Outputs: "Foo"
Child.to_be_over_ridden
# Raises error with message "Instance method `to_be_over_ridden` must be defined in NaughtyChild"
begin
NaughtyChild.new.to_be_over_ridden
rescue => e
puts e.message
end
# Raises error with message "Class method `to_be_over_ridden` must be defined in NaughtyChild"
begin
NaughtyChild.to_be_over_ridden
rescue => e
puts e.message
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment