Rails Ranger is a library I wrote that’s focused on leveraging on the defaults of Ruby on Rails APIs to make your life easier when writing javascript clients for them. It’s essentially a thin layer wrapping the powerful Axios library, while still exposing its full power for you.
$ yarn add rails-ranger
# or
$ npm install —-save rails-ranger
The most basic setup would be something like that:
import RailsRanger from 'rails-ranger'
const config = {
axios: { baseURL: 'http://api.myapp.com' }
}
export default new RailsRanger(config)
One important note here is that anything you send inside the axios option will be handed down to Axios as it is, so you can configure it as you want.
Then how do we start making requests? Like this:
import api from 'api-client'
api.list('users').then((response) => {
// your code
})
So let’s break down what’s happening here:
list
function from it, which is just an alias for index
. This will trigger a request to the http://api.myapp.com/users
URL.response.data
will have all its keys converted to snake case automatically for you!Also, you can make use of nested resources with something like this:
api.resource(users, 1)
.list('blogPosts', { hideDrafts: true })
.then((response) => {
// your code
})
And this would make a request to:
http://api.myapp.com/users/1/blog_posts&hide_drafts=true
Notice that Rails Ranger converted your resource and parameters from camel case to snake case, so each part of your app (client and API) can talk in its preferred standards.
Everybody’s happy! 🎉
Other things you can do with Rails Ranger include using namespaced routes, interpolating into the URL and making raw HTTP requests.
You can see the full list of actions and methods of Rails Ranger at our comprehensive documentation. 😄
You can also use Rails Ranger as just a path builder and handle the requests yourself with your favorite client:
import { RouteBuilder } from RailsRanger
const routes = new RouteBuilder
route = routes.create('users', { name: 'John' })
// => { path: '/users', params: { name: 'John' }, method: 'post' }
Making AJAX requests to a Ruby on Rails API can be fun if we leverage the well-stablished standards of the framework.
This way we can free ourselves from handling repetitive tasks like converting between camel case and snake case and focus on accessing endpoints in a semantic way. 🤠
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!