Module: Trello::JsonUtils::ClassMethods

Defined in:
lib/trello/json_utils.rb

Instance Method Summary collapse

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(response, 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(response, encoding = 'UTF-8')
  from_json(parse_json(response, encoding))
end

#parse_json(data, encoding = 'UTF-8') ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/trello/json_utils.rb', line 50

def parse_json(data, encoding = 'UTF-8')
  # Trello.http_client.parse_json(data, encoding)
  case data
  when Trello::Response
    JSON.parse(data.body.force_encoding(encoding))
  else
    JSON.parse(data.force_encoding(encoding))
  end
rescue JSON::ParserError => json_error
  if json_error.message =~ /model not found/
    Trello.logger.error "Could not find that record."
    raise Trello::Error, "Request could not be found."
  elsif json_error.message =~ /A JSON text must at least contain two octets/
  else
    Trello.logger.error "Unknown error."
    raise
  end
end