Skip to content

Commit cfb43f8

Browse files
committed
Add postStory to request_formatter
1 parent e016de7 commit cfb43f8

File tree

2 files changed

+45
-12
lines changed

2 files changed

+45
-12
lines changed

lib/telegram/bot/client/request_body_formatter.rb

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,25 @@ module RequestBodyFormatter
1313

1414
def format(body, action)
1515
body = body.dup
16-
case action.to_s
17-
when 'sendMediaGroup'
18-
extract_files_from_array!(body, :media)
19-
when 'editMessageMedia'
20-
replace_field(body, :media) do |value|
21-
files = {}
22-
extract_files_from_hash(value, files).tap { body.merge!(files) }
23-
end
24-
end
25-
body.each do |key, val|
26-
body[key] = val.to_json if val.is_a?(Hash) || val.is_a?(Array)
27-
end
16+
handlers = {
17+
'sendMediaGroup' => -> { extract_files_from_array!(body, :media) },
18+
'editMessageMedia' => -> { extract_and_merge!(body, :media) },
19+
'postStory' => -> { extract_and_merge!(body, :content) },
20+
}
21+
handlers[action.to_s]&.call
22+
23+
body.transform_values! { |v| v.is_a?(Hash) || v.is_a?(Array) ? v.to_json : v }
2824
end
2925

3026
private
3127

28+
def extract_and_merge!(body, field)
29+
replace_field(body, field) do |value|
30+
files = {}
31+
extract_files_from_hash(value, files).tap { body.merge!(files) }
32+
end
33+
end
34+
3235
# Detects field by symbol or string name and replaces it with mapped value.
3336
def replace_field(hash, field_name)
3437
field_name = [field_name.to_sym, field_name.to_s].find { |x| hash.key?(x) }

spec/telegram/bot/client/request_body_formatter_spec.rb

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,5 +90,35 @@
9090
it { should eq input }
9191
end
9292
end
93+
94+
context 'with postStory action' do
95+
let(:action) { :postStory }
96+
let(:input) { {content: {a: file, b: 123}, x: 789} }
97+
let(:file) { File.new(__FILE__) }
98+
99+
it 'extracts files to the top-level' do
100+
should eq(
101+
content: {a: 'attach://_file0', b: 123}.to_json,
102+
x: 789,
103+
'_file0' => file,
104+
)
105+
end
106+
107+
context 'and input has string keys' do
108+
let(:input) { super().stringify_keys }
109+
it 'extracts files to the top-level' do
110+
should eq(
111+
'content' => {a: 'attach://_file0', b: 123}.to_json,
112+
'x' => 789,
113+
'_file0' => file,
114+
)
115+
end
116+
end
117+
118+
context 'without content' do
119+
let(:input) { {a: 1, b: '2', c: nil} }
120+
it { should eq input }
121+
end
122+
end
93123
end
94124
end

0 commit comments

Comments
 (0)