# encoding: utf-8 require 'fedux_org_stdlib/require_files' require_library %w(find active_support/core_ext/object/blank active_support/core_ext/string/inflections) require 'fedux_org_stdlib/models/filesystem_based_model' module FeduxOrgStdlib module Models # model for import action module ClassBasedModel def self.included(base) base.extend ClassMethods end # Class methods module ClassMethods def require_path(name) path = File.join(library_name.underscore, model_name.pluralize.underscore, name.to_s) FeduxOrgStdlib.logger.debug(self) { "Path to instances of model \"#{name}\": #{path}" } path end def exception_for_model "#{library_name}::Exceptions::Invalid#{model_name}".constantize rescue raise FeduxOrgStdlib::Models::Exceptions::ExceptionNeedsToBeImplemented, "Exception \"#{library_name}::Exceptions::Invalid#{model_name}\" does not exist." end def check_klass(klass, *methods) fail exception_for_model, "A valid \"#{model_name}\"-class needs to respond to \"#{ methods.flatten.join(', ') }\"." unless methods.flatten.all? { |m| klass.new.respond_to? m } end def build_class_constant(name) "#{library_name}::#{model_name.pluralize}::#{name.to_s.camelcase}".constantize rescue raise exception_for_model, "Class \"#{library_name}::#{model_name.pluralize}::#{name.to_s.camelcase}\" cannot be found in file \"#{require_path(name)}\"." end def check_method fail FeduxOrgStdlib::Models::Exceptions::MethodNeedsToBeImplemented, "Method \"check_method\" does not exist." end def suffix '.rb' end def load_from_filesystem files = find_files FeduxOrgStdlib.logger.debug(self) { "Files found at path \"#{path_to_instances}\": #{ files.join(', ') }" } fail FeduxOrgStdlib::Models::Exceptions::NoImplementationsForModelFound, "You might need to store files at \"#{File.dirname(path_to_instances)}\" to make the library work." if files.blank? files.each do |f| instance_name = name(f) require require_path(instance_name) instance_klass = build_class_constant(instance_name) check_klass(instance_klass, check_method) create(instance_name, instance_klass.new) end end end end end end