Skip to content

Instantly share code, notes, and snippets.

@jaxn
Last active January 5, 2017 19:11
Show Gist options
  • Select an option

  • Save jaxn/462a6440f488ef3e9931725da47cf116 to your computer and use it in GitHub Desktop.

Select an option

Save jaxn/462a6440f488ef3e9931725da47cf116 to your computer and use it in GitHub Desktop.
Interface pattern for Single Table Inheritance model in Rails
# An example driver with multiple implementations
#
# Allows documentation on the parent class while implementing functionality on the child classes.
# Raises a NoMethodError if the child class does not implement a documented method
class InterfaceDriver < ActiveRecord::Base
self.inheritance_column = :type
def abstract( method ) #:nodoc:
raise NoMethodError.new("undefined abstract method `#{method}' called for InterfaceDriver <#{self.class}:#{self.id}>")
end
# Performs Some Action using the appropriate driver
#
# === Examples
# FacebookDriver.first.do_something
# GoogleDriver.first.do_something
# InterfaceDriver.where(type: 'FacebookDriver').first.do_something
# InterfaceDriver.new.do_something # => NoMethodError
def do_something
abstract( __method__ )
end
end
class GoogleDriver < InterfaceDriver
def do_something
# code to do something on Google
end
end
class FacebookDriver < InterfaceDriver
def do_something
# code to do something on Facebook
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment