Sha256: 6e95ee58255f576a50312625b485e6c7912dc3fb14acb4e7ba443efa5a8241e7

Contents?: true

Size: 1.64 KB

Versions: 4

Compression:

Stored size: 1.64 KB

Contents

module Ooz
  module Base
    class ModelFactory < Common::BaseFactory
      class << self
        def def_white_classes (*str_classes)
          str_classes = str_classes.map do |cls|
            case cls
            when cls.respond_to?(:name)
              cls.name
            when Symbol
              cls.to_s
            when String
              cls
            end
          end.compact
          overridable_const :white_classes, str_classes
        end

        def def_parent_class (parent_class)
          msg = "Expected a valid parent class for you factory, from which the other classes inherit. Given #{parent_class}"
          valid_class = parent_class && parent_class.is_a?(Class)
          raise msg unless valid_class

          overridable_const :parent_class, parent_class
          overridable_const :base_namespace, parent_class.name
        end

        def new(*args)
          raise "You must use 'def_parent_class' to initialize your Factory class" if !defined?(parent_class)

          type = args.first&.dig("_type")&.split("::")&.last
          raise "Your object should have field '_type' defined" if !type

          if white_classes.include?(type)
            str_class = "#{base_namespace}::#{type}"
            raise "This class does not exist: #{str_class}" if !Object.const_defined?(str_class)
            klass = Object.const_get(str_class)
          else
            str_class = "#{base_namespace}::Undefined"
            klass = Object.const_defined?(str_class)? Object.const_get(str_class) : parent_class
          end

          klass.new(*args)
        end

      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
ooze-parser-0.1.10 lib/ooz/base/model_factory.rb
ooze-parser-0.1.9 lib/ooz/base/model_factory.rb
ooze-parser-0.1.8 lib/ooz/base/model_factory.rb
ooze-parser-0.1.7 lib/ooz/base/model_factory.rb