repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/types/primitive_coercer_spec.rb | spec/grape/validations/types/primitive_coercer_spec.rb | # frozen_string_literal: true
describe Grape::Validations::Types::PrimitiveCoercer do
subject { described_class.new(type, strict) }
let(:strict) { false }
describe '#call' do
context 'BigDecimal' do
let(:type) { BigDecimal }
it 'coerces to BigDecimal' do
expect(subject.call(5)).to eq(BigDecimal('5'))
end
it 'coerces an empty string to nil' do
expect(subject.call('')).to be_nil
end
end
context 'Boolean' do
let(:type) { Grape::API::Boolean }
[true, 'true', 1].each do |val|
it "coerces '#{val}' to true" do
expect(subject.call(val)).to be(true)
end
end
[false, 'false', 0].each do |val|
it "coerces '#{val}' to false" do
expect(subject.call(val)).to be(false)
end
end
it 'returns an error when the given value cannot be coerced' do
expect(subject.call(123)).to be_instance_of(Grape::Validations::Types::InvalidValue)
end
it 'coerces an empty string to nil' do
expect(subject.call('')).to be_nil
end
end
context 'DateTime' do
let(:type) { DateTime }
it 'coerces an empty string to nil' do
expect(subject.call('')).to be_nil
end
end
context 'Float' do
let(:type) { Float }
it 'coerces an empty string to nil' do
expect(subject.call('')).to be_nil
end
end
context 'Integer' do
let(:type) { Integer }
it 'coerces an empty string to nil' do
expect(subject.call('')).to be_nil
end
it 'accepts non-nil value' do
expect(subject.call(42)).to be_a(Integer)
end
end
context 'Numeric' do
let(:type) { Numeric }
it 'coerces an empty string to nil' do
expect(subject.call('')).to be_nil
end
it 'accepts a non-nil value' do
expect(subject.call(42)).to be_a(Numeric) # in fact Integer
end
end
context 'Time' do
let(:type) { Time }
it 'coerces an empty string to nil' do
expect(subject.call('')).to be_nil
end
end
context 'String' do
let(:type) { String }
it 'coerces to String' do
expect(subject.call(10)).to eq('10')
end
it 'does not coerce an empty string to nil' do
expect(subject.call('')).to eq('')
end
end
context 'Symbol' do
let(:type) { Symbol }
it 'coerces an empty string to nil' do
expect(subject.call('')).to be_nil
end
end
context 'a type unknown in Dry-types' do
let(:type) { Complex }
it 'raises error on init' do
expect(Grape::DryTypes::Params.constants).not_to include(type.name.to_sym)
expect { subject }.to raise_error(/type Complex should support coercion/)
end
end
context 'the strict mode' do
let(:strict) { true }
context 'Boolean' do
let(:type) { Grape::API::Boolean }
it 'returns an error when the given value is not Boolean' do
expect(subject.call(1)).to be_instance_of(Grape::Validations::Types::InvalidValue)
end
it 'returns a value as it is when the given value is Boolean' do
expect(subject.call(true)).to be(true)
end
end
context 'BigDecimal' do
let(:type) { BigDecimal }
it 'returns an error when the given value is not BigDecimal' do
expect(subject.call(1)).to be_instance_of(Grape::Validations::Types::InvalidValue)
end
it 'returns a value as it is when the given value is BigDecimal' do
expect(subject.call(BigDecimal('0'))).to eq(BigDecimal('0'))
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/types/set_coercer_spec.rb | spec/grape/validations/types/set_coercer_spec.rb | # frozen_string_literal: true
describe Grape::Validations::Types::SetCoercer do
subject { described_class.new(type) }
describe '#call' do
context 'a set of primitives' do
let(:type) { Set[String] }
it 'coerces elements to the set' do
expect(subject.call([10, 20])).to eq(Set['10', '20'])
end
end
context 'a set of sets' do
let(:type) { Set[Set[Integer]] }
it 'coerces elements in the nested set' do
expect(subject.call([%w[10 20]])).to eq(Set[Set[10, 20]])
expect(subject.call([['10'], ['20']])).to eq(Set[Set[10], Set[20]])
end
end
context 'a set of sets of arrays' do
let(:type) { Set[Set[Array[Integer]]] }
it 'coerces elements in the nested set' do
expect(subject.call([[['10'], ['20']]])).to eq(Set[Set[Array[10], Array[20]]])
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/types/array_coercer_spec.rb | spec/grape/validations/types/array_coercer_spec.rb | # frozen_string_literal: true
describe Grape::Validations::Types::ArrayCoercer do
subject { described_class.new(type) }
describe '#call' do
context 'an array of primitives' do
let(:type) { Array[String] }
it 'coerces elements in the array' do
expect(subject.call([10, 20])).to eq(%w[10 20])
end
end
context 'an array of arrays' do
let(:type) { Array[Array[Integer]] }
it 'coerces elements in the nested array' do
expect(subject.call([%w[10 20]])).to eq([[10, 20]])
expect(subject.call([['10'], ['20']])).to eq([[10], [20]])
end
end
context 'an array of sets' do
let(:type) { Array[Set[Integer]] }
it 'coerces elements in the nested set' do
expect(subject.call([%w[10 20]])).to eq([Set[10, 20]])
expect(subject.call([['10'], ['20']])).to eq([Set[10], Set[20]])
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/router/greedy_route_spec.rb | spec/grape/router/greedy_route_spec.rb | # frozen_string_literal: true
RSpec.describe Grape::Router::GreedyRoute do
let(:instance) { described_class.new(pattern, endpoint: endpoint, allow_header: allow_header) }
let(:pattern) { :pattern }
let(:endpoint) { instance_double(Grape::Endpoint) }
let(:allow_header) { false }
describe 'inheritance' do
subject { instance }
it { is_expected.to be_a(Grape::Router::BaseRoute) }
end
describe '#pattern' do
subject { instance.pattern }
it { is_expected.to eq(pattern) }
end
describe '#endpoint' do
subject { instance.endpoint }
it { is_expected.to eq(endpoint) }
end
describe '#allow_header' do
subject { instance.allow_header }
it { is_expected.to eq(allow_header) }
end
describe '#params' do
subject { instance.params }
it { is_expected.to be_nil }
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/endpoint/declared_spec.rb | spec/grape/endpoint/declared_spec.rb | # frozen_string_literal: true
describe Grape::Endpoint do
subject { Class.new(Grape::API) }
let(:app) { subject }
describe '#declared' do
before do
subject.format :json
subject.params do
requires :first
optional :second
optional :third, default: 'third-default'
optional :multiple_types, types: [Integer, String]
optional :nested, type: Hash do
optional :fourth
optional :fifth
optional :nested_two, type: Hash do
optional :sixth
optional :nested_three, type: Hash do
optional :seventh
end
end
optional :nested_arr, type: Array do
optional :eighth
end
optional :empty_arr, type: Array
optional :empty_typed_arr, type: Array[String]
optional :empty_hash, type: Hash
optional :empty_set, type: Set
optional :empty_typed_set, type: Set[String]
end
optional :arr, type: Array do
optional :nineth
end
optional :empty_arr, type: Array
optional :empty_typed_arr, type: Array[String]
optional :empty_hash, type: Hash
optional :empty_hash_two, type: Hash
optional :empty_set, type: Set
optional :empty_typed_set, type: Set[String]
end
end
context 'when params are not built with default class' do
it 'returns an object that corresponds with the params class - hash with indifferent access' do
subject.params do
build_with :hash_with_indifferent_access
end
subject.get '/declared' do
d = declared(params, include_missing: true)
{ declared_class: d.class.to_s }
end
get '/declared?first=present'
expect(JSON.parse(last_response.body)['declared_class']).to eq('ActiveSupport::HashWithIndifferentAccess')
end
it 'returns an object that corresponds with the params class - hash' do
subject.params do
build_with :hash
end
subject.get '/declared' do
d = declared(params, include_missing: true)
{ declared_class: d.class.to_s }
end
get '/declared?first=present'
expect(JSON.parse(last_response.body)['declared_class']).to eq('Hash')
end
end
it 'shows nil for nested params if include_missing is true' do
subject.get '/declared' do
declared(params, include_missing: true)
end
get '/declared?first=present'
expect(last_response).to be_successful
expect(JSON.parse(last_response.body)['nested']['fourth']).to be_nil
end
it 'shows nil for multiple allowed types if include_missing is true' do
subject.get '/declared' do
declared(params, include_missing: true)
end
get '/declared?first=present'
expect(last_response).to be_successful
expect(JSON.parse(last_response.body)['multiple_types']).to be_nil
end
it 'does not work in a before filter' do
subject.before do
declared(params)
end
subject.get('/declared') { declared(params) }
expect { get('/declared') }.to raise_error(
Grape::DSL::InsideRoute::MethodNotYetAvailable
)
end
it 'has as many keys as there are declared params' do
subject.get '/declared' do
declared(params)
end
get '/declared?first=present'
expect(last_response).to be_successful
expect(JSON.parse(last_response.body).keys.size).to eq(12)
end
it 'has a optional param with default value all the time' do
subject.get '/declared' do
declared(params)
end
get '/declared?first=one'
expect(last_response).to be_successful
expect(JSON.parse(last_response.body)['third']).to eql('third-default')
end
it 'builds nested params' do
subject.get '/declared' do
declared(params)
end
get '/declared?first=present&nested[fourth]=1'
expect(last_response).to be_successful
expect(JSON.parse(last_response.body)['nested'].keys.size).to eq 9
end
it 'builds arrays correctly' do
subject.params do
requires :first
optional :second, type: Array
end
subject.post('/declared') { declared(params) }
post '/declared', first: 'present', second: ['present']
expect(last_response).to be_created
body = JSON.parse(last_response.body)
expect(body['second']).to eq(['present'])
end
it 'builds nested params when given array' do
subject.get '/dummy' do
end
subject.params do
requires :first
optional :second
optional :third, default: 'third-default'
optional :nested, type: Array do
optional :fourth
end
end
subject.get '/declared' do
declared(params)
end
get '/declared?first=present&nested[][fourth]=1&nested[][fourth]=2'
expect(last_response).to be_successful
expect(JSON.parse(last_response.body)['nested'].size).to eq 2
end
context 'when the param is missing and include_missing=false' do
before do
subject.get('/declared') { declared(params, include_missing: false) }
end
it 'sets nested objects to be nil' do
get '/declared?first=present'
expect(last_response).to be_successful
expect(JSON.parse(last_response.body)['nested']).to be_nil
end
end
context 'when the param is missing and include_missing=true' do
before do
subject.get('/declared') { declared(params, include_missing: true) }
end
it 'sets objects with type=Hash to be a hash' do
get '/declared?first=present'
expect(last_response).to be_successful
body = JSON.parse(last_response.body)
expect(body['empty_hash']).to eq({})
expect(body['empty_hash_two']).to eq({})
expect(body['nested']).to be_a(Hash)
expect(body['nested']['empty_hash']).to eq({})
expect(body['nested']['nested_two']).to be_a(Hash)
end
it 'sets objects with type=Set to be a set' do
get '/declared?first=present'
expect(last_response).to be_successful
json_empty_set = JSON.parse(Set.new.to_json)
body = JSON.parse(last_response.body)
expect(body['empty_set']).to eq(json_empty_set)
expect(body['empty_typed_set']).to eq(json_empty_set)
expect(body['nested']['empty_set']).to eq(json_empty_set)
expect(body['nested']['empty_typed_set']).to eq(json_empty_set)
end
it 'sets objects with type=Array to be an array' do
get '/declared?first=present'
expect(last_response).to be_successful
body = JSON.parse(last_response.body)
expect(body['empty_arr']).to eq([])
expect(body['empty_typed_arr']).to eq([])
expect(body['arr']).to eq([])
expect(body['nested']['empty_arr']).to eq([])
expect(body['nested']['empty_typed_arr']).to eq([])
expect(body['nested']['nested_arr']).to eq([])
end
it 'includes all declared children when type=Hash' do
get '/declared?first=present'
expect(last_response).to be_successful
body = JSON.parse(last_response.body)
expect(body['nested'].keys).to eq(%w[fourth fifth nested_two nested_arr empty_arr empty_typed_arr empty_hash empty_set empty_typed_set])
expect(body['nested']['nested_two'].keys).to eq(%w[sixth nested_three])
expect(body['nested']['nested_two']['nested_three'].keys).to eq(%w[seventh])
end
end
it 'filters out any additional params that are given' do
subject.get '/declared' do
declared(params)
end
get '/declared?first=one&other=two'
expect(last_response).to be_successful
expect(JSON.parse(last_response.body).key?(:other)).to be false
end
it 'stringifies if that option is passed' do
subject.get '/declared' do
declared(params, stringify: true)
end
get '/declared?first=one&other=two'
expect(last_response).to be_successful
expect(JSON.parse(last_response.body)['first']).to eq 'one'
end
it 'does not include missing attributes if that option is passed' do
subject.get '/declared' do
error! 'expected nil', 400 if declared(params, include_missing: false).key?(:second)
''
end
get '/declared?first=one&other=two'
expect(last_response).to be_successful
end
it 'does not include renamed missing attributes if that option is passed' do
subject.params do
optional :renamed_original, as: :renamed
end
subject.get '/declared' do
error! 'expected nil', 400 if declared(params, include_missing: false).key?(:renamed)
''
end
get '/declared?first=one&other=two'
expect(last_response).to be_successful
end
it 'includes attributes with value that evaluates to false' do
subject.params do
requires :first
optional :boolean
end
subject.post '/declared' do
error!('expected false', 400) if declared(params, include_missing: false)[:boolean] != false
''
end
post '/declared', Grape::Json.dump(first: 'one', boolean: false), 'CONTENT_TYPE' => 'application/json'
expect(last_response).to be_created
end
it 'includes attributes with value that evaluates to nil' do
subject.params do
requires :first
optional :second
end
subject.post '/declared' do
error!('expected nil', 400) unless declared(params, include_missing: false)[:second].nil?
''
end
post '/declared', Grape::Json.dump(first: 'one', second: nil), 'CONTENT_TYPE' => 'application/json'
expect(last_response).to be_created
end
it 'includes missing attributes with defaults when there are nested hashes' do
subject.get '/dummy' do
end
subject.params do
requires :first
optional :second
optional :third, default: nil
optional :nested, type: Hash do
optional :fourth, default: nil
optional :fifth, default: nil
requires :nested_nested, type: Hash do
optional :sixth, default: 'sixth-default'
optional :seven, default: nil
end
end
end
subject.get '/declared' do
declared(params, include_missing: false)
end
get '/declared?first=present&nested[fourth]=&nested[nested_nested][sixth]=sixth'
json = JSON.parse(last_response.body)
expect(last_response).to be_successful
expect(json['first']).to eq 'present'
expect(json['nested'].keys).to eq %w[fourth fifth nested_nested]
expect(json['nested']['fourth']).to eq ''
expect(json['nested']['nested_nested'].keys).to eq %w[sixth seven]
expect(json['nested']['nested_nested']['sixth']).to eq 'sixth'
end
it 'does not include missing attributes when there are nested hashes' do
subject.get '/dummy' do
end
subject.params do
requires :first
optional :second
optional :third
optional :nested, type: Hash do
optional :fourth
optional :fifth
end
end
subject.get '/declared' do
declared(params, include_missing: false)
end
get '/declared?first=present&nested[fourth]=4'
json = JSON.parse(last_response.body)
expect(last_response).to be_successful
expect(json['first']).to eq 'present'
expect(json['nested'].keys).to eq %w[fourth]
expect(json['nested']['fourth']).to eq '4'
end
end
describe '#declared; call from child namespace' do
before do
subject.format :json
subject.namespace :parent do
params do
requires :parent_name, type: String
end
namespace ':parent_name' do
params do
requires :child_name, type: String
requires :child_age, type: Integer
end
namespace ':child_name' do
params do
requires :grandchild_name, type: String
end
get ':grandchild_name' do
{
'params' => params,
'without_parent_namespaces' => declared(params, include_parent_namespaces: false),
'with_parent_namespaces' => declared(params, include_parent_namespaces: true)
}
end
end
end
end
get '/parent/foo/bar/baz', child_age: 5, extra: 'hello'
end
let(:parsed_response) { JSON.parse(last_response.body, symbolize_names: true) }
it { expect(last_response).to be_successful }
context 'with include_parent_namespaces: false' do
it 'returns declared parameters only from current namespace' do
expect(parsed_response[:without_parent_namespaces]).to eq(
grandchild_name: 'baz'
)
end
end
context 'with include_parent_namespaces: true' do
it 'returns declared parameters from every parent namespace' do
expect(parsed_response[:with_parent_namespaces]).to eq(
parent_name: 'foo',
child_name: 'bar',
grandchild_name: 'baz',
child_age: 5
)
end
end
context 'without declaration' do
it 'returns all requested parameters' do
expect(parsed_response[:params]).to eq(
parent_name: 'foo',
child_name: 'bar',
grandchild_name: 'baz',
child_age: 5,
extra: 'hello'
)
end
end
end
describe '#declared; from a nested mounted endpoint' do
before do
doubly_mounted = Class.new(Grape::API)
doubly_mounted.namespace :more do
params do
requires :y, type: Integer
end
route_param :y do
get do
{
params: params,
declared_params: declared(params)
}
end
end
end
mounted = Class.new(Grape::API)
mounted.namespace :another do
params do
requires :mount_space, type: Integer
end
route_param :mount_space do
mount doubly_mounted
end
end
subject.format :json
subject.namespace :something do
params do
requires :id, type: Integer
end
resource ':id' do
mount mounted
end
end
end
it 'can access parent attributes' do
get '/something/123/another/456/more/789'
expect(last_response).to be_successful
json = JSON.parse(last_response.body, symbolize_names: true)
# test all three levels of params
expect(json[:declared_params][:y]).to eq 789
expect(json[:declared_params][:mount_space]).to eq 456
expect(json[:declared_params][:id]).to eq 123
end
end
describe '#declared; mixed nesting' do
before do
subject.format :json
subject.resource :users do
route_param :id, type: Integer, desc: 'ID desc' do
# Adding this causes route_setting(:declared_params) to be nil for the
# get block in namespace 'foo' below
get do
end
namespace 'foo' do
get do
{
params: params,
declared_params: declared(params),
declared_params_no_parent: declared(params, include_parent_namespaces: false)
}
end
end
end
end
end
it 'can access parent route_param' do
get '/users/123/foo', bar: 'bar'
expect(last_response).to be_successful
json = JSON.parse(last_response.body, symbolize_names: true)
expect(json[:declared_params][:id]).to eq 123
expect(json[:declared_params_no_parent][:id]).to be_nil
end
end
describe '#declared; with multiple route_param' do
before do
mounted = Class.new(Grape::API)
mounted.namespace :albums do
get do
declared(params)
end
end
subject.format :json
subject.namespace :artists do
route_param :id, type: Integer do
get do
declared(params)
end
params do
requires :filter, type: String
end
get :some_route do
declared(params)
end
end
route_param :artist_id, type: Integer do
namespace :compositions do
get do
declared(params)
end
end
end
route_param :compositor_id, type: Integer do
mount mounted
end
end
end
it 'return only :id without :artist_id' do
get '/artists/1'
json = JSON.parse(last_response.body, symbolize_names: true)
expect(json).to be_key(:id)
expect(json).not_to be_key(:artist_id)
end
it 'return only :artist_id without :id' do
get '/artists/1/compositions'
json = JSON.parse(last_response.body, symbolize_names: true)
expect(json).to be_key(:artist_id)
expect(json).not_to be_key(:id)
end
it 'return :filter and :id parameters in declared for second enpoint inside route_param' do
get '/artists/1/some_route', filter: 'some_filter'
json = JSON.parse(last_response.body, symbolize_names: true)
expect(json).to be_key(:filter)
expect(json).to be_key(:id)
expect(json).not_to be_key(:artist_id)
end
it 'return :compositor_id for mounter in route_param' do
get '/artists/1/albums'
json = JSON.parse(last_response.body, symbolize_names: true)
expect(json).to be_key(:compositor_id)
expect(json).not_to be_key(:id)
expect(json).not_to be_key(:artist_id)
end
end
describe 'parameter renaming' do
context 'with a deeply nested parameter structure' do
let(:params) do
{
i_a: 'a',
i_b: {
i_c: 'c',
i_d: {
i_e: {
i_f: 'f',
i_g: 'g',
i_h: [
{
i_ha: 'ha1',
i_hb: {
i_hc: 'c'
}
},
{
i_ha: 'ha2',
i_hb: {
i_hc: 'c'
}
}
]
}
}
}
}
end
let(:declared) do
{
o_a: 'a',
o_b: {
o_c: 'c',
o_d: {
o_e: {
o_f: 'f',
o_g: 'g',
o_h: [
{
o_ha: 'ha1',
o_hb: {
o_hc: 'c'
}
},
{
o_ha: 'ha2',
o_hb: {
o_hc: 'c'
}
}
]
}
}
}
}
end
let(:params_keys) do
[
'i_a',
'i_b',
'i_b[i_c]',
'i_b[i_d]',
'i_b[i_d][i_e]',
'i_b[i_d][i_e][i_f]',
'i_b[i_d][i_e][i_g]',
'i_b[i_d][i_e][i_h]',
'i_b[i_d][i_e][i_h][i_ha]',
'i_b[i_d][i_e][i_h][i_hb]',
'i_b[i_d][i_e][i_h][i_hb][i_hc]'
]
end
before do
subject.format :json
subject.params do
optional :i_a, type: String, as: :o_a
optional :i_b, type: Hash, as: :o_b do
optional :i_c, type: String, as: :o_c
optional :i_d, type: Hash, as: :o_d do
optional :i_e, type: Hash, as: :o_e do
optional :i_f, type: String, as: :o_f
optional :i_g, type: String, as: :o_g
optional :i_h, type: Array, as: :o_h do
optional :i_ha, type: String, as: :o_ha
optional :i_hb, type: Hash, as: :o_hb do
optional :i_hc, type: String, as: :o_hc
end
end
end
end
end
end
subject.post '/test' do
declared(params, include_missing: false)
end
subject.post '/test/no-mod' do
before = params.to_h
declared(params, include_missing: false)
after = params.to_h
{ before: before, after: after }
end
end
it 'generates the correct parameter names for documentation' do
expect(subject.routes.first.params.keys).to match(params_keys)
end
it 'maps the renamed parameter correctly' do
post '/test', **params
expect(JSON.parse(last_response.body, symbolize_names: true)).to \
match(declared)
end
it 'maps no parameters when none are given' do
post '/test'
expect(JSON.parse(last_response.body)).to match({})
end
it 'does not modify the request params' do
post '/test/no-mod', **params
result = JSON.parse(last_response.body, symbolize_names: true)
expect(result[:before]).to match(result[:after])
end
end
context 'with a renamed root parameter' do
before do
subject.format :json
subject.params do
optional :email_address, type: String, regexp: /.+@.+/, as: :email
end
subject.post '/test' do
declared(params, include_missing: false)
end
end
it 'generates the correct parameter names for documentation' do
expect(subject.routes.first.params.keys).to match(%w[email_address])
end
it 'maps the renamed parameter correctly (original name)' do
post '/test', email_address: 'test@example.com'
expect(JSON.parse(last_response.body)).to \
match('email' => 'test@example.com')
end
it 'validates the renamed parameter correctly (original name)' do
post '/test', email_address: 'bad[at]example.com'
expect(JSON.parse(last_response.body)).to \
match('error' => 'email_address is invalid')
end
it 'ignores the renamed parameter (as name)' do
post '/test', email: 'test@example.com'
expect(JSON.parse(last_response.body)).to match({})
end
end
context 'with a renamed hash with nested parameters' do
before do
subject.format :json
subject.params do
optional :address, type: Hash, as: :address_attributes do
optional :street, type: String, values: ['Street 1', 'Street 2'],
default: 'Street 1'
optional :city, type: String
end
end
subject.post '/test' do
declared(params, include_missing: false)
end
end
it 'generates the correct parameter names for documentation' do
expect(subject.routes.first.params.keys).to \
match(%w[address address[street] address[city]])
end
it 'maps the renamed parameter correctly (original name)' do
post '/test', address: { city: 'Berlin', street: 'Street 2', t: 't' }
expect(JSON.parse(last_response.body)).to \
match('address_attributes' => { 'city' => 'Berlin',
'street' => 'Street 2' })
end
it 'validates the renamed parameter correctly (original name)' do
post '/test', address: { street: 'unknown' }
expect(JSON.parse(last_response.body)).to \
match('error' => 'address[street] does not have a valid value')
end
it 'ignores the renamed parameter (as name)' do
post '/test', address_attributes: { city: 'Berlin', unknown: '1' }
expect(JSON.parse(last_response.body)).to match({})
end
end
context 'with a renamed hash with nested renamed parameter' do
before do
subject.format :json
subject.params do
optional :user, type: Hash, as: :user_attributes do
optional :email_address, type: String, regexp: /.+@.+/, as: :email
end
end
subject.post '/test' do
declared(params, include_missing: false)
end
end
it 'generates the correct parameter names for documentation' do
expect(subject.routes.first.params.keys).to \
match(%w[user user[email_address]])
end
it 'maps the renamed parameter correctly (original name)' do
post '/test', user: { email_address: 'test@example.com' }
expect(JSON.parse(last_response.body)).to \
match('user_attributes' => { 'email' => 'test@example.com' })
end
it 'validates the renamed parameter correctly (original name)' do
post '/test', user: { email_address: 'bad[at]example.com' }
expect(JSON.parse(last_response.body)).to \
match('error' => 'user[email_address] is invalid')
end
it 'ignores the renamed parameter (as name, 1)' do
post '/test', user: { email: 'test@example.com' }
expect(JSON.parse(last_response.body)).to \
match({ 'user_attributes' => {} })
end
it 'ignores the renamed parameter (as name, 2)' do
post '/test', user_attributes: { email_address: 'test@example.com' }
expect(JSON.parse(last_response.body)).to match({})
end
it 'ignores the renamed parameter (as name, 3)' do
post '/test', user_attributes: { email: 'test@example.com' }
expect(JSON.parse(last_response.body)).to match({})
end
end
context 'with a renamed field inside `given` block nested in hashes' do
before do
subject.format :json
subject.params do
requires :a, type: Hash do
optional :c, type: String
given :c do
requires :b, type: Hash do
requires :input_field, as: :output_field
end
end
end
end
subject.post '/test' do
declared(params)
end
end
it 'renames parameter input_field to output_field' do
post '/test', { a: { b: { input_field: 'value' }, c: 'value2' } }
expect(JSON.parse(last_response.body)).to \
match('a' => { 'b' => { 'output_field' => 'value' }, 'c' => 'value2' })
end
end
end
describe 'optional_array' do
subject { last_response }
let(:app) do
Class.new(Grape::API) do
params do
requires :z, type: Array do
optional :a, type: Integer
end
end
post do
declared(params, include_missing: false)
end
end
end
before { post '/', { z: [] } }
it { is_expected.to be_successful }
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/config/spec_test_prof.rb | spec/config/spec_test_prof.rb | # frozen_string_literal: true
require 'test_prof/recipes/rspec/let_it_be'
TestProf::BeforeAll.adapter = Class.new do
def begin_transaction; end
def rollback_transaction; end
end.new
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/shared/versioning_examples.rb | spec/shared/versioning_examples.rb | # frozen_string_literal: true
shared_examples_for 'versioning' do
it 'sets the API version' do
subject.format :txt
subject.version 'v1', **macro_options
subject.get :hello do
"Version: #{request.env[Grape::Env::API_VERSION]}"
end
versioned_get '/hello', 'v1', macro_options
expect(last_response.body).to eql 'Version: v1'
end
it 'adds the prefix before the API version' do
subject.format :txt
subject.prefix 'api'
subject.version 'v1', **macro_options
subject.get :hello do
"Version: #{request.env[Grape::Env::API_VERSION]}"
end
versioned_get '/hello', 'v1', macro_options.merge(prefix: 'api')
expect(last_response.body).to eql 'Version: v1'
end
it 'is able to specify version as a nesting' do
subject.version 'v2', **macro_options
subject.get '/awesome' do
'Radical'
end
subject.version 'v1', **macro_options do
get '/legacy' do
'Totally'
end
end
versioned_get '/awesome', 'v1', macro_options
expect(last_response.status).to be 404
versioned_get '/awesome', 'v2', macro_options
expect(last_response.status).to be 200
versioned_get '/legacy', 'v1', macro_options
expect(last_response.status).to be 200
versioned_get '/legacy', 'v2', macro_options
expect(last_response.status).to be 404
end
it 'is able to specify multiple versions' do
subject.version 'v1', 'v2', **macro_options
subject.get 'awesome' do
'I exist'
end
versioned_get '/awesome', 'v1', macro_options
expect(last_response.status).to be 200
versioned_get '/awesome', 'v2', macro_options
expect(last_response.status).to be 200
versioned_get '/awesome', 'v3', macro_options
expect(last_response.status).to be 404
end
context 'with different versions for the same endpoint' do
context 'without a prefix' do
it 'allows the same endpoint to be implemented' do
subject.format :txt
subject.version 'v2', **macro_options
subject.get 'version' do
request.env[Grape::Env::API_VERSION]
end
subject.version 'v1', **macro_options do
get 'version' do
"version #{request.env[Grape::Env::API_VERSION]}"
end
end
versioned_get '/version', 'v2', macro_options
expect(last_response.status).to eq(200)
expect(last_response.body).to eq('v2')
versioned_get '/version', 'v1', macro_options
expect(last_response.status).to eq(200)
expect(last_response.body).to eq('version v1')
end
end
context 'with a prefix' do
it 'allows the same endpoint to be implemented' do
subject.format :txt
subject.prefix 'api'
subject.version 'v2', **macro_options
subject.get 'version' do
request.env[Grape::Env::API_VERSION]
end
subject.version 'v1', **macro_options do
get 'version' do
"version #{request.env[Grape::Env::API_VERSION]}"
end
end
versioned_get '/version', 'v1', macro_options.merge(prefix: subject.prefix)
expect(last_response.status).to eq(200)
expect(last_response.body).to eq('version v1')
versioned_get '/version', 'v2', macro_options.merge(prefix: subject.prefix)
expect(last_response.status).to eq(200)
expect(last_response.body).to eq('v2')
end
end
end
context 'with before block defined within a version block' do
it 'calls before block that is defined within the version block' do
subject.format :txt
subject.prefix 'api'
subject.version 'v2', **macro_options do
before do
@output ||= 'v2-'
end
get 'version' do
@output += 'version'
end
end
subject.version 'v1', **macro_options do
before do
@output ||= 'v1-'
end
get 'version' do
@output += 'version'
end
end
versioned_get '/version', 'v1', macro_options.merge(prefix: subject.prefix)
expect(last_response.status).to eq(200)
expect(last_response.body).to eq('v1-version')
versioned_get '/version', 'v2', macro_options.merge(prefix: subject.prefix)
expect(last_response.status).to eq(200)
expect(last_response.body).to eq('v2-version')
end
end
it 'does not overwrite version parameter with API version' do
subject.format :txt
subject.version 'v1', **macro_options
subject.params { requires :version }
subject.get :api_version_with_version_param do
params[:version]
end
versioned_get '/api_version_with_version_param?version=1', 'v1', macro_options
expect(last_response.body).to eql '1'
end
context 'with catch-all' do
let(:options) { macro_options }
let(:v1) do
klass = Class.new(Grape::API)
klass.version 'v1', **options
klass.get 'version' do
'v1'
end
klass
end
let(:v2) do
klass = Class.new(Grape::API)
klass.version 'v2', **options
klass.get 'version' do
'v2'
end
klass
end
before do
subject.format :txt
subject.mount v1
subject.mount v2
subject.route :any, '*path' do
params[:path]
end
end
context 'v1' do
it 'finds endpoint' do
versioned_get '/version', 'v1', macro_options
expect(last_response.status).to eq(200)
expect(last_response.body).to eq('v1')
end
it 'finds catch all' do
versioned_get '/whatever', 'v1', macro_options
expect(last_response.status).to eq(200)
expect(last_response.body).to end_with 'whatever'
end
end
context 'v2' do
it 'finds endpoint' do
versioned_get '/version', 'v2', macro_options
expect(last_response.status).to eq(200)
expect(last_response.body).to eq('v2')
end
it 'finds catch all' do
versioned_get '/whatever', 'v2', macro_options
expect(last_response.status).to eq(200)
expect(last_response.body).to end_with 'whatever'
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape.rb | lib/grape.rb | # frozen_string_literal: true
require 'logger'
require 'active_support'
require 'active_support/version'
require 'active_support/isolated_execution_state'
require 'active_support/core_ext/array/conversions' # to_xml
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/hash/conversions' # to_xml
require 'active_support/core_ext/hash/deep_merge'
require 'active_support/core_ext/hash/deep_transform_values'
require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/hash/reverse_merge'
require 'active_support/core_ext/module/delegation' # delegate_missing_to
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/deep_dup'
require 'active_support/core_ext/object/duplicable'
require 'active_support/deprecation'
require 'active_support/inflector'
require 'active_support/ordered_options'
require 'active_support/notifications'
require 'English'
require 'bigdecimal'
require 'date'
require 'dry-types'
require 'dry-configurable'
require 'forwardable'
require 'json'
require 'mustermann/grape'
require 'pathname'
require 'rack'
require 'rack/auth/basic'
require 'rack/builder'
require 'rack/head'
require 'set'
require 'singleton'
require 'zeitwerk'
loader = Zeitwerk::Loader.for_gem
loader.inflector.inflect(
'api' => 'API',
'dsl' => 'DSL'
)
railtie = "#{__dir__}/grape/railtie.rb"
loader.do_not_eager_load(railtie)
loader.setup
I18n.load_path << File.expand_path('grape/locale/en.yml', __dir__)
module Grape
extend Dry::Configurable
setting :param_builder, default: :hash_with_indifferent_access
setting :lint, default: false
HTTP_SUPPORTED_METHODS = [
Rack::GET,
Rack::POST,
Rack::PUT,
Rack::PATCH,
Rack::DELETE,
Rack::HEAD,
Rack::OPTIONS
].freeze
def self.deprecator
@deprecator ||= ActiveSupport::Deprecation.new('2.0', 'Grape')
end
end
# https://api.rubyonrails.org/classes/ActiveSupport/Deprecation.html
# adding Grape.deprecator to Rails App if any
require 'grape/railtie' if defined?(Rails::Railtie)
loader.eager_load
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/dry_types.rb | lib/grape/dry_types.rb | # frozen_string_literal: true
module Grape
module DryTypes
# https://dry-rb.org/gems/dry-types/main/getting-started/
# limit to what Grape is using
include Dry.Types(:params, :coercible, :strict)
class StrictCache < Grape::Util::Cache
MAPPING = {
Grape::API::Boolean => DryTypes::Strict::Bool,
BigDecimal => DryTypes::Strict::Decimal,
Numeric => DryTypes::Strict::Integer | DryTypes::Strict::Float | DryTypes::Strict::Decimal,
TrueClass => DryTypes::Strict::Bool.constrained(eql: true),
FalseClass => DryTypes::Strict::Bool.constrained(eql: false)
}.freeze
def initialize
super
@cache = Hash.new do |h, strict_type|
h[strict_type] = MAPPING.fetch(strict_type) do
DryTypes.wrapped_dry_types_const_get(DryTypes::Strict, strict_type)
end
end
end
end
class ParamsCache < Grape::Util::Cache
MAPPING = {
Grape::API::Boolean => DryTypes::Params::Bool,
BigDecimal => DryTypes::Params::Decimal,
Numeric => DryTypes::Params::Integer | DryTypes::Params::Float | DryTypes::Params::Decimal,
TrueClass => DryTypes::Params::Bool.constrained(eql: true),
FalseClass => DryTypes::Params::Bool.constrained(eql: false),
String => DryTypes::Coercible::String
}.freeze
def initialize
super
@cache = Hash.new do |h, params_type|
h[params_type] = MAPPING.fetch(params_type) do
DryTypes.wrapped_dry_types_const_get(DryTypes::Params, params_type)
end
end
end
end
def self.wrapped_dry_types_const_get(dry_type, type)
dry_type.const_get(type.name, false)
rescue NameError
raise ArgumentError, "type #{type} should support coercion via `[]`" unless type.respond_to?(:[])
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/path.rb | lib/grape/path.rb | # frozen_string_literal: true
module Grape
# Represents a path to an endpoint.
class Path
DEFAULT_FORMAT_SEGMENT = '(/.:format)'
NO_VERSIONING_WITH_VALID_PATH_FORMAT_SEGMENT = '(.:format)'
VERSION_SEGMENT = ':version'
attr_reader :origin, :suffix
def initialize(raw_path, raw_namespace, settings)
@origin = PartsCache[build_parts(raw_path, raw_namespace, settings)]
@suffix = build_suffix(raw_path, raw_namespace, settings)
end
def to_s
"#{origin}#{suffix}"
end
private
def build_suffix(raw_path, raw_namespace, settings)
if uses_specific_format?(settings)
"(.#{settings[:format]})"
elsif !uses_path_versioning?(settings) || (valid_part?(raw_namespace) || valid_part?(raw_path))
NO_VERSIONING_WITH_VALID_PATH_FORMAT_SEGMENT
else
DEFAULT_FORMAT_SEGMENT
end
end
def build_parts(raw_path, raw_namespace, settings)
[].tap do |parts|
add_part(parts, settings[:mount_path])
add_part(parts, settings[:root_prefix])
parts << VERSION_SEGMENT if uses_path_versioning?(settings)
add_part(parts, raw_namespace)
add_part(parts, raw_path)
end
end
def add_part(parts, value)
parts << value if value && not_slash?(value)
end
def not_slash?(value)
value != '/'
end
def uses_specific_format?(settings)
return false unless settings.key?(:format) && settings.key?(:content_types)
settings[:format] && Array(settings[:content_types]).size == 1
end
def uses_path_versioning?(settings)
return false unless settings.key?(:version) && settings[:version_options]&.key?(:using)
settings[:version] && settings[:version_options][:using] == :path
end
def valid_part?(part)
part&.match?(/^\S/) && not_slash?(part)
end
class PartsCache < Grape::Util::Cache
def initialize
super
@cache = Hash.new do |h, parts|
h[parts] = Grape::Router.normalize_path(parts.join('/'))
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/cookies.rb | lib/grape/cookies.rb | # frozen_string_literal: true
module Grape
class Cookies
extend Forwardable
DELETED_COOKIES_ATTRS = {
max_age: '0',
value: '',
expires: Time.at(0)
}.freeze
def_delegators :cookies, :[], :each
def initialize(rack_cookies)
@cookies = rack_cookies
@send_cookies = nil
end
def response_cookies
return unless @send_cookies
send_cookies.each do |name|
yield name, cookies[name]
end
end
def []=(name, value)
cookies[name] = value
send_cookies << name
end
# see https://github.com/rack/rack/blob/main/lib/rack/utils.rb#L338-L340
def delete(name, **opts)
self.[]=(name, opts.merge(DELETED_COOKIES_ATTRS))
end
private
def cookies
return @cookies unless @cookies.is_a?(Proc)
@cookies = @cookies.call.with_indifferent_access
end
def send_cookies
@send_cookies ||= Set.new
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/content_types.rb | lib/grape/content_types.rb | # frozen_string_literal: true
module Grape
module ContentTypes
module_function
# Content types are listed in order of preference.
DEFAULTS = {
xml: 'application/xml',
serializable_hash: 'application/json',
json: 'application/json',
binary: 'application/octet-stream',
txt: 'text/plain'
}.freeze
MIME_TYPES = Grape::ContentTypes::DEFAULTS.except(:serializable_hash).invert.freeze
def content_types_for(from_settings)
from_settings.presence || DEFAULTS
end
def mime_types_for(from_settings)
return MIME_TYPES if from_settings == Grape::ContentTypes::DEFAULTS
from_settings.invert.transform_keys! { |k| k.include?(';') ? k.split(';', 2).first : k }
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/version.rb | lib/grape/version.rb | # frozen_string_literal: true
module Grape
# The current version of Grape.
VERSION = '3.1.0'
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/declared_params_handler.rb | lib/grape/declared_params_handler.rb | # frozen_string_literal: true
module Grape
class DeclaredParamsHandler
def initialize(include_missing: true, evaluate_given: false, stringify: false, contract_key_map: nil)
@include_missing = include_missing
@evaluate_given = evaluate_given
@stringify = stringify
@contract_key_map = contract_key_map
end
def call(passed_params, declared_params, route_params, renamed_params)
recursive_declared(
passed_params,
declared_params: declared_params,
route_params: route_params,
renamed_params: renamed_params
)
end
private
def recursive_declared(passed_params, declared_params:, route_params:, renamed_params:, params_nested_path: [])
res = if passed_params.is_a?(Array)
passed_params.map do |passed_param|
recursive_declared(passed_param, declared_params:, params_nested_path:, renamed_params:, route_params:)
end
else
declared_hash(passed_params, declared_params:, params_nested_path:, renamed_params:, route_params:)
end
@contract_key_map&.each { |key_map| key_map.write(passed_params, res) }
res
end
def declared_hash(passed_params, declared_params:, params_nested_path:, renamed_params:, route_params:)
declared_params.each_with_object(passed_params.class.new) do |declared_param_attr, memo|
next if @evaluate_given && !declared_param_attr.scope.attr_meets_dependency?(passed_params)
declared_hash_attr(
passed_params,
declared_param: declared_param_attr.key,
params_nested_path:,
memo:,
renamed_params:,
route_params:
)
end
end
def declared_hash_attr(passed_params, declared_param:, params_nested_path:, memo:, renamed_params:, route_params:)
if declared_param.is_a?(Hash)
declared_param.each_pair do |declared_parent_param, declared_children_params|
next unless @include_missing || passed_params.key?(declared_parent_param)
memo_key = build_memo_key(params_nested_path, declared_parent_param, renamed_params)
passed_children_params = passed_params[declared_parent_param] || passed_params.class.new
params_nested_path_dup = params_nested_path.dup
params_nested_path_dup << declared_parent_param.to_s
memo[memo_key] = handle_passed_param(params_nested_path_dup, route_params:, has_passed_children: passed_children_params.any?) do
recursive_declared(
passed_children_params,
declared_params: declared_children_params,
params_nested_path: params_nested_path_dup,
renamed_params:,
route_params:
)
end
end
else
# If it is not a Hash then it does not have children.
# Find its value or set it to nil.
return unless @include_missing || (passed_params.respond_to?(:key?) && passed_params.key?(declared_param))
memo_key = build_memo_key(params_nested_path, declared_param, renamed_params)
passed_param = passed_params[declared_param]
params_nested_path_dup = params_nested_path.dup
params_nested_path_dup << declared_param.to_s
memo[memo_key] = passed_param || handle_passed_param(params_nested_path_dup, route_params:) do
passed_param
end
end
end
def build_memo_key(params_nested_path, declared_param, renamed_params)
rename_path = params_nested_path + [declared_param.to_s]
renamed_param_name = renamed_params[rename_path]
param = renamed_param_name || declared_param
@stringify ? param.to_s : param.to_sym
end
def handle_passed_param(params_nested_path, route_params:, has_passed_children: false, &_block)
return yield if has_passed_children
key = params_nested_path[0]
key += "[#{params_nested_path[1..].join('][')}]" if params_nested_path.size > 1
type = route_params.dig(key, :type)
has_children = route_params.keys.any? { |k| k != key && k.start_with?("#{key}[") }
if type == 'Hash' && !has_children
{}
elsif type == 'Array' || (type&.start_with?('[') && !type.include?(','))
[]
elsif type == 'Set' || type&.start_with?('#<Set', 'Set')
Set.new
else
yield
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/namespace.rb | lib/grape/namespace.rb | # frozen_string_literal: true
module Grape
# A container for endpoints or other namespaces, which allows for both
# logical grouping of endpoints as well as sharing common configuration.
# May also be referred to as group, segment, or resource.
class Namespace
attr_reader :space, :requirements, :options
# @param space [String] the name of this namespace
# @param options [Hash] options hash
# @option options :requirements [Hash] param-regex pairs, all of which must
# be met by a request's params for all endpoints in this namespace, or
# validation will fail and return a 422.
def initialize(space, requirements: nil, **options)
@space = space.to_s
@requirements = requirements
@options = options
end
# (see ::joined_space_path)
def self.joined_space(settings)
settings&.map(&:space)
end
def eql?(other)
other.class == self.class &&
other.space == space &&
other.requirements == requirements &&
other.options == options
end
alias == eql?
def hash
[self.class, space, requirements, options].hash
end
# Join the namespaces from a list of settings to create a path prefix.
# @param settings [Array] list of Grape::Util::InheritableSettings.
def self.joined_space_path(settings)
JoinedSpaceCache[joined_space(settings)]
end
class JoinedSpaceCache < Grape::Util::Cache
def initialize
super
@cache = Hash.new do |h, joined_space|
h[joined_space] = Grape::Router.normalize_path(joined_space.join('/'))
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/xml.rb | lib/grape/xml.rb | # frozen_string_literal: true
module Grape
if defined?(::MultiXml)
Xml = ::MultiXml
else
Xml = ::ActiveSupport::XmlMini
Xml::ParseError = StandardError
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/error_formatter.rb | lib/grape/error_formatter.rb | # frozen_string_literal: true
module Grape
module ErrorFormatter
extend Grape::Util::Registry
module_function
def formatter_for(format, error_formatters = nil, default_error_formatter = nil)
return error_formatters[format] if error_formatters&.key?(format)
registry[format] || default_error_formatter || Grape::ErrorFormatter::Txt
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/router.rb | lib/grape/router.rb | # frozen_string_literal: true
module Grape
class Router
# Taken from Rails
# normalize_path("/foo") # => "/foo"
# normalize_path("/foo/") # => "/foo"
# normalize_path("foo") # => "/foo"
# normalize_path("") # => "/"
# normalize_path("/%ab") # => "/%AB"
# https://github.com/rails/rails/blob/00cc4ff0259c0185fe08baadaa40e63ea2534f6e/actionpack/lib/action_dispatch/journey/router/utils.rb#L19
def self.normalize_path(path)
return '/' unless path
return path if path == '/'
# Fast path for the overwhelming majority of paths that don't need to be normalized
return path if path.start_with?('/') && !(path.end_with?('/') || path.match?(%r{%|//}))
# Slow path
encoding = path.encoding
path = "/#{path}"
path.squeeze!('/')
unless path == '/'
path.delete_suffix!('/')
path.gsub!(/(%[a-f0-9]{2})/) { ::Regexp.last_match(1).upcase }
end
path.force_encoding(encoding)
end
def initialize
@neutral_map = []
@neutral_regexes = []
@map = Hash.new { |hash, key| hash[key] = [] }
@optimized_map = Hash.new { |hash, key| hash[key] = // }
end
def compile!
return if @compiled
@union = Regexp.union(@neutral_regexes)
@neutral_regexes = nil
(Grape::HTTP_SUPPORTED_METHODS + ['*']).each do |method|
next unless @map.key?(method)
routes = @map[method]
optimized_map = routes.map.with_index { |route, index| route.to_regexp(index) }
@optimized_map[method] = Regexp.union(optimized_map)
end
@compiled = true
end
def append(route)
@map[route.request_method] << route
end
def associate_routes(greedy_route)
@neutral_regexes << greedy_route.to_regexp(@neutral_map.length)
@neutral_map << greedy_route
end
def call(env)
with_optimization do
input = Router.normalize_path(env[Rack::PATH_INFO])
method = env[Rack::REQUEST_METHOD]
response, route = identity(input, method, env)
response || rotation(input, method, env, route)
end
end
def recognize_path(input)
any = with_optimization { greedy_match?(input) }
return if any == default_response
any.endpoint
end
private
def identity(input, method, env)
route = nil
response = transaction(input, method, env) do
route = match?(input, method)
process_route(route, input, env) if route
end
[response, route]
end
def rotation(input, method, env, exact_route)
response = nil
@map[method].each do |route|
next if exact_route == route
next unless route.match?(input)
response = process_route(route, input, env)
break unless cascade?(response)
end
response
end
def transaction(input, method, env)
# using a Proc is important since `return` will exit the enclosing function
cascade_or_return_response = proc do |response|
if response
cascade?(response).tap do |cascade|
return response unless cascade
# we need to close the body if possible before dismissing
response[2].close if response[2].respond_to?(:close)
end
end
end
response = yield
last_response_cascade = cascade_or_return_response.call(response)
last_neighbor_route = greedy_match?(input)
# If last_neighbor_route exists and request method is OPTIONS,
# return response by using #include_allow_header.
return process_route(last_neighbor_route, input, env, include_allow_header: true) if !last_response_cascade && method == Rack::OPTIONS && last_neighbor_route
route = match?(input, '*')
return last_neighbor_route.call(env) if last_neighbor_route && last_response_cascade && route
last_response_cascade = cascade_or_return_response.call(process_route(route, input, env)) if route
return process_route(last_neighbor_route, input, env, include_allow_header: true) if !last_response_cascade && last_neighbor_route
nil
end
def process_route(route, input, env, include_allow_header: false)
args = env[Grape::Env::GRAPE_ROUTING_ARGS] || { route_info: route }
route_params = route.params(input)
routing_args = args.merge(route_params || {})
env[Grape::Env::GRAPE_ROUTING_ARGS] = routing_args
env[Grape::Env::GRAPE_ALLOWED_METHODS] = route.allow_header if include_allow_header
route.call(env)
end
def with_optimization
compile!
yield || default_response
end
def default_response
headers = Grape::Util::Header.new.merge('X-Cascade' => 'pass')
[404, headers, ['404 Not Found']]
end
def match?(input, method)
@optimized_map[method].match(input) { |m| @map[method].detect { |route| m[route.regexp_capture_index] } }
end
def greedy_match?(input)
@union.match(input) { |m| @neutral_map.detect { |route| m[route.regexp_capture_index] } }
end
def cascade?(response)
response && response[1]['X-Cascade'] == 'pass'
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/params_builder.rb | lib/grape/params_builder.rb | # frozen_string_literal: true
module Grape
module ParamsBuilder
extend Grape::Util::Registry
module_function
def params_builder_for(short_name)
raise Grape::Exceptions::UnknownParamsBuilder, short_name unless registry.key?(short_name)
registry[short_name]
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/parser.rb | lib/grape/parser.rb | # frozen_string_literal: true
module Grape
module Parser
extend Grape::Util::Registry
module_function
def parser_for(format, parsers = nil)
return parsers[format] if parsers&.key?(format)
registry[format]
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/validations.rb | lib/grape/validations.rb | # frozen_string_literal: true
module Grape
module Validations
extend Grape::Util::Registry
module_function
def require_validator(short_name)
raise Grape::Exceptions::UnknownValidator, short_name unless registry.key?(short_name)
registry[short_name]
end
def build_short_name(klass)
return if klass.name.blank?
klass.name.demodulize.underscore.delete_suffix('_validator')
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/json.rb | lib/grape/json.rb | # frozen_string_literal: true
module Grape
if defined?(::MultiJson)
Json = ::MultiJson
else
Json = ::JSON
Json::ParseError = Json::ParserError
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/env.rb | lib/grape/env.rb | # frozen_string_literal: true
module Grape
module Env
API_VERSION = 'api.version'
API_ENDPOINT = 'api.endpoint'
API_REQUEST_INPUT = 'api.request.input'
API_REQUEST_BODY = 'api.request.body'
API_TYPE = 'api.type'
API_SUBTYPE = 'api.subtype'
API_VENDOR = 'api.vendor'
API_FORMAT = 'api.format'
GRAPE_REQUEST = 'grape.request'
GRAPE_REQUEST_HEADERS = 'grape.request.headers'
GRAPE_REQUEST_PARAMS = 'grape.request.params'
GRAPE_ROUTING_ARGS = 'grape.routing_args'
GRAPE_ALLOWED_METHODS = 'grape.allowed_methods'
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/railtie.rb | lib/grape/railtie.rb | # frozen_string_literal: true
module Grape
class Railtie < ::Rails::Railtie
initializer 'grape.deprecator' do |app|
app.deprecators[:grape] = Grape.deprecator
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/api.rb | lib/grape/api.rb | # frozen_string_literal: true
module Grape
# The API class is the primary entry point for creating Grape APIs. Users
# should subclass this class in order to build an API.
class API
# Class methods that we want to call on the API rather than on the API object
NON_OVERRIDABLE = %i[base= base_instance? call change! configuration compile! inherit_settings recognize_path reset! routes top_level_setting= top_level_setting].freeze
Helpers = Grape::DSL::Helpers::BaseHelper
class Boolean
def self.build(val)
return nil if val != true && val != false
new
end
end
class << self
extend Forwardable
attr_accessor :base_instance, :instances
delegate_missing_to :base_instance
# This is the interface point between Rack and Grape; it accepts a request
# from Rack and ultimately returns an array of three values: the status,
# the headers, and the body. See [the rack specification]
# (https://github.com/rack/rack/blob/main/SPEC.rdoc) for more.
# NOTE: This will only be called on an API directly mounted on RACK
def_delegators :base_instance, :new, :configuration, :call, :change!, :compile!, :recognize_path, :routes
# Initialize the instance variables on the remountable class, and the base_instance
# an instance that will be used to create the set up but will not be mounted
def initial_setup(base_instance_parent)
@instances = []
@setup = []
@base_parent = base_instance_parent
@base_instance = mount_instance
end
# Redefines all methods so that are forwarded to add_setup and be recorded
def override_all_methods!
(base_instance.methods - Class.methods - NON_OVERRIDABLE).each do |method_override|
define_singleton_method(method_override) do |*args, **kwargs, &block|
add_setup(method: method_override, args: args, kwargs: kwargs, block: block)
end
end
end
# Configure an API from the outside. If a block is given, it'll pass a
# configuration hash to the block which you can use to configure your
# API. If no block is given, returns the configuration hash.
# The configuration set here is accessible from inside an API with
# `configuration` as normal.
def configure
config = @base_instance.configuration
if block_given?
yield config
self
else
config
end
end
# The remountable class can have a configuration hash to provide some dynamic class-level variables.
# For instance, a description could be done using: `desc configuration[:description]` if it may vary
# depending on where the endpoint is mounted. Use with care, if you find yourself using configuration
# too much, you may actually want to provide a new API rather than remount it.
def mount_instance(configuration: nil)
Class.new(@base_parent).tap do |instance|
instance.configuration = Grape::Util::EndpointConfiguration.new(configuration || {})
instance.base = self
replay_setup_on(instance)
end
end
private
# When inherited, will create a list of all instances (times the API was mounted)
# It will listen to the setup required to mount that endpoint, and replicate it on any new instance
def inherited(api)
super
api.initial_setup(self == Grape::API ? Grape::API::Instance : @base_instance)
api.override_all_methods!
end
# Replays the set up to produce an API as defined in this class, can be called
# on classes that inherit from Grape::API
def replay_setup_on(instance)
@setup.each do |setup_step|
replay_step_on(instance, **setup_step)
end
end
# Adds a new stage to the set up require to get a Grape::API up and running
def add_setup(**step)
@setup << step
last_response = nil
@instances.each do |instance|
last_response = replay_step_on(instance, **step)
end
refresh_mount_step if step[:method] != :mount
last_response
end
# Updating all previously mounted classes in the case that new methods have been executed.
def refresh_mount_step
@setup.each do |setup_step|
next if setup_step[:method] != :mount
refresh_mount_step = setup_step.merge(method: :refresh_mounted_api)
@setup << refresh_mount_step
@instances.each do |instance|
replay_step_on(instance, **refresh_mount_step)
end
end
end
def replay_step_on(instance, method:, args:, kwargs:, block:)
return if skip_immediate_run?(instance, args, kwargs)
eval_args = evaluate_arguments(instance.configuration, *args)
eval_kwargs = kwargs.deep_transform_values { |v| evaluate_arguments(instance.configuration, v).first }
response = instance.__send__(method, *eval_args, **eval_kwargs, &block)
if skip_immediate_run?(instance, [response], kwargs)
response
else
evaluate_arguments(instance.configuration, response).first
end
end
# Skips steps that contain arguments to be lazily executed (on re-mount time)
def skip_immediate_run?(instance, args, kwargs)
instance.base_instance? &&
(any_lazy?(args) || args.any? { |arg| arg.is_a?(Hash) && any_lazy?(arg.values) } || any_lazy?(kwargs.values))
end
def any_lazy?(args)
args.any? { |argument| argument_lazy?(argument) }
end
def evaluate_arguments(configuration, *args)
args.map do |argument|
if argument_lazy?(argument)
argument.evaluate_from(configuration)
elsif argument.is_a?(Hash)
argument.transform_values { |value| evaluate_arguments(configuration, value).first }
elsif argument.is_a?(Array)
evaluate_arguments(configuration, *argument)
else
argument
end
end
end
def argument_lazy?(argument)
argument.respond_to?(:lazy?) && argument.lazy?
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/endpoint.rb | lib/grape/endpoint.rb | # frozen_string_literal: true
module Grape
# An Endpoint is the proxy scope in which all routing
# blocks are executed. In other words, any methods
# on the instance level of this class may be called
# from inside a `get`, `post`, etc.
class Endpoint
extend Forwardable
include Grape::DSL::Settings
include Grape::DSL::Headers
include Grape::DSL::InsideRoute
attr_reader :env, :request, :source, :options
def_delegators :request, :params, :headers, :cookies
def_delegator :cookies, :response_cookies
class << self
def before_each(new_setup = false, &block)
@before_each ||= []
if new_setup == false
return @before_each unless block
@before_each << block
else
@before_each = [new_setup]
end
end
def run_before_each(endpoint)
superclass.run_before_each(endpoint) unless self == Endpoint
before_each.each { |blk| blk.call(endpoint) }
end
def block_to_unbound_method(block)
return unless block
define_method :temp_unbound_method, block
method = instance_method(:temp_unbound_method)
remove_method :temp_unbound_method
method
end
end
# Create a new endpoint.
# @param new_settings [InheritableSetting] settings to determine the params,
# validations, and other properties from.
# @param options [Hash] attributes of this endpoint
# @option options path [String or Array] the path to this endpoint, within
# the current scope.
# @option options method [String or Array] which HTTP method(s) can be used
# to reach this endpoint.
# @option options route_options [Hash]
# @note This happens at the time of API definition, so in this context the
# endpoint does not know if it will be mounted under a different endpoint.
# @yield a block defining what your API should do when this endpoint is hit
def initialize(new_settings, **options, &block)
self.inheritable_setting = new_settings.point_in_time_copy
# now +namespace_stackable(:declared_params)+ contains all params defined for
# this endpoint and its parents, but later it will be cleaned up,
# see +reset_validations!+ in lib/grape/dsl/validations.rb
inheritable_setting.route[:declared_params] = inheritable_setting.namespace_stackable[:declared_params].flatten
inheritable_setting.route[:saved_validations] = inheritable_setting.namespace_stackable[:validations]
inheritable_setting.namespace_stackable[:representations] = [] unless inheritable_setting.namespace_stackable[:representations]
inheritable_setting.namespace_inheritable[:default_error_status] = 500 unless inheritable_setting.namespace_inheritable[:default_error_status]
@options = options
@options[:path] = Array(options[:path])
@options[:path] << '/' if options[:path].empty?
@options[:method] = Array(options[:method])
@status = nil
@stream = nil
@body = nil
@source = self.class.block_to_unbound_method(block)
@before_filter_passed = false
end
# Update our settings from a given set of stackable parameters. Used when
# the endpoint's API is mounted under another one.
def inherit_settings(namespace_stackable)
parent_validations = namespace_stackable[:validations]
inheritable_setting.route[:saved_validations].concat(parent_validations) if parent_validations.any?
parent_declared_params = namespace_stackable[:declared_params]
inheritable_setting.route[:declared_params].concat(parent_declared_params.flatten) if parent_declared_params.any?
endpoints&.each { |e| e.inherit_settings(namespace_stackable) }
end
def routes
@routes ||= endpoints&.collect(&:routes)&.flatten || to_routes
end
def reset_routes!
endpoints&.each(&:reset_routes!)
@namespace = nil
@routes = nil
end
def mount_in(router)
if endpoints
compile!
return endpoints.each { |e| e.mount_in(router) }
end
reset_routes!
compile!
routes.each do |route|
router.append(route.apply(self))
next unless !inheritable_setting.namespace_inheritable[:do_not_route_head] && route.request_method == Rack::GET
route.dup.then do |head_route|
head_route.convert_to_head_request!
router.append(head_route.apply(self))
end
end
end
def namespace
@namespace ||= Namespace.joined_space_path(inheritable_setting.namespace_stackable[:namespace])
end
def call(env)
dup.call!(env)
end
def call!(env)
env[Grape::Env::API_ENDPOINT] = self
@env = env
# this adds the helpers only to the instance
singleton_class.include(@helpers) if @helpers
@app.call(env)
end
# Return the collection of endpoints within this endpoint.
# This is the case when an Grape::API mounts another Grape::API.
def endpoints
@endpoints ||= options[:app].respond_to?(:endpoints) ? options[:app].endpoints : nil
end
def equals?(endpoint)
(options == endpoint.options) && (inheritable_setting.to_hash == endpoint.inheritable_setting.to_hash)
end
# The purpose of this override is solely for stripping internals when an error occurs while calling
# an endpoint through an api. See https://github.com/ruby-grape/grape/issues/2398
# Otherwise, it calls super.
def inspect
return super unless env
"#{self.class} in '#{route.origin}' endpoint"
end
protected
def run
ActiveSupport::Notifications.instrument('endpoint_run.grape', endpoint: self, env: env) do
@request = Grape::Request.new(env, build_params_with: inheritable_setting.namespace_inheritable[:build_params_with])
begin
self.class.run_before_each(self)
run_filters befores, :before
@before_filter_passed = true
if env.key?(Grape::Env::GRAPE_ALLOWED_METHODS)
header['Allow'] = env[Grape::Env::GRAPE_ALLOWED_METHODS].join(', ')
raise Grape::Exceptions::MethodNotAllowed.new(header) unless options?
header 'Allow', header['Allow']
response_object = ''
status 204
else
run_filters before_validations, :before_validation
run_validators validations, request
run_filters after_validations, :after_validation
response_object = execute
end
run_filters afters, :after
build_response_cookies
# status verifies body presence when DELETE
@body ||= response_object
# The body commonly is an Array of Strings, the application instance itself, or a Stream-like object
response_object = stream || [body]
[status, header, response_object]
ensure
run_filters finallies, :finally
end
end
end
def execute
return unless @source
ActiveSupport::Notifications.instrument('endpoint_render.grape', endpoint: self) do
@source.bind_call(self)
end
end
def run_validators(validators, request)
validation_errors = []
ActiveSupport::Notifications.instrument('endpoint_run_validators.grape', endpoint: self, validators: validators, request: request) do
validators.each do |validator|
validator.validate(request)
rescue Grape::Exceptions::Validation => e
validation_errors << e
break if validator.fail_fast?
rescue Grape::Exceptions::ValidationArrayErrors => e
validation_errors.concat e.errors
break if validator.fail_fast?
end
end
validation_errors.any? && raise(Grape::Exceptions::ValidationErrors.new(errors: validation_errors, headers: header))
end
def run_filters(filters, type = :other)
return unless filters
ActiveSupport::Notifications.instrument('endpoint_run_filters.grape', endpoint: self, filters: filters, type: type) do
filters.each { |filter| instance_eval(&filter) }
end
end
%i[befores before_validations after_validations afters finallies].each do |method|
define_method method do
inheritable_setting.namespace_stackable[method]
end
end
def validations
saved_validations = inheritable_setting.route[:saved_validations]
return if saved_validations.nil?
return enum_for(:validations) unless block_given?
saved_validations.each do |saved_validation|
yield Grape::Validations::ValidatorFactory.create_validator(saved_validation)
end
end
def options?
options[:options_route_enabled] &&
env[Rack::REQUEST_METHOD] == Rack::OPTIONS
end
private
attr_reader :before_filter_passed
def compile!
@app = options[:app] || build_stack
@helpers = build_helpers
end
def to_routes
route_options = options[:route_options]
default_route_options = prepare_default_route_attributes(route_options)
complete_route_options = route_options.merge(default_route_options)
path_settings = prepare_default_path_settings
options[:method].flat_map do |method|
options[:path].map do |path|
prepared_path = Path.new(path, default_route_options[:namespace], path_settings)
pattern = Grape::Router::Pattern.new(
origin: prepared_path.origin,
suffix: prepared_path.suffix,
anchor: default_route_options[:anchor],
params: route_options[:params],
format: options[:format],
version: default_route_options[:version],
requirements: default_route_options[:requirements]
)
Grape::Router::Route.new(self, method, pattern, complete_route_options)
end
end
end
def prepare_default_route_attributes(route_options)
{
namespace: namespace,
version: prepare_version(inheritable_setting.namespace_inheritable[:version]),
requirements: prepare_routes_requirements(route_options[:requirements]),
prefix: inheritable_setting.namespace_inheritable[:root_prefix],
anchor: route_options.fetch(:anchor, true),
settings: inheritable_setting.route.except(:declared_params, :saved_validations),
forward_match: options[:forward_match]
}
end
def prepare_default_path_settings
namespace_stackable_hash = inheritable_setting.namespace_stackable.to_hash
namespace_inheritable_hash = inheritable_setting.namespace_inheritable.to_hash
namespace_stackable_hash.merge!(namespace_inheritable_hash)
end
def prepare_routes_requirements(route_options_requirements)
namespace_requirements = inheritable_setting.namespace_stackable[:namespace].filter_map(&:requirements)
namespace_requirements << route_options_requirements if route_options_requirements.present?
namespace_requirements.reduce({}, :merge)
end
def prepare_version(namespace_inheritable_version)
return if namespace_inheritable_version.blank?
namespace_inheritable_version.length == 1 ? namespace_inheritable_version.first : namespace_inheritable_version
end
def build_stack
stack = Grape::Middleware::Stack.new
content_types = inheritable_setting.namespace_stackable_with_hash(:content_types)
format = inheritable_setting.namespace_inheritable[:format]
stack.use Rack::Head
stack.use Rack::Lint if lint?
stack.use Grape::Middleware::Error,
format: format,
content_types: content_types,
default_status: inheritable_setting.namespace_inheritable[:default_error_status],
rescue_all: inheritable_setting.namespace_inheritable[:rescue_all],
rescue_grape_exceptions: inheritable_setting.namespace_inheritable[:rescue_grape_exceptions],
default_error_formatter: inheritable_setting.namespace_inheritable[:default_error_formatter],
error_formatters: inheritable_setting.namespace_stackable_with_hash(:error_formatters),
rescue_options: inheritable_setting.namespace_stackable_with_hash(:rescue_options),
rescue_handlers: rescue_handlers,
base_only_rescue_handlers: inheritable_setting.namespace_stackable_with_hash(:base_only_rescue_handlers),
all_rescue_handler: inheritable_setting.namespace_inheritable[:all_rescue_handler],
grape_exceptions_rescue_handler: inheritable_setting.namespace_inheritable[:grape_exceptions_rescue_handler]
stack.concat inheritable_setting.namespace_stackable[:middleware]
if inheritable_setting.namespace_inheritable[:version].present?
stack.use Grape::Middleware::Versioner.using(inheritable_setting.namespace_inheritable[:version_options][:using]),
versions: inheritable_setting.namespace_inheritable[:version].flatten,
version_options: inheritable_setting.namespace_inheritable[:version_options],
prefix: inheritable_setting.namespace_inheritable[:root_prefix],
mount_path: inheritable_setting.namespace_stackable[:mount_path].first
end
stack.use Grape::Middleware::Formatter,
format: format,
default_format: inheritable_setting.namespace_inheritable[:default_format] || :txt,
content_types: content_types,
formatters: inheritable_setting.namespace_stackable_with_hash(:formatters),
parsers: inheritable_setting.namespace_stackable_with_hash(:parsers)
builder = stack.build
builder.run ->(env) { env[Grape::Env::API_ENDPOINT].run }
builder.to_app
end
def build_helpers
helpers = inheritable_setting.namespace_stackable[:helpers]
return if helpers.empty?
Module.new { helpers.each { |mod_to_include| include mod_to_include } }
end
def build_response_cookies
response_cookies do |name, value|
cookie_value = value.is_a?(Hash) ? value : { value: value }
Rack::Utils.set_cookie_header! header, name, cookie_value
end
end
def lint?
inheritable_setting.namespace_inheritable[:lint] || Grape.config.lint
end
def rescue_handlers
rescue_handlers = inheritable_setting.namespace_reverse_stackable[:rescue_handlers]
return if rescue_handlers.blank?
rescue_handlers.each_with_object({}) do |rescue_handler, result|
result.merge!(rescue_handler) { |_k, s1, _s2| s1 }
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/request.rb | lib/grape/request.rb | # frozen_string_literal: true
module Grape
class Request < Rack::Request
# Based on rack 3 KNOWN_HEADERS
# https://github.com/rack/rack/blob/4f15e7b814922af79605be4b02c5b7c3044ba206/lib/rack/headers.rb#L10
KNOWN_HEADERS = %w[
Accept
Accept-CH
Accept-Encoding
Accept-Language
Accept-Patch
Accept-Ranges
Accept-Version
Access-Control-Allow-Credentials
Access-Control-Allow-Headers
Access-Control-Allow-Methods
Access-Control-Allow-Origin
Access-Control-Expose-Headers
Access-Control-Max-Age
Age
Allow
Alt-Svc
Authorization
Cache-Control
Client-Ip
Connection
Content-Disposition
Content-Encoding
Content-Language
Content-Length
Content-Location
Content-MD5
Content-Range
Content-Security-Policy
Content-Security-Policy-Report-Only
Content-Type
Cookie
Date
Delta-Base
Dnt
ETag
Expect-CT
Expires
Feature-Policy
Forwarded
Host
If-Modified-Since
If-None-Match
IM
Last-Modified
Link
Location
NEL
P3P
Permissions-Policy
Pragma
Preference-Applied
Proxy-Authenticate
Public-Key-Pins
Range
Referer
Referrer-Policy
Refresh
Report-To
Retry-After
Sec-Fetch-Dest
Sec-Fetch-Mode
Sec-Fetch-Site
Sec-Fetch-User
Server
Set-Cookie
Status
Strict-Transport-Security
Timing-Allow-Origin
Tk
Trailer
Transfer-Encoding
Upgrade
Upgrade-Insecure-Requests
User-Agent
Vary
Version
Via
Warning
WWW-Authenticate
X-Accel-Buffering
X-Accel-Charset
X-Accel-Expires
X-Accel-Limit-Rate
X-Accel-Mapping
X-Accel-Redirect
X-Access-Token
X-Auth-Request-Access-Token
X-Auth-Request-Email
X-Auth-Request-Groups
X-Auth-Request-Preferred-Username
X-Auth-Request-Redirect
X-Auth-Request-Token
X-Auth-Request-User
X-Cascade
X-Client-Ip
X-Content-Duration
X-Content-Security-Policy
X-Content-Type-Options
X-Correlation-Id
X-Download-Options
X-Forwarded-Access-Token
X-Forwarded-Email
X-Forwarded-For
X-Forwarded-Groups
X-Forwarded-Host
X-Forwarded-Port
X-Forwarded-Preferred-Username
X-Forwarded-Proto
X-Forwarded-Scheme
X-Forwarded-Ssl
X-Forwarded-Uri
X-Forwarded-User
X-Frame-Options
X-HTTP-Method-Override
X-Permitted-Cross-Domain-Policies
X-Powered-By
X-Real-IP
X-Redirect-By
X-Request-Id
X-Requested-With
X-Runtime
X-Sendfile
X-Sendfile-Type
X-UA-Compatible
X-WebKit-CS
X-XSS-Protection
].each_with_object({}) do |header, response|
response["HTTP_#{header.upcase.tr('-', '_')}"] = header
end.freeze
alias rack_params params
alias rack_cookies cookies
def initialize(env, build_params_with: nil)
super(env)
@params_builder = Grape::ParamsBuilder.params_builder_for(build_params_with || Grape.config.param_builder)
end
def params
@params ||= make_params
end
def headers
@headers ||= build_headers
end
def cookies
@cookies ||= Grape::Cookies.new(-> { rack_cookies })
end
# needs to be public until extensions param_builder are removed
def grape_routing_args
# preserve version from query string parameters
env[Grape::Env::GRAPE_ROUTING_ARGS]&.except(:version, :route_info) || {}
end
private
def make_params
@params_builder.call(rack_params).deep_merge!(grape_routing_args)
rescue EOFError
raise Grape::Exceptions::EmptyMessageBody.new(content_type)
rescue Rack::Multipart::MultipartPartLimitError, Rack::Multipart::MultipartTotalPartLimitError
raise Grape::Exceptions::TooManyMultipartFiles.new(Rack::Utils.multipart_part_limit)
rescue Rack::QueryParser::ParamsTooDeepError
raise Grape::Exceptions::TooDeepParameters.new(Rack::Utils.param_depth_limit)
rescue Rack::Utils::ParameterTypeError
raise Grape::Exceptions::ConflictingTypes
rescue Rack::Utils::InvalidParameterError
raise Grape::Exceptions::InvalidParameters
end
def build_headers
each_header.with_object(Grape::Util::Header.new) do |(k, v), headers|
next unless k.start_with? 'HTTP_'
transformed_header = KNOWN_HEADERS.fetch(k) { -k[5..].tr('_', '-').downcase }
headers[transformed_header] = v
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/formatter.rb | lib/grape/formatter.rb | # frozen_string_literal: true
module Grape
module Formatter
extend Grape::Util::Registry
module_function
DEFAULT_LAMBDA_FORMATTER = ->(obj, _env) { obj }
def formatter_for(api_format, formatters)
return formatters[api_format] if formatters&.key?(api_format)
registry[api_format] || DEFAULT_LAMBDA_FORMATTER
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/registry.rb | lib/grape/util/registry.rb | # frozen_string_literal: true
module Grape
module Util
module Registry
def register(klass)
short_name = build_short_name(klass)
return if short_name.nil?
warn "#{short_name} is already registered with class #{registry[short_name]}. It will be overridden globally with the following: #{klass.name}" if registry.key?(short_name)
registry[short_name] = klass
end
private
def build_short_name(klass)
return if klass.name.blank?
klass.name.demodulize.underscore
end
def registry
@registry ||= {}.with_indifferent_access
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/base_inheritable.rb | lib/grape/util/base_inheritable.rb | # frozen_string_literal: true
module Grape
module Util
# Base for classes which need to operate with own values kept
# in the hash and inherited values kept in a Hash-like object.
class BaseInheritable
attr_accessor :inherited_values, :new_values
# @param inherited_values [Object] An object implementing an interface
# of the Hash class.
def initialize(inherited_values = nil)
@inherited_values = inherited_values || {}
@new_values = {}
end
def delete(*keys)
keys.map do |key|
# since delete returns the deleted value, seems natural to `map` the result
new_values.delete key
end
end
def initialize_copy(other)
super
self.inherited_values = other.inherited_values
self.new_values = other.new_values.dup
end
def keys
if new_values.any?
inherited_values.keys.tap do |combined|
combined.concat(new_values.keys)
combined.uniq!
end
else
inherited_values.keys
end
end
def key?(name)
inherited_values.key?(name) || new_values.key?(name)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/api_description.rb | lib/grape/util/api_description.rb | # frozen_string_literal: true
module Grape
module Util
class ApiDescription
DSL_METHODS = %i[
body_name
consumes
default
deprecated
detail
entity
headers
hidden
http_codes
is_array
named
nickname
params
produces
security
summary
tags
].freeze
def initialize(description, endpoint_configuration, &)
@endpoint_configuration = endpoint_configuration
@attributes = { description: description }
instance_eval(&)
end
DSL_METHODS.each do |attribute|
define_method attribute do |value|
@attributes[attribute] = value
end
end
alias success entity
alias failure http_codes
def configuration
@configuration ||= eval_endpoint_config(@endpoint_configuration)
end
def settings
@attributes
end
private
def eval_endpoint_config(configuration)
return configuration if configuration.is_a?(Hash)
configuration.evaluate
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/endpoint_configuration.rb | lib/grape/util/endpoint_configuration.rb | # frozen_string_literal: true
module Grape
module Util
class EndpointConfiguration < Lazy::ValueHash
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/reverse_stackable_values.rb | lib/grape/util/reverse_stackable_values.rb | # frozen_string_literal: true
module Grape
module Util
class ReverseStackableValues < StackableValues
protected
def concat_values(inherited_value, new_value)
return inherited_value unless new_value
new_value + inherited_value
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/media_type.rb | lib/grape/util/media_type.rb | # frozen_string_literal: true
module Grape
module Util
class MediaType
attr_reader :type, :subtype, :vendor, :version, :format
# based on the HTTP Accept header with the pattern:
# application/vnd.:vendor-:version+:format
VENDOR_VERSION_HEADER_REGEX = /\Avnd\.(?<vendor>[a-z0-9.\-_!^]+?)(?:-(?<version>[a-z0-9*.]+))?(?:\+(?<format>[a-z0-9*\-.]+))?\z/
def initialize(type:, subtype:)
@type = type
@subtype = subtype
VENDOR_VERSION_HEADER_REGEX.match(subtype) do |m|
@vendor = m[:vendor]
@version = m[:version]
@format = m[:format]
end
end
def ==(other)
eql?(other)
end
def eql?(other)
self.class == other.class &&
other.type == type &&
other.subtype == subtype &&
other.vendor == vendor &&
other.version == version &&
other.format == format
end
def hash
[self.class, type, subtype, vendor, version, format].hash
end
class << self
def best_quality(header, available_media_types)
parse(best_quality_media_type(header, available_media_types))
end
def parse(media_type)
return if media_type.blank?
type, subtype = media_type.split('/', 2)
return if type.blank? || subtype.blank?
new(type: type, subtype: subtype)
end
def match?(media_type)
return false if media_type.blank?
subtype = media_type.split('/', 2).last
return false if subtype.blank?
VENDOR_VERSION_HEADER_REGEX.match?(subtype)
end
def best_quality_media_type(header, available_media_types)
header.blank? ? available_media_types.first : Rack::Utils.best_q_match(header, available_media_types)
end
end
private_class_method :best_quality_media_type
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/inheritable_setting.rb | lib/grape/util/inheritable_setting.rb | # frozen_string_literal: true
module Grape
module Util
# A branchable, inheritable settings object which can store both stackable
# and inheritable values (see InheritableValues and StackableValues).
class InheritableSetting
attr_accessor :route, :api_class, :namespace, :namespace_inheritable, :namespace_stackable, :namespace_reverse_stackable, :parent, :point_in_time_copies
# Retrieve global settings.
def self.global
@global ||= {}
end
# Clear all global settings.
# @api private
# @note only for testing
def self.reset_global!
@global = {}
end
# Instantiate a new settings instance, with blank values. The fresh
# instance can then be set to inherit from an existing instance (see
# #inherit_from).
def initialize
self.route = {}
self.api_class = {}
self.namespace = InheritableValues.new # only inheritable from a parent when
# used with a mount, or should every API::Class be a separate namespace by default?
self.namespace_inheritable = InheritableValues.new
self.namespace_stackable = StackableValues.new
self.namespace_reverse_stackable = ReverseStackableValues.new
self.point_in_time_copies = []
self.parent = nil
end
# Return the class-level global properties.
def global
self.class.global
end
# Set our inherited values to the given parent's current values. Also,
# update the inherited values on any settings instances which were forked
# from us.
# @param parent [InheritableSetting]
def inherit_from(parent)
return if parent.nil?
self.parent = parent
namespace_inheritable.inherited_values = parent.namespace_inheritable
namespace_stackable.inherited_values = parent.namespace_stackable
namespace_reverse_stackable.inherited_values = parent.namespace_reverse_stackable
self.route = parent.route.merge(route)
point_in_time_copies.map { |cloned_one| cloned_one.inherit_from parent }
end
# Create a point-in-time copy of this settings instance, with clones of
# all our values. Note that, should this instance's parent be set or
# changed via #inherit_from, it will copy that inheritence to any copies
# which were made.
def point_in_time_copy
self.class.new.tap do |new_setting|
point_in_time_copies << new_setting
new_setting.point_in_time_copies = []
new_setting.namespace = namespace.clone
new_setting.namespace_inheritable = namespace_inheritable.clone
new_setting.namespace_stackable = namespace_stackable.clone
new_setting.namespace_reverse_stackable = namespace_reverse_stackable.clone
new_setting.route = route.clone
new_setting.api_class = api_class
new_setting.inherit_from(parent)
end
end
# Resets the instance store of per-route settings.
# @api private
def route_end
@route = {}
end
# Return a serializable hash of our values.
def to_hash
{
global: global.clone,
route: route.clone,
namespace: namespace.to_hash,
namespace_inheritable: namespace_inheritable.to_hash,
namespace_stackable: namespace_stackable.to_hash,
namespace_reverse_stackable: namespace_reverse_stackable.to_hash
}
end
def namespace_stackable_with_hash(key)
data = namespace_stackable[key]
return if data.blank?
data.each_with_object({}) { |value, result| result.deep_merge!(value) }
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/inheritable_values.rb | lib/grape/util/inheritable_values.rb | # frozen_string_literal: true
module Grape
module Util
class InheritableValues < BaseInheritable
def [](name)
values[name]
end
def []=(name, value)
new_values[name] = value
end
def merge(new_hash)
values.merge!(new_hash)
end
def to_hash
values
end
protected
def values
@inherited_values.merge(@new_values)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/stackable_values.rb | lib/grape/util/stackable_values.rb | # frozen_string_literal: true
module Grape
module Util
class StackableValues < BaseInheritable
# Even if there is no value, an empty array will be returned.
def [](name)
inherited_value = inherited_values[name]
new_value = new_values[name]
return new_value || [] unless inherited_value
concat_values(inherited_value, new_value)
end
def []=(name, value)
new_values[name] ||= []
new_values[name].push value
end
def to_hash
keys.each_with_object({}) do |key, result|
result[key] = self[key]
end
end
protected
def concat_values(inherited_value, new_value)
return inherited_value unless new_value
inherited_value + new_value
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/header.rb | lib/grape/util/header.rb | # frozen_string_literal: true
module Grape
module Util
if Gem::Version.new(Rack.release) >= Gem::Version.new('3')
require 'rack/headers'
Header = Rack::Headers
else
require 'rack/utils'
Header = Rack::Utils::HeaderHash
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/cache.rb | lib/grape/util/cache.rb | # frozen_string_literal: true
module Grape
module Util
class Cache
include Singleton
attr_reader :cache
class << self
extend Forwardable
def_delegators :cache, :[]
def_delegators :instance, :cache
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/lazy/value.rb | lib/grape/util/lazy/value.rb | # frozen_string_literal: true
module Grape
module Util
module Lazy
class Value
attr_reader :access_keys
def initialize(value, access_keys = [])
@value = value
@access_keys = access_keys
end
def evaluate_from(configuration)
matching_lazy_value = configuration.fetch(@access_keys)
matching_lazy_value.evaluate
end
def evaluate
@value
end
def lazy?
true
end
def reached_by(parent_access_keys, access_key)
@access_keys = parent_access_keys + [access_key]
self
end
def to_s
evaluate.to_s
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/lazy/value_enumerable.rb | lib/grape/util/lazy/value_enumerable.rb | # frozen_string_literal: true
module Grape
module Util
module Lazy
class ValueEnumerable < Value
def [](key)
if @value_hash[key].nil?
Value.new(nil).reached_by(access_keys, key)
else
@value_hash[key].reached_by(access_keys, key)
end
end
def fetch(access_keys)
fetched_keys = access_keys.dup
value = self[fetched_keys.shift]
fetched_keys.any? ? value.fetch(fetched_keys) : value
end
def []=(key, value)
@value_hash[key] = case value
when Hash
ValueHash.new(value)
when Array
ValueArray.new(value)
else
Value.new(value)
end
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/lazy/value_array.rb | lib/grape/util/lazy/value_array.rb | # frozen_string_literal: true
module Grape
module Util
module Lazy
class ValueArray < ValueEnumerable
def initialize(array)
super
@value_hash = []
array.each_with_index do |value, index|
self[index] = value
end
end
def evaluate
@value_hash.map(&:evaluate)
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/lazy/value_hash.rb | lib/grape/util/lazy/value_hash.rb | # frozen_string_literal: true
module Grape
module Util
module Lazy
class ValueHash < ValueEnumerable
def initialize(hash)
super
@value_hash = ActiveSupport::HashWithIndifferentAccess.new
hash.each do |key, value|
self[key] = value
end
end
def evaluate
@value_hash.transform_values(&:evaluate)
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/util/lazy/block.rb | lib/grape/util/lazy/block.rb | # frozen_string_literal: true
module Grape
module Util
module Lazy
class Block
def initialize(&new_block)
@block = new_block
end
def evaluate_from(configuration)
@block.call(configuration)
end
def evaluate
@block.call({})
end
def lazy?
true
end
def to_s
evaluate.to_s
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/params_builder/hash_with_indifferent_access.rb | lib/grape/params_builder/hash_with_indifferent_access.rb | # frozen_string_literal: true
module Grape
module ParamsBuilder
class HashWithIndifferentAccess < Base
def self.call(params)
params.with_indifferent_access
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/params_builder/base.rb | lib/grape/params_builder/base.rb | # frozen_string_literal: true
module Grape
module ParamsBuilder
class Base
class << self
def call(_params)
raise NotImplementedError
end
private
def inherited(klass)
super
ParamsBuilder.register(klass)
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/params_builder/hashie_mash.rb | lib/grape/params_builder/hashie_mash.rb | # frozen_string_literal: true
module Grape
module ParamsBuilder
class HashieMash < Base
def self.call(params)
::Hashie::Mash.new(params)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/params_builder/hash.rb | lib/grape/params_builder/hash.rb | # frozen_string_literal: true
module Grape
module ParamsBuilder
class Hash < Base
def self.call(params)
params.deep_symbolize_keys
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/serve_stream/file_body.rb | lib/grape/serve_stream/file_body.rb | # frozen_string_literal: true
module Grape
module ServeStream
CHUNK_SIZE = 16_384
# Class helps send file through API
class FileBody
attr_reader :path
# @param path [String]
def initialize(path)
@path = path
end
# Need for Rack::Sendfile middleware
#
# @return [String]
def to_path
path
end
def each
File.open(path, 'rb') do |file|
while (chunk = file.read(CHUNK_SIZE))
yield chunk
end
end
end
def ==(other)
path == other.path
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/serve_stream/sendfile_response.rb | lib/grape/serve_stream/sendfile_response.rb | # frozen_string_literal: true
module Grape
module ServeStream
# Response should respond to to_path method
# for using Rack::SendFile middleware
class SendfileResponse < Rack::Response
def respond_to?(method_name, include_all = false)
if method_name == :to_path
@body.respond_to?(:to_path, include_all)
else
super
end
end
def to_path
@body.to_path
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/serve_stream/stream_response.rb | lib/grape/serve_stream/stream_response.rb | # frozen_string_literal: true
module Grape
module ServeStream
# A simple class used to identify responses which represent streams (or files) and do not
# need to be formatted or pre-read by Rack::Response
class StreamResponse
attr_reader :stream
# @param stream [Object]
def initialize(stream)
@stream = stream
end
# Equality provided mostly for tests.
#
# @return [Boolean]
def ==(other)
stream == other.stream
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/presenters/presenter.rb | lib/grape/presenters/presenter.rb | # frozen_string_literal: true
module Grape
module Presenters
class Presenter
def self.represent(object, **_options)
object
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/unknown_parameter.rb | lib/grape/exceptions/unknown_parameter.rb | # frozen_string_literal: true
module Grape
module Exceptions
class UnknownParameter < Base
def initialize(param)
super(message: compose_message(:unknown_parameter, param: param))
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/empty_message_body.rb | lib/grape/exceptions/empty_message_body.rb | # frozen_string_literal: true
module Grape
module Exceptions
class EmptyMessageBody < Base
def initialize(body_format)
super(message: compose_message(:empty_message_body, body_format: body_format), status: 400)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/invalid_formatter.rb | lib/grape/exceptions/invalid_formatter.rb | # frozen_string_literal: true
module Grape
module Exceptions
class InvalidFormatter < Base
def initialize(klass, to_format)
super(message: compose_message(:invalid_formatter, klass: klass, to_format: to_format))
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/validation_errors.rb | lib/grape/exceptions/validation_errors.rb | # frozen_string_literal: true
module Grape
module Exceptions
class ValidationErrors < Base
ERRORS_FORMAT_KEY = 'grape.errors.format'
DEFAULT_ERRORS_FORMAT = '%<attributes>s %<message>s'
include Enumerable
attr_reader :errors
def initialize(errors: [], headers: {})
@errors = errors.group_by(&:params)
super(message: full_messages.join(', '), status: 400, headers: headers)
end
def each
errors.each_pair do |attribute, errors|
errors.each do |error|
yield attribute, error
end
end
end
def as_json(**_opts)
errors.map do |k, v|
{
params: k,
messages: v.map(&:to_s)
}
end
end
def to_json(*_opts)
as_json.to_json
end
def full_messages
messages = map do |attributes, error|
I18n.t(
ERRORS_FORMAT_KEY,
default: DEFAULT_ERRORS_FORMAT,
attributes: translate_attributes(attributes),
message: error.message
)
end
messages.uniq!
messages
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/unknown_params_builder.rb | lib/grape/exceptions/unknown_params_builder.rb | # frozen_string_literal: true
module Grape
module Exceptions
class UnknownParamsBuilder < Base
def initialize(params_builder_type)
super(message: compose_message(:unknown_params_builder, params_builder_type: params_builder_type))
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/missing_vendor_option.rb | lib/grape/exceptions/missing_vendor_option.rb | # frozen_string_literal: true
module Grape
module Exceptions
class MissingVendorOption < Base
def initialize
super(message: compose_message(:missing_vendor_option))
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/invalid_message_body.rb | lib/grape/exceptions/invalid_message_body.rb | # frozen_string_literal: true
module Grape
module Exceptions
class InvalidMessageBody < Base
def initialize(body_format)
super(message: compose_message(:invalid_message_body, body_format: body_format), status: 400)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/conflicting_types.rb | lib/grape/exceptions/conflicting_types.rb | # frozen_string_literal: true
module Grape
module Exceptions
class ConflictingTypes < Base
def initialize
super(message: compose_message(:conflicting_types), status: 400)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/missing_group_type.rb | lib/grape/exceptions/missing_group_type.rb | # frozen_string_literal: true
module Grape
module Exceptions
class MissingGroupType < Base
def initialize
super(message: compose_message(:missing_group_type))
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/invalid_with_option_for_represent.rb | lib/grape/exceptions/invalid_with_option_for_represent.rb | # frozen_string_literal: true
module Grape
module Exceptions
class InvalidWithOptionForRepresent < Base
def initialize
super(message: compose_message(:invalid_with_option_for_represent))
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/unknown_validator.rb | lib/grape/exceptions/unknown_validator.rb | # frozen_string_literal: true
module Grape
module Exceptions
class UnknownValidator < Base
def initialize(validator_type)
super(message: compose_message(:unknown_validator, validator_type: validator_type))
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/invalid_response.rb | lib/grape/exceptions/invalid_response.rb | # frozen_string_literal: true
module Grape
module Exceptions
class InvalidResponse < Base
def initialize
super(message: compose_message(:invalid_response))
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/too_deep_parameters.rb | lib/grape/exceptions/too_deep_parameters.rb | # frozen_string_literal: true
module Grape
module Exceptions
class TooDeepParameters < Base
def initialize(limit)
super(message: compose_message(:too_deep_parameters, limit: limit), status: 400)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/invalid_versioner_option.rb | lib/grape/exceptions/invalid_versioner_option.rb | # frozen_string_literal: true
module Grape
module Exceptions
class InvalidVersionerOption < Base
def initialize(strategy)
super(message: compose_message(:invalid_versioner_option, strategy: strategy))
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/unknown_auth_strategy.rb | lib/grape/exceptions/unknown_auth_strategy.rb | # frozen_string_literal: true
module Grape
module Exceptions
class UnknownAuthStrategy < Base
def initialize(strategy:)
super(message: compose_message(:unknown_auth_strategy, strategy: strategy))
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/invalid_version_header.rb | lib/grape/exceptions/invalid_version_header.rb | # frozen_string_literal: true
module Grape
module Exceptions
class InvalidVersionHeader < Base
def initialize(message, headers)
super(message: compose_message(:invalid_version_header, message: message), status: 406, headers: headers)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/too_many_multipart_files.rb | lib/grape/exceptions/too_many_multipart_files.rb | # frozen_string_literal: true
module Grape
module Exceptions
class TooManyMultipartFiles < Base
def initialize(limit)
super(message: compose_message(:too_many_multipart_files, limit: limit), status: 413)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/unsupported_group_type.rb | lib/grape/exceptions/unsupported_group_type.rb | # frozen_string_literal: true
module Grape
module Exceptions
class UnsupportedGroupType < Base
def initialize
super(message: compose_message(:unsupported_group_type))
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/invalid_parameters.rb | lib/grape/exceptions/invalid_parameters.rb | # frozen_string_literal: true
module Grape
module Exceptions
class InvalidParameters < Base
def initialize
super(message: compose_message(:invalid_parameters), status: 400)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/invalid_accept_header.rb | lib/grape/exceptions/invalid_accept_header.rb | # frozen_string_literal: true
module Grape
module Exceptions
class InvalidAcceptHeader < Base
def initialize(message, headers)
super(message: compose_message(:invalid_accept_header, message: message), status: 406, headers: headers)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/base.rb | lib/grape/exceptions/base.rb | # frozen_string_literal: true
module Grape
module Exceptions
class Base < StandardError
BASE_MESSAGES_KEY = 'grape.errors.messages'
BASE_ATTRIBUTES_KEY = 'grape.errors.attributes'
FALLBACK_LOCALE = :en
attr_reader :status, :headers
def initialize(status: nil, message: nil, headers: nil)
super(message)
@status = status
@headers = headers
end
def [](index)
__send__ index
end
protected
# TODO: translate attribute first
# if BASE_ATTRIBUTES_KEY.key respond to a string message, then short_message is returned
# if BASE_ATTRIBUTES_KEY.key respond to a Hash, means it may have problem , summary and resolution
def compose_message(key, **attributes)
short_message = translate_message(key, attributes)
return short_message unless short_message.is_a?(Hash)
each_steps(key, attributes).with_object(+'') do |detail_array, message|
message << "\n#{detail_array[0]}:\n #{detail_array[1]}" unless detail_array[1].blank?
end
end
def each_steps(key, attributes)
return enum_for(:each_steps, key, attributes) unless block_given?
yield 'Problem', translate_message(:"#{key}.problem", attributes)
yield 'Summary', translate_message(:"#{key}.summary", attributes)
yield 'Resolution', translate_message(:"#{key}.resolution", attributes)
end
def translate_attributes(keys, options = {})
keys.map do |key|
translate("#{BASE_ATTRIBUTES_KEY}.#{key}", options.merge(default: key.to_s))
end.join(', ')
end
def translate_message(key, options = {})
case key
when Symbol
translate("#{BASE_MESSAGES_KEY}.#{key}", options.merge(default: ''))
when Proc
key.call
else
key
end
end
def translate(key, options)
message = ::I18n.translate(key, **options)
message.presence || fallback_message(key, options)
end
def fallback_message(key, options)
if ::I18n.enforce_available_locales && !::I18n.available_locales.include?(FALLBACK_LOCALE)
key
else
::I18n.translate(key, locale: FALLBACK_LOCALE, **options)
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/method_not_allowed.rb | lib/grape/exceptions/method_not_allowed.rb | # frozen_string_literal: true
module Grape
module Exceptions
class MethodNotAllowed < Base
def initialize(headers)
super(message: '405 Not Allowed', status: 405, headers: headers)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/incompatible_option_values.rb | lib/grape/exceptions/incompatible_option_values.rb | # frozen_string_literal: true
module Grape
module Exceptions
class IncompatibleOptionValues < Base
def initialize(option1, value1, option2, value2)
super(message: compose_message(:incompatible_option_values, option1: option1, value1: value1, option2: option2, value2: value2))
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/missing_mime_type.rb | lib/grape/exceptions/missing_mime_type.rb | # frozen_string_literal: true
module Grape
module Exceptions
class MissingMimeType < Base
def initialize(new_format)
super(message: compose_message(:missing_mime_type, new_format: new_format))
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/validation.rb | lib/grape/exceptions/validation.rb | # frozen_string_literal: true
module Grape
module Exceptions
class Validation < Base
attr_accessor :params, :message_key
def initialize(params:, message: nil, status: nil, headers: nil)
@params = params
if message
@message_key = message if message.is_a?(Symbol)
message = translate_message(message)
end
super(status: status, message: message, headers: headers)
end
# Remove all the unnecessary stuff from Grape::Exceptions::Base like status
# and headers when converting a validation error to json or string
def as_json(*_args)
to_s
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/exceptions/validation_array_errors.rb | lib/grape/exceptions/validation_array_errors.rb | # frozen_string_literal: true
module Grape
module Exceptions
class ValidationArrayErrors < Base
attr_reader :errors
def initialize(errors)
super()
@errors = errors
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/globals.rb | lib/grape/middleware/globals.rb | # frozen_string_literal: true
module Grape
module Middleware
class Globals < Base
def before
request = Grape::Request.new(@env, build_params_with: @options[:build_params_with])
@env[Grape::Env::GRAPE_REQUEST] = request
@env[Grape::Env::GRAPE_REQUEST_HEADERS] = request.headers
@env[Grape::Env::GRAPE_REQUEST_PARAMS] = request.params if @env[Rack::RACK_INPUT]
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/filter.rb | lib/grape/middleware/filter.rb | # frozen_string_literal: true
module Grape
module Middleware
# This is a simple middleware for adding before and after filters
# to Grape APIs. It is used like so:
#
# use Grape::Middleware::Filter, before: -> { do_something }, after: -> { do_something }
class Filter < Base
def before
app.instance_eval(&options[:before]) if options[:before]
end
def after
app.instance_eval(&options[:after]) if options[:after]
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/stack.rb | lib/grape/middleware/stack.rb | # frozen_string_literal: true
module Grape
module Middleware
# Class to handle the stack of middlewares based on ActionDispatch::MiddlewareStack
# It allows to insert and insert after
class Stack
extend Forwardable
class Middleware
attr_reader :args, :block, :klass
def initialize(klass, args, block)
@klass = klass
@args = args
@block = block
end
def name
klass.name
end
def ==(other)
case other
when Middleware
klass == other.klass
when Class
klass == other || (name.nil? && klass.superclass == other)
end
end
def inspect
klass.to_s
end
def build(builder)
# we need to force the ruby2_keywords_hash for middlewares that initialize contains keywords
# like ActionDispatch::RequestId since middleware arguments are serialized
# https://rubyapi.org/3.4/o/hash#method-c-ruby2_keywords_hash
args[-1] = Hash.ruby2_keywords_hash(args[-1]) if args.last.is_a?(Hash) && Hash.respond_to?(:ruby2_keywords_hash)
builder.use(klass, *args, &block)
end
end
include Enumerable
attr_accessor :middlewares, :others
def_delegators :middlewares, :each, :size, :last, :[]
def initialize
@middlewares = []
@others = []
end
def insert(index, klass, *args, &block)
index = assert_index(index, :before)
middlewares.insert(index, self.class::Middleware.new(klass, args, block))
end
alias insert_before insert
def insert_after(index, ...)
index = assert_index(index, :after)
insert(index + 1, ...)
end
def use(klass, *args, &block)
middleware = self.class::Middleware.new(klass, args, block)
middlewares.push(middleware)
end
def merge_with(middleware_specs)
middleware_specs.each do |operation, klass, *args|
if args.last.is_a?(Proc)
last_proc = args.pop
public_send(operation, klass, *args, &last_proc)
else
public_send(operation, klass, *args)
end
end
end
# @return [Rack::Builder] the builder object with our middlewares applied
def build
Rack::Builder.new.tap do |builder|
others.shift(others.size).each { |m| merge_with(m) }
middlewares.each do |m|
m.build(builder)
end
end
end
# @description Add middlewares with :use operation to the stack. Store others with :insert_* operation for later
# @param [Array] other_specs An array of middleware specifications (e.g. [[:use, klass], [:insert_before, *args]])
def concat(other_specs)
use, not_use = other_specs.partition { |o| o.first == :use }
others << not_use
merge_with(use)
end
protected
def assert_index(index, where)
i = index.is_a?(Integer) ? index : middlewares.index(index)
i || raise("No such middleware to insert #{where}: #{index.inspect}")
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/base.rb | lib/grape/middleware/base.rb | # frozen_string_literal: true
module Grape
module Middleware
class Base
include Grape::DSL::Headers
attr_reader :app, :env, :options
# @param [Rack Application] app The standard argument for a Rack middleware.
# @param [Hash] options A hash of options, simply stored for use by subclasses.
def initialize(app, **options)
@app = app
@options = merge_default_options(options)
@app_response = nil
end
def call(env)
dup.call!(env).to_a
end
def call!(env)
@env = env
before
begin
@app_response = @app.call(@env)
ensure
begin
after_response = after
rescue StandardError => e
warn "caught error of type #{e.class} in after callback inside #{self.class.name} : #{e.message}"
raise e
end
end
response = after_response || @app_response
merge_headers response
response
end
# @abstract
# Called before the application is called in the middleware lifecycle.
def before; end
# @abstract
# Called after the application is called in the middleware lifecycle.
# @return [Response, nil] a Rack SPEC response or nil to call the application afterwards.
def after; end
def rack_request
@rack_request ||= Rack::Request.new(env)
end
def context
env[Grape::Env::API_ENDPOINT]
end
def response
return @app_response if @app_response.is_a?(Rack::Response)
@app_response = Rack::Response[*@app_response]
end
def content_types
@content_types ||= Grape::ContentTypes.content_types_for(options[:content_types])
end
def mime_types
@mime_types ||= Grape::ContentTypes.mime_types_for(content_types)
end
def content_type_for(format)
content_types_indifferent_access[format]
end
def content_type
content_type_for(env[Grape::Env::API_FORMAT] || options[:format]) || 'text/html'
end
def query_params
rack_request.GET
rescue Rack::QueryParser::ParamsTooDeepError
raise Grape::Exceptions::TooDeepParameters.new(Rack::Utils.param_depth_limit)
rescue Rack::Utils::ParameterTypeError
raise Grape::Exceptions::ConflictingTypes
end
private
def merge_headers(response)
return unless headers.is_a?(Hash)
case response
when Rack::Response then response.headers.merge!(headers)
when Array then response[1].merge!(headers)
end
end
def content_types_indifferent_access
@content_types_indifferent_access ||= content_types.with_indifferent_access
end
def merge_default_options(options)
if respond_to?(:default_options)
default_options.deep_merge(options)
elsif self.class.const_defined?(:DEFAULT_OPTIONS)
self.class::DEFAULT_OPTIONS.deep_merge(options)
else
options
end
end
def try_scrub(obj)
obj.respond_to?(:valid_encoding?) && !obj.valid_encoding? ? obj.scrub : obj
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/versioner.rb | lib/grape/middleware/versioner.rb | # frozen_string_literal: true
# Versioners set env['api.version'] when a version is defined on an API and
# on the requests. The current methods for determining version are:
#
# :header - version from HTTP Accept header.
# :accept_version_header - version from HTTP Accept-Version header
# :path - version from uri. e.g. /v1/resource
# :param - version from uri query string, e.g. /v1/resource?apiver=v1
# See individual classes for details.
module Grape
module Middleware
module Versioner
extend Grape::Util::Registry
module_function
# @param strategy [Symbol] :path, :header, :accept_version_header or :param
# @return a middleware class based on strategy
def using(strategy)
raise Grape::Exceptions::InvalidVersionerOption, strategy unless registry.key?(strategy)
registry[strategy]
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/formatter.rb | lib/grape/middleware/formatter.rb | # frozen_string_literal: true
module Grape
module Middleware
class Formatter < Base
DEFAULT_OPTIONS = {
default_format: :txt
}.freeze
ALL_MEDIA_TYPES = '*/*'
def before
negotiate_content_type
read_body_input
end
def after
return unless @app_response
status, headers, bodies = *@app_response
if Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include?(status)
[status, headers, []]
else
build_formatted_response(status, headers, bodies)
end
end
private
def build_formatted_response(status, headers, bodies)
headers = ensure_content_type(headers)
if bodies.is_a?(Grape::ServeStream::StreamResponse)
Grape::ServeStream::SendfileResponse.new([], status, headers) do |resp|
resp.body = bodies.stream
end
else
# Allow content-type to be explicitly overwritten
formatter = fetch_formatter(headers, options)
bodymap = ActiveSupport::Notifications.instrument('format_response.grape', formatter: formatter, env: env) do
bodies.collect { |body| formatter.call(body, env) }
end
Rack::Response.new(bodymap, status, headers)
end
rescue Grape::Exceptions::InvalidFormatter => e
throw :error, status: 500, message: e.message, backtrace: e.backtrace, original_exception: e
end
def fetch_formatter(headers, options)
api_format = env.fetch(Grape::Env::API_FORMAT) { mime_types[headers[Rack::CONTENT_TYPE]] }
Grape::Formatter.formatter_for(api_format, options[:formatters])
end
# Set the content type header for the API format if it is not already present.
#
# @param headers [Hash]
# @return [Hash]
def ensure_content_type(headers)
if headers[Rack::CONTENT_TYPE]
headers
else
headers.merge(Rack::CONTENT_TYPE => content_type_for(env[Grape::Env::API_FORMAT]))
end
end
def read_body_input
input = rack_request.body # reads RACK_INPUT
return if input.nil?
return unless read_body_input?
rewind = input.respond_to?(:rewind)
input.rewind if rewind
body = env[Grape::Env::API_REQUEST_INPUT] = input.read
begin
read_rack_input(body)
ensure
input.rewind if rewind
end
end
def read_rack_input(body)
return if body.empty?
media_type = rack_request.media_type
fmt = media_type ? mime_types[media_type] : options[:default_format]
throw :error, status: 415, message: "The provided content-type '#{media_type}' is not supported." unless content_type_for(fmt)
parser = Grape::Parser.parser_for fmt, options[:parsers]
if parser
begin
body = (env[Grape::Env::API_REQUEST_BODY] = parser.call(body, env))
if body.is_a?(Hash)
env[Rack::RACK_REQUEST_FORM_HASH] = if env.key?(Rack::RACK_REQUEST_FORM_HASH)
env[Rack::RACK_REQUEST_FORM_HASH].merge(body)
else
body
end
env[Rack::RACK_REQUEST_FORM_INPUT] = env[Rack::RACK_INPUT]
end
rescue Grape::Exceptions::Base => e
raise e
rescue StandardError => e
throw :error, status: 400, message: e.message, backtrace: e.backtrace, original_exception: e
end
else
env[Grape::Env::API_REQUEST_BODY] = body
end
end
# this middleware will not try to format the following content-types since Rack already handles them
# when calling Rack's `params` function
# - application/x-www-form-urlencoded
# - multipart/form-data
# - multipart/related
# - multipart/mixed
def read_body_input?
(rack_request.post? || rack_request.put? || rack_request.patch? || rack_request.delete?) &&
!(rack_request.form_data? && rack_request.content_type) &&
!rack_request.parseable_data? &&
(rack_request.content_length.to_i.positive? || rack_request.env['HTTP_TRANSFER_ENCODING'] == 'chunked')
end
def negotiate_content_type
fmt = format_from_extension || query_params['format'] || options[:format] || format_from_header || options[:default_format]
if content_type_for(fmt)
env[Grape::Env::API_FORMAT] = fmt.to_sym
else
throw :error, status: 406, message: "The requested format '#{fmt}' is not supported."
end
end
def format_from_extension
request_path = try_scrub(rack_request.path)
dot_pos = request_path.rindex('.')
return unless dot_pos
extension = request_path[(dot_pos + 1)..]
extension if content_type_for(extension)
end
def format_from_header
accept_header = try_scrub(env['HTTP_ACCEPT'])
return if accept_header.blank? || accept_header == ALL_MEDIA_TYPES
media_type = Rack::Utils.best_q_match(accept_header, mime_types.keys)
mime_types[media_type] if media_type
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/error.rb | lib/grape/middleware/error.rb | # frozen_string_literal: true
module Grape
module Middleware
class Error < Base
DEFAULT_OPTIONS = {
default_status: 500,
default_message: '',
format: :txt,
rescue_all: false,
rescue_grape_exceptions: false,
rescue_subclasses: true,
rescue_options: {
backtrace: false,
original_exception: false
}.freeze
}.freeze
def call!(env)
@env = env
error_response(catch(:error) { return @app.call(@env) })
rescue Exception => e # rubocop:disable Lint/RescueException
run_rescue_handler(find_handler(e.class), e, @env[Grape::Env::API_ENDPOINT])
end
private
def rack_response(status, headers, message)
message = Rack::Utils.escape_html(message) if headers[Rack::CONTENT_TYPE] == 'text/html'
Rack::Response.new(Array.wrap(message), Rack::Utils.status_code(status), Grape::Util::Header.new.merge(headers))
end
def format_message(message, backtrace, original_exception = nil)
format = env[Grape::Env::API_FORMAT] || options[:format]
formatter = Grape::ErrorFormatter.formatter_for(format, options[:error_formatters], options[:default_error_formatter])
return formatter.call(message, backtrace, options, env, original_exception) if formatter
throw :error,
status: 406,
message: "The requested format '#{format}' is not supported.",
backtrace: backtrace,
original_exception: original_exception
end
def find_handler(klass)
rescue_handler_for_base_only_class(klass) ||
rescue_handler_for_class_or_its_ancestor(klass) ||
rescue_handler_for_grape_exception(klass) ||
rescue_handler_for_any_class(klass) ||
raise
end
def error_response(error = {})
status = error[:status] || options[:default_status]
env[Grape::Env::API_ENDPOINT].status(status) # error! may not have been called
message = error[:message] || options[:default_message]
headers = { Rack::CONTENT_TYPE => content_type }.tap do |h|
h.merge!(error[:headers]) if error[:headers].is_a?(Hash)
end
backtrace = error[:backtrace] || error[:original_exception]&.backtrace || []
original_exception = error.is_a?(Exception) ? error : error[:original_exception]
rack_response(status, headers, format_message(message, backtrace, original_exception))
end
def default_rescue_handler(exception)
error_response(message: exception.message, backtrace: exception.backtrace, original_exception: exception)
end
def rescue_handler_for_base_only_class(klass)
error, handler = options[:base_only_rescue_handlers]&.find { |err, _handler| klass == err }
return unless error
handler || method(:default_rescue_handler)
end
def rescue_handler_for_class_or_its_ancestor(klass)
error, handler = options[:rescue_handlers]&.find { |err, _handler| klass <= err }
return unless error
handler || method(:default_rescue_handler)
end
def rescue_handler_for_grape_exception(klass)
return unless klass <= Grape::Exceptions::Base
return method(:error_response) if klass == Grape::Exceptions::InvalidVersionHeader
return unless options[:rescue_grape_exceptions] || !options[:rescue_all]
options[:grape_exceptions_rescue_handler] || method(:error_response)
end
def rescue_handler_for_any_class(klass)
return unless klass <= StandardError
return unless options[:rescue_all] || options[:rescue_grape_exceptions]
options[:all_rescue_handler] || method(:default_rescue_handler)
end
def run_rescue_handler(handler, error, endpoint)
handler = endpoint.public_method(handler) if handler.instance_of?(Symbol)
response = catch(:error) do
handler.arity.zero? ? endpoint.instance_exec(&handler) : endpoint.instance_exec(error, &handler)
end
if error?(response)
error_response(response)
elsif response.is_a?(Rack::Response)
response
else
run_rescue_handler(method(:default_rescue_handler), Grape::Exceptions::InvalidResponse.new, endpoint)
end
end
def error!(message, status = options[:default_status], headers = {}, backtrace = [], original_exception = nil)
env[Grape::Env::API_ENDPOINT].status(status) # not error! inside route
rack_response(
status, headers.reverse_merge(Rack::CONTENT_TYPE => content_type),
format_message(message, backtrace, original_exception)
)
end
def error?(response)
return false unless response.is_a?(Hash)
response.key?(:message) && response.key?(:status) && response.key?(:headers)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/auth/strategies.rb | lib/grape/middleware/auth/strategies.rb | # frozen_string_literal: true
module Grape
module Middleware
module Auth
module Strategies
module_function
def add(label, strategy, option_fetcher = ->(_) { [] })
auth_strategies[label] = StrategyInfo.new(strategy, option_fetcher)
end
def auth_strategies
@auth_strategies ||= {
http_basic: StrategyInfo.new(Rack::Auth::Basic, ->(settings) { [settings[:realm]] })
}
end
def [](label)
auth_strategies[label]
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/auth/strategy_info.rb | lib/grape/middleware/auth/strategy_info.rb | # frozen_string_literal: true
module Grape
module Middleware
module Auth
StrategyInfo = Struct.new(:auth_class, :settings_fetcher) do
def create(app, options, &block)
strategy_args = settings_fetcher.call(options)
auth_class.new(app, *strategy_args, &block)
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/auth/dsl.rb | lib/grape/middleware/auth/dsl.rb | # frozen_string_literal: true
module Grape
module Middleware
module Auth
module DSL
def auth(type = nil, options = {}, &block)
namespace_inheritable = inheritable_setting.namespace_inheritable
return namespace_inheritable[:auth] unless type
namespace_inheritable[:auth] = options.reverse_merge(type: type.to_sym, proc: block)
use Grape::Middleware::Auth::Base, namespace_inheritable[:auth]
end
# Add HTTP Basic authorization to the API.
#
# @param [Hash] options A hash of options.
# @option options [String] :realm "API Authorization" The HTTP Basic realm.
def http_basic(options = {}, &)
options[:realm] ||= 'API Authorization'
auth(:http_basic, options, &)
end
def http_digest(options = {}, &)
options[:realm] ||= 'API Authorization'
if options[:realm].respond_to?(:values_at)
options[:realm][:opaque] ||= 'secret'
else
options[:opaque] ||= 'secret'
end
auth(:http_digest, options, &)
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/auth/base.rb | lib/grape/middleware/auth/base.rb | # frozen_string_literal: true
module Grape
module Middleware
module Auth
class Base < Grape::Middleware::Base
def initialize(app, **options)
super
@auth_strategy = Grape::Middleware::Auth::Strategies[options[:type]].tap do |auth_strategy|
raise Grape::Exceptions::UnknownAuthStrategy.new(strategy: options[:type]) unless auth_strategy
end
end
def call!(env)
@env = env
@auth_strategy.create(app, options) do |*args|
context.instance_exec(*args, &options[:proc])
end.call(env)
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/versioner/path.rb | lib/grape/middleware/versioner/path.rb | # frozen_string_literal: true
module Grape
module Middleware
module Versioner
# This middleware sets various version related rack environment variables
# based on the uri path and removes the version substring from the uri
# path. If the version substring does not match any potential initialized
# versions, a 404 error is thrown.
#
# Example: For a uri path
# /v1/resource
#
# The following rack env variables are set and path is rewritten to
# '/resource':
#
# env['api.version'] => 'v1'
#
class Path < Base
def before
path_info = Grape::Router.normalize_path(env[Rack::PATH_INFO])
return if path_info == '/'
[mount_path, Grape::Router.normalize_path(prefix)].each do |path|
path_info = path_info.delete_prefix(path) if path.present? && path != '/' && path_info.start_with?(path)
end
slash_position = path_info.index('/', 1) # omit the first one
return unless slash_position
potential_version = path_info[1..(slash_position - 1)]
return unless potential_version.match?(pattern)
version_not_found! unless potential_version_match?(potential_version)
env[Grape::Env::API_VERSION] = potential_version
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/versioner/param.rb | lib/grape/middleware/versioner/param.rb | # frozen_string_literal: true
module Grape
module Middleware
module Versioner
# This middleware sets various version related rack environment variables
# based on the request parameters and removes that parameter from the
# request parameters for subsequent middleware and API.
# If the version substring does not match any potential initialized
# versions, a 404 error is thrown.
# If the version substring is not passed the version (highest mounted)
# version will be used.
#
# Example: For a uri path
# /resource?apiver=v1
#
# The following rack env variables are set and path is rewritten to
# '/resource':
#
# env['api.version'] => 'v1'
class Param < Base
def before
potential_version = query_params[parameter]
return if potential_version.blank?
version_not_found! unless potential_version_match?(potential_version)
env[Grape::Env::API_VERSION] = env[Rack::RACK_REQUEST_QUERY_HASH].delete(parameter)
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/versioner/accept_version_header.rb | lib/grape/middleware/versioner/accept_version_header.rb | # frozen_string_literal: true
module Grape
module Middleware
module Versioner
# This middleware sets various version related rack environment variables
# based on the HTTP Accept-Version header
#
# Example: For request header
# Accept-Version: v1
#
# The following rack env variables are set:
#
# env['api.version'] => 'v1'
#
# If version does not match this route, then a 406 is raised with
# X-Cascade header to alert Grape::Router to attempt the next matched
# route.
class AcceptVersionHeader < Base
def before
potential_version = try_scrub(env['HTTP_ACCEPT_VERSION'])
not_acceptable!('Accept-Version header must be set.') if strict && potential_version.blank?
return if potential_version.blank?
not_acceptable!('The requested version is not supported.') unless potential_version_match?(potential_version)
env[Grape::Env::API_VERSION] = potential_version
end
private
def not_acceptable!(message)
throw :error, status: 406, headers: error_headers, message: message
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/versioner/base.rb | lib/grape/middleware/versioner/base.rb | # frozen_string_literal: true
module Grape
module Middleware
module Versioner
class Base < Grape::Middleware::Base
DEFAULT_OPTIONS = {
pattern: /.*/i,
prefix: nil,
mount_path: nil,
version_options: {
strict: false,
cascade: true,
parameter: 'apiver',
vendor: nil
}.freeze
}.freeze
CASCADE_PASS_HEADER = { 'X-Cascade' => 'pass' }.freeze
DEFAULT_OPTIONS.each_key do |key|
define_method key do
options[key]
end
end
DEFAULT_OPTIONS[:version_options].each_key do |key|
define_method key do
options[:version_options][key]
end
end
def self.inherited(klass)
super
Versioner.register(klass)
end
attr_reader :error_headers, :versions
def initialize(app, **options)
super
@error_headers = cascade ? CASCADE_PASS_HEADER : {}
@versions = options[:versions]&.map(&:to_s) # making sure versions are strings to ease potential match
end
def potential_version_match?(potential_version)
versions.blank? || versions.include?(potential_version)
end
def version_not_found!
throw :error, status: 404, message: '404 API Version Not Found', headers: CASCADE_PASS_HEADER
end
private
def available_media_types
@available_media_types ||= begin
media_types = []
base_media_type = "application/vnd.#{vendor}"
content_types.each_key do |extension|
versions&.reverse_each do |version|
media_types << "#{base_media_type}-#{version}+#{extension}"
media_types << "#{base_media_type}-#{version}"
end
media_types << "#{base_media_type}+#{extension}"
end
media_types << base_media_type
media_types.concat(content_types.values.flatten)
media_types
end
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/middleware/versioner/header.rb | lib/grape/middleware/versioner/header.rb | # frozen_string_literal: true
module Grape
module Middleware
module Versioner
# This middleware sets various version related rack environment variables
# based on the HTTP Accept header with the pattern:
# application/vnd.:vendor-:version+:format
#
# Example: For request header
# Accept: application/vnd.mycompany.a-cool-resource-v1+json
#
# The following rack env variables are set:
#
# env['api.type'] => 'application'
# env['api.subtype'] => 'vnd.mycompany.a-cool-resource-v1+json'
# env['api.vendor] => 'mycompany.a-cool-resource'
# env['api.version] => 'v1'
# env['api.format] => 'json'
#
# If version does not match this route, then a 406 is raised with
# X-Cascade header to alert Grape::Router to attempt the next matched
# route.
class Header < Base
def before
match_best_quality_media_type! do |media_type|
env.update(
Grape::Env::API_TYPE => media_type.type,
Grape::Env::API_SUBTYPE => media_type.subtype,
Grape::Env::API_VENDOR => media_type.vendor,
Grape::Env::API_VERSION => media_type.version,
Grape::Env::API_FORMAT => media_type.format
)
end
end
private
def match_best_quality_media_type!
return unless vendor
strict_header_checks!
media_type = Grape::Util::MediaType.best_quality(accept_header, available_media_types)
if media_type
yield media_type
else
fail!
end
end
def accept_header
env['HTTP_ACCEPT']
end
def strict_header_checks!
return unless strict
accept_header_check!
version_and_vendor_check!
end
def accept_header_check!
return if accept_header.present?
invalid_accept_header!('Accept header must be set.')
end
def version_and_vendor_check!
return if versions.blank? || version_and_vendor?
invalid_accept_header!('API vendor or version not found.')
end
def q_values_mime_types
@q_values_mime_types ||= Rack::Utils.q_values(accept_header).map(&:first)
end
def version_and_vendor?
q_values_mime_types.any? { |mime_type| Grape::Util::MediaType.match?(mime_type) }
end
def invalid_accept_header!(message)
raise Grape::Exceptions::InvalidAcceptHeader.new(message, error_headers)
end
def invalid_version_header!(message)
raise Grape::Exceptions::InvalidVersionHeader.new(message, error_headers)
end
def fail!
return if env[Grape::Env::GRAPE_ALLOWED_METHODS].present?
media_types = q_values_mime_types.map { |mime_type| Grape::Util::MediaType.parse(mime_type) }
vendor_not_found!(media_types) || version_not_found!(media_types)
end
def vendor_not_found!(media_types)
return unless media_types.all? { |media_type| media_type&.vendor && media_type.vendor != vendor }
invalid_accept_header!('API vendor not found.')
end
def version_not_found!(media_types)
return unless media_types.all? { |media_type| media_type&.version && versions && !versions.include?(media_type.version) }
invalid_version_header!('API version not found.')
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/formatter/txt.rb | lib/grape/formatter/txt.rb | # frozen_string_literal: true
module Grape
module Formatter
class Txt < Base
def self.call(object, _env)
object.respond_to?(:to_txt) ? object.to_txt : object.to_s
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/formatter/xml.rb | lib/grape/formatter/xml.rb | # frozen_string_literal: true
module Grape
module Formatter
class Xml < Base
def self.call(object, _env)
return object.to_xml if object.respond_to?(:to_xml)
raise Grape::Exceptions::InvalidFormatter.new(object.class, 'xml')
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/formatter/json.rb | lib/grape/formatter/json.rb | # frozen_string_literal: true
module Grape
module Formatter
class Json < Base
def self.call(object, _env)
return object.to_json if object.respond_to?(:to_json)
::Grape::Json.dump(object)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/formatter/base.rb | lib/grape/formatter/base.rb | # frozen_string_literal: true
module Grape
module Formatter
class Base
def self.call(_object, _env)
raise NotImplementedError
end
def self.inherited(klass)
super
Formatter.register(klass)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/formatter/serializable_hash.rb | lib/grape/formatter/serializable_hash.rb | # frozen_string_literal: true
module Grape
module Formatter
class SerializableHash < Base
class << self
def call(object, _env)
return object if object.is_a?(String)
return ::Grape::Json.dump(serialize(object)) if serializable?(object)
return object.to_json if object.respond_to?(:to_json)
::Grape::Json.dump(object)
end
private
def serializable?(object)
object.respond_to?(:serializable_hash) || array_serializable?(object) || object.is_a?(Hash)
end
def serialize(object)
if object.respond_to? :serializable_hash
object.serializable_hash
elsif array_serializable?(object)
object.map(&:serializable_hash)
elsif object.is_a?(Hash)
object.transform_values { |v| serialize(v) }
else
object
end
end
def array_serializable?(object)
object.is_a?(Array) && object.all? { |o| o.respond_to? :serializable_hash }
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/lib/grape/dsl/desc.rb | lib/grape/dsl/desc.rb | # frozen_string_literal: true
module Grape
module DSL
module Desc
extend Grape::DSL::Settings
# Add a description to the next namespace or function.
# @param description [String] descriptive string for this endpoint
# or namespace
# @param options [Hash] other properties you can set to describe the
# endpoint or namespace. Optional.
# @option options :detail [String] additional detail about this endpoint
# @option options :summary [String] summary for this endpoint
# @option options :params [Hash] param types and info. normally, you set
# these via the `params` dsl method.
# @option options :entity [Grape::Entity] the entity returned upon a
# successful call to this action
# @option options :http_codes [Array[Array]] possible HTTP codes this
# endpoint may return, with their meanings, in a 2d array
# @option options :named [String] a specific name to help find this route
# @option options :body_name [String] override the autogenerated body name param
# @option options :headers [Hash] HTTP headers this method can accept
# @option options :hidden [Boolean] hide the endpoint or not
# @option options :deprecated [Boolean] deprecate the endpoint or not
# @option options :is_array [Boolean] response entity is array or not
# @option options :nickname [String] nickname of the endpoint
# @option options :produces [Array[String]] a list of MIME types the endpoint produce
# @option options :consumes [Array[String]] a list of MIME types the endpoint consume
# @option options :security [Array[Hash]] a list of security schemes
# @option options :tags [Array[String]] a list of tags
# @yield a block yielding an instance context with methods mapping to
# each of the above, except that :entity is also aliased as #success
# and :http_codes is aliased as #failure.
#
# @example
#
# desc 'create a user'
# post '/users' do
# # ...
# end
#
# desc 'find a user' do
# detail 'locates the user from the given user ID'
# failure [ [404, 'Couldn\'t find the given user' ] ]
# success User::Entity
# end
# get '/user/:id' do
# # ...
# end
#
def desc(description, options = {}, &config_block)
settings =
if config_block
endpoint_config = defined?(configuration) ? configuration : nil
Grape::Util::ApiDescription.new(description, endpoint_config, &config_block).settings
else
options.merge(description: description)
end
inheritable_setting.namespace[:description] = settings
inheritable_setting.route[:description] = settings
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.