Class: Summon::Schema::Attr
Instance Attribute Summary collapse
-
#name ⇒ Object
readonly
Returns the value of attribute name.
Instance Method Summary collapse
- #camelize(str) ⇒ Object
- #get(service, json) ⇒ Object
-
#initialize(name, options) ⇒ Attr
constructor
A new instance of Attr.
- #pascalize(str) ⇒ Object
- #transform(service, raw) ⇒ Object
Constructor Details
#initialize(name, options) ⇒ Attr
Returns a new instance of Attr.
72 73 74 75 76 77 78 79 80 81 |
# File 'lib/summon/schema.rb', line 72 def initialize(name, ) @name = name @boolean = [:boolean] @camel_name = camelize(name.to_s) @pascal_name = @camel_name.gsub(/^\w/) {|first| first.upcase} @transform = [:transform] @json_name = [:json_name].to_s if [:json_name] @json_name = "is#{@pascal_name}" if @boolean unless @json_name @single = [:single].nil? ? !(name.to_s.downcase =~ /s$/) : [:single] end |
Instance Attribute Details
#name ⇒ Object (readonly)
Returns the value of attribute name.
71 72 73 |
# File 'lib/summon/schema.rb', line 71 def name @name end |
Instance Method Details
#camelize(str) ⇒ Object
94 95 96 97 98 |
# File 'lib/summon/schema.rb', line 94 def camelize(str) str.gsub /(\w)_(\w)/ do "#{$1}#{$2.upcase}" end end |
#get(service, json) ⇒ Object
83 84 85 86 87 88 89 90 91 92 |
# File 'lib/summon/schema.rb', line 83 def get(service, json) raw = json[@json_name || @camel_name] raw = json[@pascal_name] if raw.nil? if raw.nil? @single ? nil : [] else raw = @single && raw.kind_of?(Array) ? raw.first : raw transform(service, raw) || raw end end |
#pascalize(str) ⇒ Object
100 101 102 |
# File 'lib/summon/schema.rb', line 100 def pascalize(str) str.gsub(/(_|^)(\w)/) {$2.upcase} end |
#transform(service, raw) ⇒ Object
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
# File 'lib/summon/schema.rb', line 104 def transform(service, raw) if @transform case @transform when Class ctor = proc do |s,h| @transform.new(s, h) end when Array obj = ::Summon @transform.each do |ns| obj = obj.const_get(pascalize(ns.to_s)) end ctor = proc do |s, h| obj.new(s, h) end else ctor = proc do |s,h| ::Summon.const_get(@transform).new(s,h) end end raw.kind_of?(Array) ? raw.map {|a| [service, a]}.map(&ctor) : ctor.call(service, raw) end end |