Module: Trello::JsonUtils::ClassMethods
- Defined in:
- lib/trello/json_utils.rb
Instance Method Summary collapse
- #from_json(json) ⇒ Object
-
#from_response(data, encoding = 'UTF-8') ⇒ Object
Public - Decodes some JSON text in the receiver, and marshals it into a class specified in obj.
- #parse_json(string, encoding = 'UTF-8') ⇒ Object
Instance Method Details
#from_json(json) ⇒ Object
39 40 41 42 43 44 45 46 47 48 |
# File 'lib/trello/json_utils.rb', line 39 def from_json(json) case json when Array json.map { |element| from_json(element) } when Hash self.new(json) else json end end |
#from_response(data, encoding = 'UTF-8') ⇒ Object
Public - Decodes some JSON text in the receiver, and marshals it into a class specified in obj.
For instance:
class Stuff
attr_reader :a, :b
def initialize(values)
@a = values['a']
@b = values['b']
end
end
thing = Stuff.from_response '{"a":42,"b":"foo"}'
thing.a == 42
thing.b == "foo"
35 36 37 |
# File 'lib/trello/json_utils.rb', line 35 def from_response(data, encoding = 'UTF-8') from_json(parse_json(data, encoding)) end |
#parse_json(string, encoding = 'UTF-8') ⇒ Object
50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/trello/json_utils.rb', line 50 def parse_json(string, encoding = 'UTF-8') JSON.parse(string.force_encoding(encoding)) rescue JSON::ParserError => json_error if json_error. =~ /model not found/ Trello.logger.error "Could not find that record." raise Trello::Error, "Request could not be found." elsif json_error. =~ /A JSON text must at least contain two octets/ else Trello.logger.error "Unknown error." raise end end |