Skip to content

Instantly share code, notes, and snippets.

@jameswritescode
Created November 14, 2018 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jameswritescode/ef6095e885ce55b103f4f4ca61df1264 to your computer and use it in GitHub Desktop.
Save jameswritescode/ef6095e885ce55b103f4f4ca61df1264 to your computer and use it in GitHub Desktop.
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
module Interface
# Documentation on what `some_method` is used for, and what the implementation expects
def method_to_implement; end
end
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