Skip to content

Instantly share code, notes, and snippets.

@raulsouzalima
Last active December 18, 2020 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raulsouzalima/327621fd08d49e687591dc033bd670f4 to your computer and use it in GitHub Desktop.
Save raulsouzalima/327621fd08d49e687591dc033bd670f4 to your computer and use it in GitHub Desktop.
JsonSchema.rb
# app/schemas/credit_card_params_schema.json
{
"id": "//credit_card_params_schema",
"type": "object",
"properties": {
"holder_name": { "type": "string" },
"number": { "type": "string" },
"brand": { "type": "string" },
"month": { "type": "string" },
"year": { "type": "string" },
"verification_value": { "type": "string" },
"gateway_name": { "type": "string", "format": "gateway_name" }
}
}
# app/controllers/v1/credit_cards/models_controller.rb
def secure
credit_card_params.validate!(:credit_card_params_schema)
...
end
private
def credit_card_params
params.require(:credit_card).permit!
end
# config/initializers/json_schema.rb
[Hash, ActiveSupport::HashWithIndifferentAccess, ActionController::Parameters].each do |klass|
klass.class_eval do
def validate!(schema)
schema = JSON.parse(File.read(Rails.root.join('app', 'schemas', "#{schema}.json")), symbolize_names: true)
h = self.to_h
errors = JSON::Validator.fully_validate(schema, h, strict: true)
raise JSONValidatorError, errors unless errors.empty?
h
end
end
end
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment