Module: ServiceStack::DTO::Serializer
- Defined in:
- lib/servicestack/dto.rb
Overview
Converts values to and from their JSON representation.
Class Method Summary collapse
- .camel_case(name) ⇒ Object
- .from_json_value(type, value) ⇒ Object
- .parse_date(value) ⇒ Object
- .snake_case(name) ⇒ Object
- .to_json_value(value) ⇒ Object
Class Method Details
.camel_case(name) ⇒ Object
196 197 198 199 |
# File 'lib/servicestack/dto.rb', line 196 def camel_case(name) parts = name.to_s.split('_') ([parts.first] + parts[1..].map(&:capitalize)).join end |
.from_json_value(type, value) ⇒ Object
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
# File 'lib/servicestack/dto.rb', line 143 def from_json_value(type, value) return nil if value.nil? # Arrays declare their element Type, e.g. type: [Booking] if type.is_a?(::Array) element_type = type.first return value.map { |x| from_json_value(element_type, x) } if value.is_a?(::Array) return value end # Hashes declare their key and value Types, e.g. type: { String => Booking } if type.is_a?(::Hash) value_type = type.values.first return value.each_with_object({}) { |(k, v), to| to[k] = from_json_value(value_type, v) } if value.is_a?(::Hash) return value end return value if type.nil? return parse_date(value) if type == ::DateTime || type == ::Time || type == ::Date return value.to_s if type == ::String return value.to_i if type == ::Integer && !value.is_a?(::Integer) return value.to_f if type == ::Float && !value.is_a?(::Float) if type.is_a?(::Class) && type.include?(DTO) && value.is_a?(::Hash) return type.from_hash(value) end value end |
.parse_date(value) ⇒ Object
175 176 177 178 179 180 181 182 183 184 185 186 |
# File 'lib/servicestack/dto.rb', line 175 def parse_date(value) return value unless value.is_a?(::String) # ServiceStack also serializes dates in WCF's /Date(1670000000000)/ format if (match = value.match(%r{^/Date\((-?\d+)([+-]\d{4})?\)/$})) return ::Time.at(match[1].to_i / 1000.0).to_datetime end ::DateTime.parse(value) rescue ::ArgumentError, ::TypeError value end |
.snake_case(name) ⇒ Object
188 189 190 191 192 193 194 |
# File 'lib/servicestack/dto.rb', line 188 def snake_case(name) name.to_s .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .tr('-', '_') .downcase end |
.to_json_value(value) ⇒ Object
130 131 132 133 134 135 136 137 138 139 140 141 |
# File 'lib/servicestack/dto.rb', line 130 def to_json_value(value) case value when nil then nil when ::DateTime, ::Time then value.iso8601 when ::Date then value.iso8601 when ::Symbol then value.to_s when ::Array then value.map { |x| to_json_value(x) } when ::Hash then value.each_with_object({}) { |(k, v), to| to[k.to_s] = to_json_value(v) } else value.respond_to?(:to_hash) && value.class.include?(DTO) ? value.to_hash : value end end |