Created
November 14, 2018 19:02
-
-
Save jameswritescode/ef6095e885ce55b103f4f4ca61df1264 to your computer and use it in GitHub Desktop.
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
class ApplicationRecord < ActiveRecord::Base | |
self.abstract_class = true | |
class << self | |
# implements would take a list of modules and verify that the model "implementing" | |
# defines the methods inside of the interface on itself | |
def implements(*interfaces) | |
interfaces_with_methods = interfaces.map do |interface| | |
[interface.name, interface.instance_methods(false)] | |
end | |
interfaces_with_methods.each do |interface_name, interface_methods| | |
verify_implements(interface_name, interface_methods) | |
end | |
end | |
private | |
def self_defined_methods | |
@self_defined_methods ||= instance_methods(false) | |
end | |
def verify_implements(interface_name, interface_methods) | |
interface_methods.each do |method_name| | |
unless self_defined_methods.include?(method_name) | |
raise NotImplementedError, "#{name} does not implement #{method_name} from #{interface_name}" | |
end | |
end | |
end | |
end | |
end |
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
module Interface | |
# Documentation on what `some_method` is used for, and what the implementation expects | |
def method_to_implement; end | |
end |
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
class Model < ApplicationRecord | |
# Will raise an error if the methods defined in Interface aren't implemented on Model | |
implements Interface | |
def method_to_implement | |
# ... | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment