Class: Onsi::Resource
- Inherits:
-
Object
- Object
- Onsi::Resource
- Defined in:
- lib/onsi/resource.rb
Overview
The wrapper for generating a object
Defined Under Namespace
Classes: InvalidResourceError
Instance Attribute Summary collapse
-
#includes ⇒ Array<Onsi::Includes>
readonly
The includes for the object.
-
#object ⇒ Any
readonly
The backing object.
-
#version ⇒ Symbol
readonly
The version to render.
Class Method Summary collapse
-
.as_resource(resource, version) ⇒ Onsi::Resource+
Convert an object into a Onsi::Resource.
-
.render(resource, version) ⇒ Hash
Render a resource to JSON.
Instance Method Summary collapse
-
#as_json(_opts = {}) ⇒ Hash
Creates a raw JSON object.
-
#initialize(object, version = nil, includes: nil) ⇒ Onsi::Resource
constructor
Create a new resouce.
Constructor Details
#initialize(object, version = nil, includes: nil) ⇒ Onsi::Resource
Note:
The object MUST be a single object that includes Onsi::Model
Note:
The includes MUST be an array of Onsi::Include objects.
Create a new resouce.
146 147 148 149 150 151 |
# File 'lib/onsi/resource.rb', line 146 def initialize(object, version = nil, includes: nil) @object = object @version = version || Model::DEFAULT_API_VERSION @includes = includes validate! end |
Instance Attribute Details
#includes ⇒ Array<Onsi::Includes> (readonly)
The includes for the object.
131 132 133 |
# File 'lib/onsi/resource.rb', line 131 def includes @includes end |
#object ⇒ Any (readonly)
Note:
MUST include Onsi::Model
The backing object.
119 120 121 |
# File 'lib/onsi/resource.rb', line 119 def object @object end |
#version ⇒ Symbol (readonly)
The version to render.
125 126 127 |
# File 'lib/onsi/resource.rb', line 125 def version @version end |
Class Method Details
.as_resource(resource, version) ⇒ Onsi::Resource+
Convert an object into a Onsi::Resource
70 71 72 73 74 75 76 77 78 79 |
# File 'lib/onsi/resource.rb', line 70 def as_resource(resource, version) case resource when Onsi::Resource resource when Enumerable resource.map { |res| as_resource(res, version) } else Onsi::Resource.new(resource, version) end end |
.render(resource, version) ⇒ Hash
Render a resource to JSON
90 91 92 93 94 95 96 97 98 99 100 101 102 |
# File 'lib/onsi/resource.rb', line 90 def render(resource, version) resources = as_resource(resource, version) {}.tap do |root| root[DATA_KEY] = resources.as_json included = all_included(resources) if included.any? root[INCLUDED_KEY] = included end root[META_KEY] = {}.tap do || [:count] = resources.count if resources.respond_to?(:count) end end end |
Instance Method Details
#as_json(_opts = {}) ⇒ Hash
Creates a raw JSON object.
157 158 159 160 161 162 163 164 165 166 |
# File 'lib/onsi/resource.rb', line 157 def as_json(_opts = {}) {}.tap do |root| root[TYPE_KEY] = type root[ID_KEY] = object_identifier root[ATTRIBUTES_KEY] = generate_attributes append_relationships(root) (root) append_includes(root) end end |