Sha256: f3f45e998a9ed461c97ca64db5e4d81877468d9a67077552125e818a79f8c18c

Contents?: true

Size: 1.25 KB

Versions: 4

Compression:

Stored size: 1.25 KB

Contents

require 'active_support/concern'
module SchemaTools
  module Modules
    # Extend a class so it can be rendered as json from a named schema
    module AsSchema
      extend ActiveSupport::Concern

      # convert this class to a schema markup.
      # @param [Hash{Symbol=>Mixed}] opts passed on to #SchemaTools::Hash.from_schema
      # @return [String] json
      def as_schema_json(opts={})
        ActiveSupport::JSON.encode(as_schema_hash(opts))
      end

      # Get the object as hash with fields detected from its schema.
      # The schema is derived from
      # * from options[:class_name]
      # * has_schema_attrs definition(if used)
      # * the underscored class name
      # @param [Hash{Symbol=>Mixed}] opts passed on to #SchemaTools::Hash.from_schema
      # @return [Hash]
      def as_schema_hash(opts={})
        # detect schema name from class method, else class name or opts is used.
        if self.class.schema_name
          opts[:class_name] ||= self.class.schema_name
        end
        SchemaTools::Hash.from_schema(self, opts)
      end

      module ClassMethods
        # Get or set the schema name used
        def schema_name(name=nil)
          @schema_name = name if name
          @schema_name
        end
      end

    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
json_schema_tools-0.2.3 lib/schema_tools/modules/as_schema.rb
json_schema_tools-0.2.2 lib/schema_tools/modules/as_schema.rb
json_schema_tools-0.2.1 lib/schema_tools/modules/as_schema.rb
json_schema_tools-0.2.0 lib/schema_tools/modules/as_schema.rb