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`.

Method Chaining

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.

Reflection

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:

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!



Elmer Thomas is SendGrid's Developer Experience Engineer. His mission is to help SendGrid live up to its slogan: "Email Delivery. Simplified" by improving the lives of developers, both internally and externally. Via all sorts of hackery, of course. Follow his exploits on Twitter and GitHub.