diff options
author | Rémy Coutable <remy@rymai.me> | 2016-10-13 19:44:52 +0300 |
---|---|---|
committer | Rémy Coutable <remy@rymai.me> | 2016-10-13 19:44:52 +0300 |
commit | b2c771f45261e1484158d1304cd898e866002f07 (patch) | |
tree | 1ecdda0ea9d2d300954afa3ab8bc2c7af3adc56c /doc/development/api_styleguide.md | |
parent | 626d5e555a5634abd4ab61cf942c36025aed60f4 (diff) |
Add an API styleguide
Signed-off-by: Rémy Coutable <remy@rymai.me>
Diffstat (limited to 'doc/development/api_styleguide.md')
-rw-r--r-- | doc/development/api_styleguide.md | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/doc/development/api_styleguide.md b/doc/development/api_styleguide.md new file mode 100644 index 00000000000..ee5e7ad3988 --- /dev/null +++ b/doc/development/api_styleguide.md @@ -0,0 +1,58 @@ +# API styleguide + +This styleguide recommends best practices for the API development. + +## Declared params + +> Grape allows you to access only the parameters that have been declared by your +`params` block. It filters out the params that have been passed, but are not +allowed. + +– https://github.com/ruby-grape/grape#declared + +### Exclude params from parent namespaces + +> By default `declared(params) `includes parameters that were defined in all +parent namespaces. + +– https://github.com/ruby-grape/grape#include-parent-namespaces + +In most cases you will want to exclude params from the parent namespaces: + +```ruby +declared(params, include_parent_namespaces: false) +``` + +### When to use `declared(params)`? + +You should always use `declared(params)` when you pass the params hash as +arguments to a method call. + +For instance: + +```ruby +# bad +User.create(params) # imagine the user submitted `admin=1`... :) + +# good +User.create(declared(params, include_parent_namespaces: false).to_h) +``` + +>**Note:** +`declared(params)` return a `Hashie::Mash` object, on which you will have to +call `.to_h`. + +But we can use directly `params[key]` when we access single elements. + +For instance: + +```ruby +# good +Model.create(foo: params[:foo]) +``` + +>**Note:** +Since you [should use Grape's DSL to declare params](doc_styleguide.md#method-description), [parameters validation and +coercion] comes for free! + +[parameters validation and coercion]: https://github.com/ruby-grape/grape#parameter-validation-and-coercion |