Module: SchemaTools::Modules::Hash

Included in:
Hash
Defined in:
lib/schema_tools/modules/hash.rb

Instance Method Summary collapse

Instance Method Details

#from_schema(obj, opts = {}) ⇒ Hash{String=>{String=>Mixed}}

Create a Hash with the available (api)object attributes defined in the according schema properties. This is the meat of the object-to-api-markup workflow

Example

obj = Invoice.new(:title =>'hello world', :number=>'4711')

obj_hash = SchemaTools::Hash.from_schema(obj)
 => { 'invoice' =>{'title'=>'hello world', 'number'=>'4711' } }

obj_hash = Schema.to_hash_from_schema(obj, fields: ['title'])
 => { 'invoice' =>{'title'=>'hello world' } }

obj_hash = Schema.to_hash_from_schema(obj, class_name: :document)
 => { 'document' =>{'title'=>'hello world' } }

a lowercase underscored name and it MUST have an existing schema file. Use it to override the default, which is obj.class.name. Only used for top-level object NOT nested objects properties are used. of the global one array inline.

Parameters:

  • obj (Object)

    returned as hash

  • opts (Hash{Symbol=>Mixed}) (defaults to: {})

    additional options

Returns:

  • (Hash{String=>{String=>Mixed}})

    The object as hash: { ‘invoice’ => {‘title’=>‘hello world’, ‘number’=>‘4711’ } }



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/schema_tools/modules/hash.rb', line 45

def from_schema(obj, opts={})
  # get objects class name without inheritance
  real_class_name = obj.class.name.split('::').last.underscore
  class_name = opts[:class_name] || real_class_name
  schema =  if opts[:reader].present?
              opts[:reader].read(class_name)
            elsif opts[:schema].present?
              # TODO inline schema can be problematic with nested resource types,
              # use a local reader instance until we figured it out
              opts.delete(:schema)
            else
              SchemaTools::Reader.read(class_name, opts[:path])
            end

  # iterate over the defined schema fields
  data = parse_properties(obj, schema, opts)
  if opts[:links]
    links = parse_links(obj, schema, opts)
    links && data['_links'] = links
  end
  data
end