Skip to content

Instantly share code, notes, and snippets.

@fractaledmind
Created September 9, 2022 17:27
Show Gist options
  • Save fractaledmind/f01e24a3691687393b7e2ed346d29d80 to your computer and use it in GitHub Desktop.
Save fractaledmind/f01e24a3691687393b7e2ed346d29d80 to your computer and use it in GitHub Desktop.
Ruby on Rails model interfaces
# frozen_string_literal: true
module ArtifactInterface
extend ActiveSupport::Concern
extend Interfaceable
def key
raise NotImplementedError
end
def uid
raise NotImplementedError
end
def display_name
raise NotImplementedError
end
def display_type
raise NotImplementedError
end
def display_svg_file
raise NotImplementedError
end
def display_url
raise NotImplementedError
end
end
# frozen_string_literal: true
module Interfaceable
class InterfaceNotImplementedError < NoMethodError
end
def verify(model, instance = nil)
return if verifying_ar_model_but_migrations_not_run?
instance ||= model.new
unimplemented_instance_methods = instance_methods - instance.methods
return true if unimplemented_instance_methods.empty?
methods_not_implemented(model, unimplemented_instance_methods)
end
private
def methods_not_implemented(klass, *methods)
fail InterfaceNotImplementedError,
"#{klass} needs to implement #{methods.join(", ")} for interface #{name}!"
end
def verifying_ar_model_but_migrations_not_run?
return false unless defined? ActiveRecord::Base
ActiveRecord::Base.connection.data_sources.empty?
end
end
class Jira::Issue < ApplicationRecord
# ...
ArtifactInterface.verify(self)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment