Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/trello/core_ext/string.rb

Instance Method Summary collapse

Instance Method Details

#json_into(obj, encoding = 'UTF-8') ⇒ Object

Decodes some JSON text in the receiver, and marshals it into a class specified in obj. If obj is not a class, then we marshall the data into that instance via update_fields.

For instance:

class Stuff
  attr_reader :a, :b
  def initialize(values)
    @a = values['a']
    @b = values['b']
  end
end
thing = '{"a":42,"b":"foo"}'.json_into(Stuff)
thing.a == 42
thing.b == "foo"


18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/trello/core_ext/string.rb', line 18

def json_into(obj, encoding = 'UTF-8')
  data = JSON.parse(self.force_encoding(encoding))
  data.jsoned_into(obj)
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