respondo 2.1.2 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,352 +1,450 @@
1
- # frozen_string_literal: true
2
-
3
- require "rails/generators"
4
-
5
- module Respondo
6
- module Generators
7
- class InstallGenerator < Rails::Generators::Base
8
- desc "Interactive setup — creates config/initializers/respondo.rb with your preferences."
9
-
10
- # We bypass Thor's `say` entirely for all display output and use
11
- # $stdout.puts / print directly. This prevents Thor from re-echoing
12
- # buffered output and causing duplicate lines in the terminal.
13
-
14
- def run_interactive_setup
15
- # out LOGO
16
- out logo_with_version
17
- out divider
18
- out line(" This wizard will generate config/initializers/respondo.rb")
19
- out line(" tailored to your project — no need to read the full README.")
20
- out blank
21
- out line(yellow(" All settings can be changed later by editing the initializer."))
22
- out divider
23
- out blank
24
-
25
- unless confirm(" Ready to configure Respondo? (y/n) ")
26
- out blank
27
- out line(yellow(" Skipped. Run this again any time:"))
28
- out line(" rails generate respondo:install")
29
- out blank
30
- return
31
- end
32
-
33
- @cfg = {}
34
-
35
- step_project_info
36
- step_messages
37
- step_request_id
38
- step_camelize
39
- step_default_meta
40
- step_serializer
41
-
42
- print_summary
43
- write_initializer
44
- print_done
45
- end
46
-
47
- private
48
-
49
- # =========================================================================
50
- # Steps
51
- # =========================================================================
52
-
53
- def step_project_info
54
- out section("Project Info")
55
- out line(" Project / app name")
56
- out line(yellow(" (Used as a comment header in the initializer)"))
57
- @cfg[:project_name] = prompt_default(Rails.application.class.module_parent_name)
58
-
59
- out blank
60
- out line(" API version")
61
- out line(yellow(" (e.g. v1 — added to every response meta block)"))
62
- @cfg[:api_version] = prompt_default("v1")
63
- end
64
-
65
- def step_messages
66
- out section("Response Messages")
67
- out line(" Fallback messages used when you don't pass message: explicitly.")
68
- out blank
69
-
70
- out line(" Default success message")
71
- @cfg[:default_success_message] = prompt_default("Success")
72
-
73
- out blank
74
- out line(" Default error message")
75
- @cfg[:default_error_message] = prompt_default("An error occurred")
76
- end
77
-
78
- def step_request_id
79
- out section("Request ID")
80
- out line(" When enabled, Rails request.request_id is included in every")
81
- out line(" response meta block — useful for log correlation and debugging.")
82
- out blank
83
- @cfg[:include_request_id] = confirm(" Include request_id in every response? (y/n) ")
84
- end
85
-
86
- def step_camelize
87
- out section("Key Format")
88
- out line(" When enabled, all JSON keys are camelCased:")
89
- out line(yellow(' { "createdAt": "...", "userId": 1 }'))
90
- out line(" Recommended for Flutter, React, and JavaScript clients.")
91
- out blank
92
- @cfg[:camelize_keys] = confirm(" Camelize all response keys? (y/n) ")
93
- end
94
-
95
- def step_default_meta
96
- out section("Global Meta Fields")
97
- out line(" Static key=value pairs merged into the meta block of EVERY response.")
98
- out line(" Example: platform=mobile environment=production")
99
- out blank
100
- out line(yellow(" Note: api_version from above is already included automatically."))
101
- out blank
102
-
103
- @cfg[:default_meta] = {}
104
- return unless confirm(" Add extra global meta fields? (y/n) ")
105
-
106
- out blank
107
- out line(" Enter key=value one at a time. Blank line to finish.")
108
- out blank
109
-
110
- loop do
111
- $stdout.print cyan(" key=value › ")
112
- raw = $stdin.gets.to_s.strip
113
- break if raw.empty?
114
-
115
- unless raw.include?("=")
116
- out line(yellow(" Use key=value format (e.g. platform=mobile). Skipping."))
117
- next
118
- end
119
-
120
- key, value = raw.split("=", 2)
121
-
122
- next out line(yellow(" Use key=value format.")) if key.nil? || key.strip.empty?
123
-
124
- k = key.strip
125
- v = (value || "").strip
126
- @cfg[:default_meta][k] = v
127
- out line(green(" ✓ #{k}: #{v.inspect}"))
128
- end
129
- end
130
-
131
- def step_serializer
132
- out section("Custom Serializer")
133
- out line(" By default Respondo serializes ActiveRecord models, collections,")
134
- out line(" hashes, and arrays automatically.")
135
- out blank
136
- out line(" You can override with any callable: ->(obj) { MySerializer.new(obj).as_json }")
137
- out blank
138
- @cfg[:custom_serializer] = confirm(" Add a custom serializer stub? (y/n) ")
139
- end
140
-
141
- # =========================================================================
142
- # Summary
143
- # =========================================================================
144
-
145
- def print_summary
146
- out blank
147
- out divider
148
- out line(cyan(" Configuration Summary"))
149
- out divider
150
- out blank
151
- summary_row "Project", @cfg[:project_name]
152
- summary_row "API version", @cfg[:api_version]
153
- summary_row "Success message", @cfg[:default_success_message]
154
- summary_row "Error message", @cfg[:default_error_message]
155
- summary_row "Include request_id", @cfg[:include_request_id]
156
- summary_row "Camelize keys", @cfg[:camelize_keys]
157
- summary_row "Custom serializer", @cfg[:custom_serializer]
158
-
159
- unless @cfg[:default_meta].empty?
160
- out blank
161
- out line(" Global meta:")
162
- @cfg[:default_meta].each { |k, v| out line(" #{k}: #{v.inspect}") }
163
- end
164
-
165
- out blank
166
- out divider
167
- out blank
168
- end
169
-
170
- def summary_row(label, value)
171
- bool_true = value == true
172
- val_str = bool_true ? green(value.inspect) : yellow(value.inspect)
173
- out " #{("#{label}:").ljust(24)}#{val_str}\n"
174
- end
175
-
176
- # =========================================================================
177
- # Write file
178
- # =========================================================================
179
-
180
- def write_initializer
181
- dir = File.join(destination_root, "config", "initializers")
182
- path = File.join(dir, "respondo.rb")
183
- FileUtils.mkdir_p(dir)
184
- File.write(path, build_content)
185
- out line(green(" ✅ Created config/initializers/respondo.rb"))
186
- out blank
187
- end
188
-
189
- def build_content
190
- # meta = { "api_version" => @cfg[:api_version] }.merge(@cfg[:default_meta])
191
- meta = @cfg[:default_meta].dup
192
- meta["api_version"] = @cfg[:api_version] unless @cfg[:api_version].to_s.empty?
193
- b = Lines.new
194
-
195
- b << "# frozen_string_literal: true"
196
- b << ""
197
- b << "# Respondo initializer — #{@cfg[:project_name]}"
198
- b << "# Generated by: rails generate respondo:install"
199
- b << "# Respondo version: #{Respondo::VERSION}"
200
- b << "# Docs: https://github.com/your-org/respondo"
201
- b << ""
202
- b << "Respondo.configure do |config|"
203
- b << ""
204
- b << " # ── Messages ─────────────────────────────────────────────────────────"
205
- b << " # Fallback when render_success / render_error is called without message:"
206
- b << " config.default_success_message = #{@cfg[:default_success_message].inspect}"
207
- b << " config.default_error_message = #{@cfg[:default_error_message].inspect}"
208
- b << ""
209
- b << " # ── Request ID ───────────────────────────────────────────────────────"
210
- b << " # Includes Rails request.request_id in every response meta block."
211
- b << " config.include_request_id = #{@cfg[:include_request_id]}"
212
- b << ""
213
- b << " # ── Key Format ───────────────────────────────────────────────────────"
214
- b << " # CamelCase all JSON keys — recommended for Flutter / JS clients."
215
- b << " config.camelize_keys = #{@cfg[:camelize_keys]}"
216
- b << ""
217
- b << " # ── Global Meta ──────────────────────────────────────────────────────"
218
- b << " # Static fields merged into the meta block of every response."
219
-
220
- if meta.empty?
221
- b << " config.default_meta = {}"
222
- else
223
- b << " config.default_meta = {"
224
- meta.each_with_index do |(k, v), i|
225
- comma = i < meta.size - 1 ? "," : ""
226
- b << " #{k}: #{v.inspect}#{comma}"
227
- end
228
- b << " }"
229
- end
230
-
231
- if @cfg[:custom_serializer]
232
- b << ""
233
- b << " # ── Custom Serializer ────────────────────────────────────────────────"
234
- b << " # Replace the lambda body with your own serialization logic."
235
- b << " # Examples:"
236
- b << " # ActiveModelSerializers: ->(obj) { SomeSerializer.new(obj).as_json }"
237
- b << " # Blueprinter: ->(obj) { UserBlueprint.render_as_hash(obj) }"
238
- b << " #"
239
- b << " # config.serializer = ->(obj) { MySerializer.new(obj).as_json }"
240
- end
241
-
242
- b << ""
243
- b << "end"
244
- b << ""
245
- b.to_s
246
- end
247
-
248
- # =========================================================================
249
- # Done
250
- # =========================================================================
251
-
252
- def print_done
253
- out divider
254
- out blank
255
- out line(cyan(" 🎉 Respondo is ready!"))
256
- out blank
257
- out line(" Next steps:")
258
- out line(" 1. Review config/initializers/respondo.rb")
259
- out line(" 2. Use render_success / render_error in your controllers")
260
- out line(" 3. Re-run rails generate respondo:install to regenerate")
261
- out blank
262
- out divider
263
- out blank
264
- end
265
-
266
- # =========================================================================
267
- # Output primitives — all output goes through $stdout, never through Thor
268
- # =========================================================================
269
-
270
- def out(str)
271
- $stdout.print str
272
- $stdout.flush
273
- end
274
-
275
- def line(str) = "#{str}\n"
276
- def blank = "\n"
277
-
278
- def divider
279
- " #{cyan("─" * 68)}\n"
280
- end
281
-
282
- def section(title)
283
- dashes = "─" * [0, 54 - title.length].max
284
- "\n #{cyan("┌─ #{title} #{dashes}┐")}\n\n"
285
- end
286
-
287
- def prompt_default(default)
288
- $stdout.print " #{cyan("›")} #{yellow("[#{default}]")}: "
289
- $stdout.flush
290
- result = $stdin.gets.to_s.strip
291
- result.empty? ? default.to_s : result
292
- end
293
-
294
- def confirm(question)
295
- $stdout.print question
296
- $stdout.flush
297
- $stdin.gets.to_s.strip.downcase.start_with?("y")
298
- end
299
-
300
- # =========================================================================
301
- # ANSI colors
302
- # =========================================================================
303
-
304
- def cyan(t) = "\e[36m#{t}\e[0m"
305
- def green(t) = "\e[32m#{t}\e[0m"
306
- def yellow(t) = "\e[33m#{t}\e[0m"
307
-
308
- # =========================================================================
309
- # ASCII logo
310
- # =========================================================================
311
-
312
- LOGOS = <<~'LOGO'
313
-
314
- ██████╗ ███████╗███████╗██████╗ ██████╗ ███╗ ██╗██████╗ ██████╗
315
- ██╔══██╗██╔════╝██╔════╝██╔══██╗██╔═══██╗████╗ ██║██╔══██╗██╔═══██╗
316
- ██████╔╝█████╗ ███████╗██████╔╝██║ ██║██╔██╗ ██║██║ ██║██║ ██║
317
- ██╔══██╗██╔══╝ ╚════██║██╔═══╝ ██║ ██║██║╚██╗██║██║ ██║██║ ██║
318
- ██║ ██║███████╗███████║██║ ╚██████╔╝██║ ╚████║██████╔╝╚██████╔╝
319
- ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═════╝ ╚═════╝
320
-
321
- Smart JSON API Response Formatter for Rails
322
- ─── v#{Respondo::VERSION} ───
323
-
324
- LOGO
325
-
326
- def logo_with_version
327
- green(<<~LOGO)
328
-
329
- ██████╗ ███████╗███████╗██████╗ ██████╗ ███╗ ██╗██████╗ ██████╗
330
- ██╔══██╗██╔════╝██╔════╝██╔══██╗██╔═══██╗████╗ ██║██╔══██╗██╔═══██╗
331
- ██████╔╝█████╗ ███████╗██████╔╝██║ ██║██╔██╗ ██║██║ ██║██║ ██║
332
- ██╔══██╗██╔══╝ ╚════██║██╔═══╝ ██║ ██║██║╚██╗██║██║ ██║██║ ██║
333
- ██║ ██║███████╗███████║██║ ╚██████╔╝██║ ╚████║██████╔╝╚██████╔╝
334
- ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═════╝ ╚═════╝
335
-
336
- Smart JSON API Response Formatter for Rails
337
- ─── v#{Respondo::VERSION} ───
338
-
339
- LOGO
340
- end
341
- # =========================================================================
342
- # Simple line buffer for building file content
343
- # =========================================================================
344
-
345
- class Lines
346
- def initialize = (@buf = [])
347
- def <<(str) = @buf << str
348
- def to_s = @buf.join("\n") + "\n"
349
- end
350
- end
351
- end
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+
5
+ module Respondo
6
+ module Generators
7
+ class InstallGenerator < Rails::Generators::Base
8
+ desc "Interactive setup — creates config/initializers/respondo.rb with your preferences."
9
+
10
+ # We bypass Thor's `say` entirely for all display output and use
11
+ # $stdout.puts / print directly. This prevents Thor from re-echoing
12
+ # buffered output and causing duplicate lines in the terminal.
13
+
14
+ def run_interactive_setup
15
+ # out LOGO
16
+ out logo_with_version
17
+ out divider
18
+ out line(" This wizard will generate config/initializers/respondo.rb")
19
+ out line(" tailored to your project — no need to read the full README.")
20
+ out blank
21
+ out line(yellow(" All settings can be changed later by editing the initializer."))
22
+ out divider
23
+ out blank
24
+
25
+ unless confirm(" Ready to configure Respondo? (y/n) ")
26
+ out blank
27
+ out line(yellow(" Skipped. Run this again any time:"))
28
+ out line(" rails generate respondo:install")
29
+ out blank
30
+ return
31
+ end
32
+
33
+ @cfg = {}
34
+
35
+ step_project_info
36
+ step_messages
37
+ step_request_id
38
+ step_camelize
39
+ step_default_meta
40
+ step_serializer
41
+ step_security
42
+
43
+ print_summary
44
+ write_initializer
45
+ print_done
46
+ end
47
+
48
+ private
49
+
50
+ # =========================================================================
51
+ # Steps
52
+ # =========================================================================
53
+
54
+ def step_project_info
55
+ out section("Project Info")
56
+ out line(" Project / app name")
57
+ out line(yellow(" (Used as a comment header in the initializer)"))
58
+ @cfg[:project_name] = prompt_default(Rails.application.class.module_parent_name)
59
+
60
+ out blank
61
+ out line(" API version")
62
+ out line(yellow(" (e.g. v1 — added to every response meta block)"))
63
+ @cfg[:api_version] = prompt_default("v1")
64
+ end
65
+
66
+ def step_messages
67
+ out section("Response Messages")
68
+ out line(" Fallback messages used when you don't pass message: explicitly.")
69
+ out blank
70
+
71
+ out line(" Default success message")
72
+ @cfg[:default_success_message] = prompt_default("Success")
73
+
74
+ out blank
75
+ out line(" Default error message")
76
+ @cfg[:default_error_message] = prompt_default("An error occurred")
77
+ end
78
+
79
+ def step_request_id
80
+ out section("Request ID")
81
+ out line(" When enabled, Rails request.request_id is included in every")
82
+ out line(" response meta block — useful for log correlation and debugging.")
83
+ out blank
84
+ @cfg[:include_request_id] = confirm(" Include request_id in every response? (y/n) ")
85
+ end
86
+
87
+ def step_camelize
88
+ out section("Key Format")
89
+ out line(" When enabled, all JSON keys are camelCased:")
90
+ out line(yellow(' { "createdAt": "...", "userId": 1 }'))
91
+ out line(" Recommended for Flutter, React, and JavaScript clients.")
92
+ out blank
93
+ @cfg[:camelize_keys] = confirm(" Camelize all response keys? (y/n) ")
94
+ end
95
+
96
+ def step_default_meta
97
+ out section("Global Meta Fields")
98
+ out line(" Static key=value pairs merged into the meta block of EVERY response.")
99
+ out line(" Example: platform=mobile environment=production")
100
+ out blank
101
+ out line(yellow(" Note: api_version from above is already included automatically."))
102
+ out blank
103
+
104
+ @cfg[:default_meta] = {}
105
+ return unless confirm(" Add extra global meta fields? (y/n) ")
106
+
107
+ out blank
108
+ out line(" Enter key=value one at a time. Blank line to finish.")
109
+ out blank
110
+
111
+ loop do
112
+ $stdout.print cyan(" key=value › ")
113
+ raw = $stdin.gets.to_s.strip
114
+ break if raw.empty?
115
+
116
+ unless raw.include?("=")
117
+ out line(yellow(" Use key=value format (e.g. platform=mobile). Skipping."))
118
+ next
119
+ end
120
+
121
+ key, value = raw.split("=", 2)
122
+
123
+ next out line(yellow(" Use key=value format.")) if key.nil? || key.strip.empty?
124
+
125
+ k = key.strip
126
+ v = (value || "").strip
127
+
128
+ unless k.match?(META_KEY_PATTERN)
129
+ out line(yellow(" Key must be a plain identifier (letters, digits, underscores; not starting with a digit). Skipping."))
130
+ next
131
+ end
132
+
133
+ @cfg[:default_meta][k] = v
134
+ out line(green(" ✓ #{k}: #{v.inspect}"))
135
+ end
136
+ end
137
+
138
+ def step_serializer
139
+ out section("Custom Serializer")
140
+ out line(" By default Respondo serializes ActiveRecord models, collections,")
141
+ out line(" hashes, and arrays automatically.")
142
+ out blank
143
+ out line(" You can override with any callable: ->(obj) { MySerializer.new(obj).as_json }")
144
+ out blank
145
+ @cfg[:custom_serializer] = confirm(" Add a custom serializer stub? (y/n) ")
146
+ end
147
+
148
+ def step_security
149
+ out section("Security")
150
+ out line(" A raw ActiveRecord model is serialized with EVERY column, including")
151
+ out line(" password_digest and API tokens. Strict mode raises an error instead of")
152
+ out line(" leaking them, so you must pass an explicit shape:")
153
+ out line(yellow(" render_ok(data: user.as_json(only: %i[id name email]))"))
154
+ out line(" (or configure config.serializer).")
155
+ out blank
156
+ @cfg[:strict_serialization] = confirm_default_yes(" Enable strict_serialization? (recommended) (Y/n) ")
157
+
158
+ out blank
159
+ out line(" Maximum items allowed in one collection (protects against huge responses).")
160
+ out line(yellow(" Enter a number such as 1000, or leave blank for no limit."))
161
+ raw = prompt_default("no limit")
162
+ @cfg[:max_collection_size] = parse_collection_limit(raw)
163
+ end
164
+
165
+ # =========================================================================
166
+ # Summary
167
+ # =========================================================================
168
+
169
+ def print_summary
170
+ out blank
171
+ out divider
172
+ out line(cyan(" Configuration Summary"))
173
+ out divider
174
+ out blank
175
+ summary_row "Project", @cfg[:project_name]
176
+ summary_row "API version", @cfg[:api_version]
177
+ summary_row "Success message", @cfg[:default_success_message]
178
+ summary_row "Error message", @cfg[:default_error_message]
179
+ summary_row "Include request_id", @cfg[:include_request_id]
180
+ summary_row "Camelize keys", @cfg[:camelize_keys]
181
+ summary_row "Custom serializer", @cfg[:custom_serializer]
182
+ summary_row "Strict serialization", @cfg[:strict_serialization]
183
+ summary_row "Max collection size", @cfg[:max_collection_size] || "no limit"
184
+
185
+ unless @cfg[:default_meta].empty?
186
+ out blank
187
+ out line(" Global meta:")
188
+ @cfg[:default_meta].each { |k, v| out line(" #{k}: #{v.inspect}") }
189
+ end
190
+
191
+ out blank
192
+ out divider
193
+ out blank
194
+ end
195
+
196
+ def summary_row(label, value)
197
+ bool_true = value == true
198
+ val_str = bool_true ? green(value.inspect) : yellow(value.inspect)
199
+ out " #{("#{label}:").ljust(24)}#{val_str}\n"
200
+ end
201
+
202
+ # =========================================================================
203
+ # Write file
204
+ # =========================================================================
205
+
206
+ def write_initializer
207
+ dir = File.join(destination_root, "config", "initializers")
208
+ path = File.join(dir, "respondo.rb")
209
+ FileUtils.mkdir_p(dir)
210
+
211
+ if File.exist?(path)
212
+ FileUtils.cp(path, "#{path}.bak")
213
+ out line(yellow(" ℹ️ Existing initializer backed up to config/initializers/respondo.rb.bak"))
214
+ end
215
+
216
+ File.write(path, build_content)
217
+ out line(green(" ✅ Created config/initializers/respondo.rb"))
218
+ out blank
219
+ end
220
+
221
+ # Valid Ruby identifier-style keys only. Anything else is never written
222
+ # raw into the generated Ruby file.
223
+ META_KEY_PATTERN = /\A[a-z_][a-z0-9_]*\z/i.freeze
224
+
225
+ # Returns the key as safe Ruby source, including the separator, e.g.
226
+ # `platform: ` for plain identifiers or `:"odd key" => ` as a fallback.
227
+ # String#inspect / Symbol#inspect escape quotes and newlines, so the key
228
+ # can never terminate the hash literal or inject statements.
229
+ def meta_key_literal(key)
230
+ key = key.to_s
231
+ key.match?(META_KEY_PATTERN) ? "#{key}: " : "#{key.to_sym.inspect} => "
232
+ end
233
+
234
+ def build_content
235
+ # meta = { "api_version" => @cfg[:api_version] }.merge(@cfg[:default_meta])
236
+ meta = @cfg[:default_meta].dup
237
+ meta["api_version"] = @cfg[:api_version] unless @cfg[:api_version].to_s.empty?
238
+ b = Lines.new
239
+
240
+ b << "# frozen_string_literal: true"
241
+ b << ""
242
+ b << "# Respondo initializer — #{@cfg[:project_name].to_s.gsub(/[\r\n]+/, " ")}"
243
+ b << "# Generated by: rails generate respondo:install"
244
+ b << "# Respondo version: #{Respondo::VERSION}"
245
+ b << "# Docs: https://github.com/spatelpatidar/respondo"
246
+ b << ""
247
+ b << "Respondo.configure do |config|"
248
+ b << ""
249
+ b << " # ── Messages ─────────────────────────────────────────────────────────"
250
+ b << " # Fallback when render_success / render_error is called without message:"
251
+ b << " config.default_success_message = #{@cfg[:default_success_message].inspect}"
252
+ b << " config.default_error_message = #{@cfg[:default_error_message].inspect}"
253
+ b << ""
254
+ b << " # ── Request ID ───────────────────────────────────────────────────────"
255
+ b << " # Includes Rails request.request_id in every response meta block."
256
+ b << " config.include_request_id = #{@cfg[:include_request_id]}"
257
+ b << ""
258
+ b << " # ── Key Format ───────────────────────────────────────────────────────"
259
+ b << " # CamelCase all JSON keys — recommended for Flutter / JS clients."
260
+ b << " config.camelize_keys = #{@cfg[:camelize_keys]}"
261
+ b << ""
262
+ b << " # ── Security ─────────────────────────────────────────────────────────"
263
+ b << " # Raise Respondo::UnsafeSerializationError when a raw ActiveRecord model or"
264
+ b << " # relation is passed as data: without a serializer (it would expose every"
265
+ b << " # column, e.g. password_digest or API tokens). Recommended: true."
266
+ b << " config.strict_serialization = #{@cfg[:strict_serialization] == true}"
267
+ b << ""
268
+ b << " # Raise Respondo::CollectionTooLargeError when a collection has more items"
269
+ b << " # than this (nil = no limit). Paginate large lists instead."
270
+ b << " config.max_collection_size = #{@cfg[:max_collection_size].inspect}"
271
+ b << ""
272
+ b << " # ── Global Meta ──────────────────────────────────────────────────────"
273
+ b << " # Static fields merged into the meta block of every response."
274
+
275
+ if meta.empty?
276
+ b << " config.default_meta = {}"
277
+ else
278
+ b << " config.default_meta = {"
279
+ meta.each_with_index do |(k, v), i|
280
+ comma = i < meta.size - 1 ? "," : ""
281
+ b << " #{meta_key_literal(k)}#{v.inspect}#{comma}"
282
+ end
283
+ b << " }"
284
+ end
285
+
286
+ if @cfg[:custom_serializer]
287
+ b << ""
288
+ b << " # ── Custom Serializer ────────────────────────────────────────────────"
289
+ b << " # Replace the lambda body with your own serialization logic."
290
+ b << " # Examples:"
291
+ b << " # ActiveModelSerializers: ->(obj) { SomeSerializer.new(obj).as_json }"
292
+ b << " # Blueprinter: ->(obj) { UserBlueprint.render_as_hash(obj) }"
293
+ b << " #"
294
+ b << " # config.serializer = ->(obj) { MySerializer.new(obj).as_json }"
295
+ end
296
+
297
+ b << ""
298
+ b << "end"
299
+ b << ""
300
+ b.to_s
301
+ end
302
+
303
+ # =========================================================================
304
+ # Done
305
+ # =========================================================================
306
+
307
+ def print_done
308
+ out divider
309
+ out blank
310
+ out line(cyan(" 🎉 Respondo is ready!"))
311
+ out blank
312
+ out line(" Next steps:")
313
+ out line(" 1. Review config/initializers/respondo.rb")
314
+ out line(" 2. Use render_success / render_error in your controllers")
315
+ out line(" 3. Handle Respondo::UnsafeSerializationError and")
316
+ out line(" Respondo::CollectionTooLargeError with rescue_from")
317
+ out line(" 4. Re-run rails generate respondo:install to regenerate")
318
+ out blank
319
+ out divider
320
+ out blank
321
+ end
322
+
323
+ # =========================================================================
324
+ # Output primitives — all output goes through $stdout, never through Thor
325
+ # =========================================================================
326
+
327
+ def out(str)
328
+ $stdout.print str
329
+ $stdout.flush
330
+ end
331
+
332
+ def line(str)
333
+ "#{str}\n"
334
+ end
335
+ def blank
336
+ "\n"
337
+ end
338
+
339
+ def divider
340
+ " #{cyan("─" * 68)}\n"
341
+ end
342
+
343
+ def section(title)
344
+ dashes = "─" * [0, 54 - title.length].max
345
+ "\n #{cyan("┌─ #{title} #{dashes}┐")}\n\n"
346
+ end
347
+
348
+ def prompt_default(default)
349
+ $stdout.print " #{cyan("›")} #{yellow("[#{default}]")}: "
350
+ $stdout.flush
351
+ result = $stdin.gets.to_s.strip
352
+ result.empty? ? default.to_s : result
353
+ end
354
+
355
+ # Like confirm, but pressing Enter means yes (used for the secure default).
356
+ def confirm_default_yes(question)
357
+ $stdout.print question
358
+ $stdout.flush
359
+ answer = $stdin.gets.to_s.strip.downcase
360
+ answer.empty? || answer.start_with?("y")
361
+ end
362
+
363
+ # "1000" / "1_000" / "1,000" -> 1000. Blank, "no limit", zero, negative or
364
+ # non-numeric input -> nil (no limit), with a hint when the input was invalid.
365
+ def parse_collection_limit(raw)
366
+ text = raw.to_s.strip.downcase
367
+ return nil if text.empty? || text == "no limit"
368
+
369
+ digits = text.delete("_,")
370
+ if digits.match?(/\A\d+\z/) && digits.to_i.positive?
371
+ digits.to_i
372
+ else
373
+ out line(yellow(" Not a positive whole number — using no limit."))
374
+ nil
375
+ end
376
+ end
377
+
378
+ def confirm(question)
379
+ $stdout.print question
380
+ $stdout.flush
381
+ $stdin.gets.to_s.strip.downcase.start_with?("y")
382
+ end
383
+
384
+ # =========================================================================
385
+ # ANSI colors
386
+ # =========================================================================
387
+
388
+ def cyan(t)
389
+ "\e[36m#{t}\e[0m"
390
+ end
391
+ def green(t)
392
+ "\e[32m#{t}\e[0m"
393
+ end
394
+ def yellow(t)
395
+ "\e[33m#{t}\e[0m"
396
+ end
397
+
398
+ # =========================================================================
399
+ # ASCII logo
400
+ # =========================================================================
401
+
402
+ LOGOS = <<~'LOGO'
403
+
404
+ ██████╗ ███████╗███████╗██████╗ ██████╗ ███╗ ██╗██████╗ ██████╗
405
+ ██╔══██╗██╔════╝██╔════╝██╔══██╗██╔═══██╗████╗ ██║██╔══██╗██╔═══██╗
406
+ ██████╔╝█████╗ ███████╗██████╔╝██║ ██║██╔██╗ ██║██║ ██║██║ ██║
407
+ ██╔══██╗██╔══╝ ╚════██║██╔═══╝ ██║ ██║██║╚██╗██║██║ ██║██║ ██║
408
+ ██║ ██║███████╗███████║██║ ╚██████╔╝██║ ╚████║██████╔╝╚██████╔╝
409
+ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═════╝ ╚═════╝
410
+
411
+ Smart JSON API Response Formatter for Rails
412
+ ─── v#{Respondo::VERSION} ───
413
+
414
+ LOGO
415
+
416
+ def logo_with_version
417
+ green(<<~LOGO)
418
+
419
+ ██████╗ ███████╗███████╗██████╗ ██████╗ ███╗ ██╗██████╗ ██████╗
420
+ ██╔══██╗██╔════╝██╔════╝██╔══██╗██╔═══██╗████╗ ██║██╔══██╗██╔═══██╗
421
+ ██████╔╝█████╗ ███████╗██████╔╝██║ ██║██╔██╗ ██║██║ ██║██║ ██║
422
+ ██╔══██╗██╔══╝ ╚════██║██╔═══╝ ██║ ██║██║╚██╗██║██║ ██║██║ ██║
423
+ ██║ ██║███████╗███████║██║ ╚██████╔╝██║ ╚████║██████╔╝╚██████╔╝
424
+ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═════╝ ╚═════╝
425
+
426
+ Smart JSON API Response Formatter for Rails
427
+ ─── v#{Respondo::VERSION} ───
428
+
429
+ LOGO
430
+ end
431
+ # =========================================================================
432
+ # Simple line buffer for building file content
433
+ # =========================================================================
434
+
435
+ class Lines
436
+ def initialize
437
+ @buf = []
438
+ end
439
+
440
+ def <<(str)
441
+ @buf << str
442
+ end
443
+
444
+ def to_s
445
+ @buf.join("\n") + "\n"
446
+ end
447
+ end
448
+ end
449
+ end
352
450
  end