Is there a pattern or best practice in Rails whereby we can specify, in one place, the names/symbols of params that are to be used in the API, so that we can reference it throughout our code and tests?
Our application entails a user passing in parameters to our API via HTTP POST. We use symbols to get at the values as follows:
first_name = params[:firstname]
last_name = params[:lastname]
...
We also set the values of params within our RSpec tests:
params = {
firstname: 'John',
lastname: 'Doe',
...
}
Obviously the above examples are rather simplistic, and in our application we have many more parameters. As such it would be good to have a definitive set of API parameters that can be used. The main benefit being that other developers can then know what parameters are available in the application. Furthermore, we want to safeguard against symbols being typed incorrectly.
My thinking at the minute is to use a module called API with some constants defined:
Module API
FIRST_NAME = :firstname
LAST_NAME = :lastname
...
end
We could then use the module as follows:
first_name = params[API::FIRST_NAME]
last_name = params[API::LAST_NAME]
...
Is this approach even correct? Will there be a performance cost?
Note: We will have the same parameters for every call. Furthermore, the parameters may change as we’re currently in the early stages of development and the final set of API fields along with their names haven’t been decided on yet.
It is likely your API will not have the same parameters for every call. Also, you probably won’t want to change the parameters frequently unless you are the only consumer of your API as changes in the API will break things for your customers. For these reasons I don’t think constantizing the params in a module is going to buy you that much.
While there are plenty of places to try to remove redundant code, I’m doubting that your proposed strategy is going to work well for you in the long term. If you find you are repeating yourself a lot in your tests (which certainly happens with APIs), you may want to take a look at rack-test-rest, a gem which can take care of a lot of the pain of API testing.
Basically it makes reasonable assumptions about arguments you don’t provide to keep you on track for code http status codes, responses, etc. Hope this helps!