Module: SchemaTools::Modules::Hash
- Included in:
- Hash
- Defined in:
- lib/schema_tools/modules/hash.rb
Instance Method Summary collapse
-
#from_schema(obj, opts = {}) ⇒ Hash{String=>{String=>Mixed}}
Create a Hash with the available (api)object attributes defined in the according schema properties.
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. array inline.
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# 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 inline_schema = opts.delete(:schema) if opts[:schema].present? schema = inline_schema || SchemaTools::Reader.read(class_name, opts[:path]) # 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 |