Module: Knuckles::View
Overview
An absolutely bare bones serializer. It is meant as a replacement for ‘ActiveModelSerializers`, but is entirely focused on being simple and explicit. Views are templates that satisfy the interface of:
-
root #=> symbol
-
data #=> hash
-
relations #=> hash
Any object that satisfies that interface can be rendered correctly by the ‘Renderer` stage.
Instance Method Summary collapse
-
#data(_object, _options = {}) ⇒ Hash
Serialize an object into a hash.
-
#has_many(objects, view, options = {}) ⇒ Array<Hash>
Renders all associated objects using the specified view.
-
#has_one(object, view, options = {}) ⇒ Array<Hash>
Renders an associated object using the specified view, wrapping the results in an array.
-
#relations(_object, _options = {}) ⇒ Hash
Extracts associations for an object.
-
#render(object, options = {}) ⇒ Hash
Convenience for combining the results of data and relations into a single object.
-
#root ⇒ Symbol?
Specifies the top level key that data will be stored under.
Instance Method Details
#data(_object, _options = {}) ⇒ Hash
Serialize an object into a hash. This simply returns an empty hash by default, it must be overridden by submodules.
82 83 84 |
# File 'lib/knuckles/view.rb', line 82 def data(_object, = {}) {} end |
#has_many(objects, view, options = {}) ⇒ Array<Hash>
Renders all associated objects using the specified view.
142 143 144 |
# File 'lib/knuckles/view.rb', line 142 def has_many(objects, view, = {}) objects.map { |object| view.data(object, ) } end |
#has_one(object, view, options = {}) ⇒ Array<Hash>
Renders an associated object using the specified view, wrapping the results in an array.
123 124 125 |
# File 'lib/knuckles/view.rb', line 123 def has_one(object, view, = {}) has_many([object], view, ) end |
#relations(_object, _options = {}) ⇒ Hash
Extracts associations for an object. Later these are merged with the output of ‘data`. View relations are shallow, meaning the relations of relations are not included.
106 107 108 |
# File 'lib/knuckles/view.rb', line 106 def relations(_object, = {}) {} end |
#render(object, options = {}) ⇒ Hash
Convenience for combining the results of data and relations into a single object.
59 60 61 |
# File 'lib/knuckles/view.rb', line 59 def render(object, = {}) relations(object, ).merge!(root => [data(object, )]) end |
#root ⇒ Symbol?
Specifies the top level key that data will be stored under. The value will not be stringified or pluralized during rendering, so be aware of the format.
43 44 |
# File 'lib/knuckles/view.rb', line 43 def root end |