Applying Common Filtering for Rails Api Based Applications
Sometimes there are common sets of fields and id’s that we would like the api to filter before sending the details to the client. It would be great if we can place them in a common place so that they can be changed anytime.
File: lib/api_config.rb
1 2 |
|
File: config/initializers/json_config.rb
1 2 3 4 5 6 7 8 9 10 |
|
the alias_method_chain does two things here:
firstly it creates an alias method called as_json_without_filter to as_json
secondly it looks for as_json_with_filter and makes that as the new as_json method
The as_json method is one that gets called when the to_json method is called on a model object or a collection of model objects in rails
example: users controller file
1 2 3 4 5 6 7 8 9 |
|
the above would call the as_json method of the user model, we have just overridden the super class to filter out a few fields
1 2 3 4 5 |
|
for xml, this is slightly Different
File: config/initializers/xml_config.rb
1 2 3 4 5 6 7 8 9 10 |
|
Any questions, please feel free to ask. We’re here to help…