Created
September 9, 2022 17:27
-
-
Save fractaledmind/f01e24a3691687393b7e2ed346d29d80 to your computer and use it in GitHub Desktop.
Ruby on Rails model interfaces
This file contains 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
# 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 |
This file contains 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
# 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 |
This file contains 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 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