Module: InJson::ClassMethods
- Defined in:
- lib/in_json.rb
Instance Method Summary collapse
-
#in_json(name = :default) { ... } ⇒ Object
Defines an InJson definition that can be used to convert an object to JSON format InstanceMethods#in_json.
-
#in_json_definition(name, injected_definition) ⇒ Object
TODO move precedence to doc.
-
#include_in_json(name = :default, injected_definition = nil) ⇒ Hash
Calculates associations to be load alongside based on an InJson definition.
Instance Method Details
#in_json(name = :default) { ... } ⇒ Object
Defines an InJson definition that can be used to convert an object to JSON format InstanceMethods#in_json
53 54 55 56 57 58 59 |
# File 'lib/in_json.rb', line 53 def in_json(name = :default, &block) definitions = read_inheritable_attribute(:in_json_definitions) || {} definitions[name] = Definition.new.instance_eval(&block) write_inheritable_attribute :in_json_definitions, definitions end |
#in_json_definition(name, injected_definition) ⇒ Object
TODO move precedence to doc
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/in_json.rb', line 62 def in_json_definition(name, injected_definition) definitions = read_inheritable_attribute(:in_json_definitions) # Try nested first (if I am nested) return injected_definition if injected_definition.kind_of?(Hash) # Try named second injected_definition.kind_of?(Symbol) && definitions && result = definitions[injected_definition] return result if result # Try thread third thread_definition = Thread.current[:in_json_definition] thread_definition && definitions && result = definitions[thread_definition] return result if result # *yuck* # Try given definitions fourth definitions && result = definitions[name] return result if result # Try default last return definitions && definitions[:default] end |
#include_in_json(name = :default, injected_definition = nil) ⇒ Hash
Calculates associations to be load alongside based on an InJson definition
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
# File 'lib/in_json.rb', line 88 def include_in_json(name = :default, injected_definition = nil) definition = in_json_definition(name, injected_definition) return unless definition reflexions = reflections definition.inject({}) do |result, attr_dfn| attr, definition = attr_dfn klass = reflexions[attr].klass if reflexions.has_key?(attr) && reflexions[attr] def_at = (klass.include_in_json(name, definition) || {}) if klass result[attr] = def_at if def_at result end end |