Sha256: e1901b5be0fbd074d90c229f4b9884ef6a11d266e0dcc47605729f1387fe8200

Contents?: true

Size: 1.42 KB

Versions: 8

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true

require 'forwardable'
require_relative 'errors'
require_relative 'json_schema/schemas'

module Meta
  class Entity
    class << self
      extend Forwardable

      attr_reader :schema_builder

      def inherited(base)
        base.instance_eval do
          @schema_builder = JsonSchema::ObjectSchemaBuilder.new
          @schema_builder.schema_name(proc { |locked_scope, stage|
            generate_schema_name(locked_scope, stage)
          })
        end
      end

      def_delegators :schema_builder, :property, :param, :expose, :use, :lock, :locked, :schema_name, :to_schema

      def method_missing(method, *args)
        if method =~ /^lock_(\w+)$/
          schema_builder.send(method, *args)
        else
          super
        end
      end

      private

      def generate_schema_name(stage, locked_scopes)
        # 匿名类不考虑自动生成名称
        return nil unless self.name

        schema_name = self.name.gsub('::', '_')
        schema_name = schema_name.delete_suffix('Entity') unless schema_name == 'Entity'

        # 先考虑 stage
        case stage
        when :param
          schema_name += 'Params'
        when :render
          schema_name += 'Entity'
        end

        # 再考虑 locked_scope
        scope_suffix = locked_scopes.join('_')
        schema_name = "#{schema_name}_#{scope_suffix}" unless scope_suffix.empty?

        schema_name
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
meta-api-0.0.9 lib//meta/entity.rb
meta-api-0.0.8 lib/meta/entity.rb
meta-api-0.0.7 lib/meta/entity.rb
meta-api-0.0.6 lib/meta/entity.rb
meta-api-0.0.5 lib/meta/entity.rb
meta-api-0.0.4 lib/meta/entity.rb
meta-api-0.0.3 lib/meta/entity.rb
meta-api-0.0.2 lib/meta/entity.rb