From 1b12435d8b794641d7ab0925c870fecc05e10ea7 Mon Sep 17 00:00:00 2001 From: Max Melentiev Date: Fri, 26 Feb 2016 16:23:07 +0600 Subject: [PATCH] Encodes nested hashes in request body as json --- lib/telegram/bot/client.rb | 11 +++++++++-- spec/telegram/bot/client_spec.rb | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/lib/telegram/bot/client.rb b/lib/telegram/bot/client.rb index 4f6443f..0e2bad6 100644 --- a/lib/telegram/bot/client.rb +++ b/lib/telegram/bot/client.rb @@ -28,6 +28,13 @@ module Telegram def typed_response! prepend TypedResponse end + + # Encodes nested hashes as json. + def prepare_body(body) + body.each do |k, val| + body[k] = val.to_json if val.is_a?(Hash) + end + end end attr_reader :client, :token, :username, :base_uri @@ -47,8 +54,8 @@ module Telegram client.debug_dev = nil end - def request(action, data = {}) - res = http_request("#{base_uri}#{action}", data) + def request(action, body = {}) + res = http_request("#{base_uri}#{action}", self.class.prepare_body(body)) status = res.status return JSON.parse(res.body) if 300 > status result = JSON.parse(res.body) rescue nil # rubocop:disable RescueModifier diff --git a/spec/telegram/bot/client_spec.rb b/spec/telegram/bot/client_spec.rb index fbad969..836261d 100644 --- a/spec/telegram/bot/client_spec.rb +++ b/spec/telegram/bot/client_spec.rb @@ -44,4 +44,23 @@ RSpec.describe Telegram::Bot::Client do end end end + + describe '.prepare_body' do + subject { described_class.prepare_body(input) } + + context 'when plain hash is given' do + let(:input) { {a: 1, b: '2', c: [1, 2]} } + it { should eq input } + end + + context 'when nested hash is given' do + let(:input) { {a: 1, b: '2', c: [1, 2], d: {a: 1}, e: {b: []}} } + + it 'encodes nested hashes to json' do + expected = input.dup + %i(d e).each { |x| expected[x] = expected[x].to_json } + should eq expected + end + end + end end