Now that we’ve covered Python, PHP, and C#, Ruby is the last of the HTTP clients that incorporates a fluent interface. Unfortunately, Java, Node.js, and Go don’t make developing fluent interfaces as easy, but we’ll get to them in the future. For today, let’s focus on some Ruby magic.
The remainder of this post will reference the following code:
Fluent Interface Recap
A fluent interface allows us to create API calls dynamically, without the need to pre-define every endpoint. For example, we can use `client.path.to.the.endpoint.get()` for a call to: `GET /path/to/the/endpoint` without having to define methods for `path`, `to`, `the`, and `endpoint`.
To chain our method calls together, in general, we simply return `self`. However, in this case we are returning a new version of the `Fluent` object, because we want to preserve fragments of the cache for later reuse see line 13.
To capture the method calls dynamically, we need to use Ruby’s dynamic `method_missing`, which is called whenever the object can’t find the method you are calling see line 7. You can read more about`method_missing` at Ruby-Doc.org.
Handling Special Cases
To handle special cases or allow users to specify a complete path as a string, we use the `_()` method see line 12. You pass in a string and receive a new object with the name of your string added to the cache variable.
References & Acknowledgements
The following references helped me understand the concepts described in this post:
- Respond to an Unknown Method Call in Ruby
- Python HTTP Client Blog Post
- PHP HTTP Client Blog Post
- C# HTTP Client Blog Post
Thank you for dropping by, and if you decide to build something with this library or have some contributions, please open an issue in our Ruby HTTP Client repository.
What’s next? Stay tuned as we explore why we didn’t create a fluent interface with Node.js, Go, and Java!