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. their class name and the object hash gets _links and _class_name 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’ } }



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

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

  # get schema
  schema = SchemaTools::Reader.read(class_name, opts[:path])
  # iterate over the defined schema fields
  data = parse_properties(obj, schema, opts)
  #get links if present
  links = parse_links(obj, schema, opts)

  if opts[:exclude_root]
    hsh = data
    hsh['_class_name'] = "#{class_name}"
    links && hsh['_links'] = links
  else
    hsh = { "#{class_name}" => data }
    links && hsh['links'] = links
  end
  hsh
end