Last active
January 5, 2017 19:11
-
-
Save jaxn/462a6440f488ef3e9931725da47cf116 to your computer and use it in GitHub Desktop.
Interface pattern for Single Table Inheritance model in Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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