Module: Donatello
- Extended by:
- Forwardable
- Defined in:
- lib/donatello.rb,
lib/donatello/railtie.rb,
lib/donatello/version.rb,
lib/donatello/serializer.rb
Overview
rubocop:disable Style/Documentation
Defined Under Namespace
Constant Summary collapse
- VERSION =
"0.1.0"- MAX_LEVELS =
TODO: make this configurable
4
Class Method Summary collapse
Instance Method Summary collapse
-
#apply_schema(object, schema_name, current_level = 0) ⇒ Object
rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity.
- #serialize(object, schema_name) ⇒ Object
Class Method Details
.config ⇒ Object
34 35 36 |
# File 'lib/donatello.rb', line 34 def config @config ||= Config.new end |
.reset! ⇒ Object
30 31 32 |
# File 'lib/donatello.rb', line 30 def reset! @config = nil end |
.setup {|config| ... } ⇒ Object
26 27 28 |
# File 'lib/donatello.rb', line 26 def setup yield config if block_given? end |
Instance Method Details
#apply_schema(object, schema_name, current_level = 0) ⇒ Object
rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/donatello/serializer.rb', line 12 def apply_schema(object, schema_name, current_level = 0) # rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity # Stack level is too deep, return return { schema_name => nil } if current_level > MAX_LEVELS || object.nil? schema = Donatello.schema[schema_name.to_s] # Handle empty schemas # ex. schema: `empty:` return nil if schema.nil? # Handle collections of objects if non_hash_enumerable?(object) result = object.map do |o| apply_schema(o, schema_name, current_level + 1)[schema_name] end return { schema_name => result } end # We can process this schema result = schema.inject({}) do |acc, item| # TODO: detect cycles # TODO: add a test for cycles # TODO: add a pretty print to show the stack when stack level too deep # TODO: add a pretty print to show the stack when there's a cycle if item.is_a?(Hash) if item["with"] acc.merge( handle_with(object, item, current_level) ) else acc.merge( handle_attribute_config(object, item, current_level) ) end elsif object.respond_to?(item) acc.merge( handle_attribute(object, item) ) else handle_exception(object, item) end end { schema_name => result } end |
#serialize(object, schema_name) ⇒ Object
6 7 8 9 10 |
# File 'lib/donatello/serializer.rb', line 6 def serialize(object, schema_name) applied = apply_schema(object, schema_name, 0) # Don't include the root applied ? Oj.dump(applied[schema_name]) : Oj.dump(nil) end |