Module: Takagi::Helpers
- Defined in:
- lib/takagi/helpers.rb
Overview
Helper methods for route handlers to improve DX
Dynamically generates response helper methods from CoAP::Registries::Response registry:
-
Success methods (2.xx): created(data = {}), changed(data = {}), etc.
-
Error methods (4.xx, 5.xx): bad_request(message = …), not_found(message = …), etc.
Instance Method Summary collapse
-
#halt(response) ⇒ Object
Halts execution and returns the given response Useful for early returns.
-
#json(data = {}) ⇒ Takagi::Message::Outbound
Returns a JSON response with 2.05 Content status and sets Content-Format to application/json Similar to Sinatra’s json helper, automatically sets the Content-Format option.
-
#respond(payload = {}, code: CoAP::Registries::Response::CONTENT, formats: nil, force: nil, options: {}) ⇒ Object
Respond with content-format negotiation handled automatically.
-
#validate_params(*required_params) ⇒ Object
Validates that required parameters are present.
Instance Method Details
#halt(response) ⇒ Object
Halts execution and returns the given response Useful for early returns
52 53 54 |
# File 'lib/takagi/helpers.rb', line 52 def halt(response) throw :halt, response end |
#json(data = {}) ⇒ Takagi::Message::Outbound
Returns a JSON response with 2.05 Content status and sets Content-Format to application/json Similar to Sinatra’s json helper, automatically sets the Content-Format option
35 36 37 |
# File 'lib/takagi/helpers.rb', line 35 def json(data = {}) respond(data, code: CoAP::Registries::Response.value_for(:content), formats: [Takagi::Router::DEFAULT_CONTENT_FORMAT]) end |
#respond(payload = {}, code: CoAP::Registries::Response::CONTENT, formats: nil, force: nil, options: {}) ⇒ Object
Respond with content-format negotiation handled automatically.
26 27 28 29 |
# File 'lib/takagi/helpers.rb', line 26 def respond(payload = {}, code: CoAP::Registries::Response::CONTENT, formats: nil, force: nil, options: {}) formats ||= core_content_formats if respond_to?(:core_content_formats, true) ResponseBuilder.respond(request, payload, code: code, formats: formats, force: force, options: , logger: Takagi.logger) end |
#validate_params(*required_params) ⇒ Object
Validates that required parameters are present
42 43 44 45 46 47 |
# File 'lib/takagi/helpers.rb', line 42 def validate_params(*required_params) missing = required_params.select { |param| params[param].nil? } return if missing.empty? raise ArgumentError, "Missing required parameters: #{missing.join(', ')}" end |