Module: Surrealist::InstanceMethods

Defined in:
lib/surrealist/instance_methods.rb

Overview

Instance methods that are included to the object’s class

Instance Method Summary collapse

Instance Method Details

#build_schema(**args) ⇒ Object

Invokes Surrealist‘s class method build_schema



62
63
64
65
66
67
68
69
70
# File 'lib/surrealist/instance_methods.rb', line 62

def build_schema(**args)
  return args[:serializer].new(self).build_schema(**args) if args[:serializer]

  if (serializer = find_serializer(args[:for]))
    return serializer.new(self).build_schema(**args)
  end

  Surrealist.build_schema(instance: self, **args)
end

#surrealize(**args) ⇒ String

Dumps the object’s methods corresponding to the schema provided in the object’s class and type-checks the values.

Examples:

Define a schema and surrealize the object

class User
  include Surrealist

  json_schema do
    {
      name: String,
      age: Integer,
    }
  end

  def name
    'Nikita'
  end

  def age
    23
  end
end

User.new.surrealize
# => "{\"name\":\"Nikita\",\"age\":23}"
# For more examples see README

Parameters:

  • [optional] (Boolean)

    camelize optional argument for converting hash to camelBack.

  • [optional] (Boolean)

    include_root optional argument for having the root key of the resulting hash as instance’s class name.

  • [optional] (Boolean)

    include_namespaces optional argument for having root key as a nested hash of instance’s namespaces. Animal::Cat.new.surrealize -> (animal: { cat: { weight: ‘3 kilos’ } })

  • [optional] (String)

    root optional argument for using a specified root key for the hash

  • [optional] (Integer)

    namespaces_nesting_level level of namespaces nesting.

Returns:

  • (String)

    a json-formatted string corresponding to the schema provided in the object’s class. Values will be taken from the return values of appropriate methods from the object.

Raises:

  • Surrealist::UnknownSchemaError if no schema was provided in the object’s class.

  • Surrealist::InvalidTypeError if type-check failed at some point.

  • Surrealist::UndefinedMethodError if a key defined in the schema does not have a corresponding method on the object.



51
52
53
54
55
56
57
58
59
# File 'lib/surrealist/instance_methods.rb', line 51

def surrealize(**args)
  return args[:serializer].new(self).surrealize(**args) if args[:serializer]

  if (serializer = find_serializer(args[:for]))
    return serializer.new(self).surrealize(**args)
  end

  Oj.dump(Surrealist.build_schema(instance: self, **args), mode: :compat)
end