Module: ModelFacet
- Extended by:
- ActiveSupport::Concern
- Included in:
- ApplicationRecord
- Defined in:
- lib/generators/propel_facets/templates/models/concerns/model_facet.rb
Overview
Helper for defining json facets for an ActiveRecord model
This should allow you to define json facets like seen in the following example. Facets are used by JSON renderers like our controllers to determine which format suits better for a given situation.
“‘ruby class MyModel < ApplicationRecord
json_facet :short, :name, :logo
json_facet :public, :email, extend: :short
json_facet :agency, :address_1, :address_2, extend: :public
end “‘
The names for the facets here are :short, :public and :agency, but you are free to use any name you wish. Those are names expected to be looked by our API controllers. If not facet satisfies the reader, it may choose to either throw an error or fall-back to some format of his own choice.
Instance Method Summary collapse
-
#inject_facet(options = nil) ⇒ Object
Inject our facet options to this model.
-
#serializable_hash(options = nil) ⇒ Object
Public model method to allow getting JSON facet.
Instance Method Details
#inject_facet(options = nil) ⇒ Object
Inject our facet options to this model
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 |
# File 'lib/generators/propel_facets/templates/models/concerns/model_facet.rb', line 174 def inject_facet( = nil) if &.include? :facet missing = .fetch(:missing, :error) name = [:facet] facet = self.class.find_facet(name, missing: missing) if facet.nil? else extra = self.class.(name, facet) .merge(extra).except(:facet, :missing) end else end end |
#serializable_hash(options = nil) ⇒ Object
Public model method to allow getting JSON facet
165 166 167 168 169 170 171 |
# File 'lib/generators/propel_facets/templates/models/concerns/model_facet.rb', line 165 def serializable_hash( = nil) injected = inject_facet() hash = super(injected) hash['id'] = id hash['type'] = model_name.element.pluralize.underscore.dasherize hash end |