Class: Jsoning::Protocol
- Inherits:
-
Object
- Object
- Jsoning::Protocol
- Defined in:
- lib/jsoning/foundations/protocol.rb
Overview
takes care of the class
Instance Attribute Summary collapse
-
#klass ⇒ Object
readonly
Returns the value of attribute klass.
-
#mappers ⇒ Object
readonly
Returns the value of attribute mappers.
-
#mappers_order ⇒ Object
readonly
Returns the value of attribute mappers_order.
Instance Method Summary collapse
- #add_mapper(mapper) ⇒ Object
-
#generate(object, options = {}) ⇒ Object
generate a JSON object options: - pretty: pretty print json data.
-
#initialize(klass) ⇒ Protocol
constructor
A new instance of Protocol.
- #mapper_for(name) ⇒ Object
- #parse(object) ⇒ Object
Constructor Details
#initialize(klass) ⇒ Protocol
Returns a new instance of Protocol.
7 8 9 10 11 12 13 14 |
# File 'lib/jsoning/foundations/protocol.rb', line 7 def initialize(klass) @klass = klass # mappers, only storing symbol of mapped values @mappers_order = [] @mappers = {} end |
Instance Attribute Details
#klass ⇒ Object (readonly)
Returns the value of attribute klass.
3 4 5 |
# File 'lib/jsoning/foundations/protocol.rb', line 3 def klass @klass end |
#mappers ⇒ Object (readonly)
Returns the value of attribute mappers.
4 5 6 |
# File 'lib/jsoning/foundations/protocol.rb', line 4 def mappers @mappers end |
#mappers_order ⇒ Object (readonly)
Returns the value of attribute mappers_order.
5 6 7 |
# File 'lib/jsoning/foundations/protocol.rb', line 5 def mappers_order @mappers_order end |
Instance Method Details
#add_mapper(mapper) ⇒ Object
16 17 18 19 20 |
# File 'lib/jsoning/foundations/protocol.rb', line 16 def add_mapper(mapper) raise Jsoning::Error, "Mapper must be of class Jsoning::Mapper" unless mapper.is_a?(Jsoning::Mapper) @mappers_order << canonical_name(mapper.name) @mappers[canonical_name(mapper.name)] = mapper end |
#generate(object, options = {}) ⇒ Object
generate a JSON object options:
-
pretty: pretty print json data
29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/jsoning/foundations/protocol.rb', line 29 def generate(object, = {}) pretty = [:pretty] pretty = ["pretty"] if pretty.nil? pretty = false if pretty.nil? data = parse(object) if pretty JSON.pretty_generate(data) else JSON.generate(data) end end |
#mapper_for(name) ⇒ Object
22 23 24 |
# File 'lib/jsoning/foundations/protocol.rb', line 22 def mapper_for(name) @mappers[canonical_name(name)] end |
#parse(object) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/jsoning/foundations/protocol.rb', line 43 def parse(object) # hold data here data = {} mappers_order.each do |mapper_sym| mapper = mapper_for(mapper_sym) mapper.extract(object, data) end data end |