Last active
December 18, 2020 13:33
-
-
Save raulsouzalima/327621fd08d49e687591dc033bd670f4 to your computer and use it in GitHub Desktop.
JsonSchema.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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