Coder Social home page Coder Social logo

rails-rfc6570's Introduction

Rails::RFC6570

Build Status

Pragmatic access to your Rails routes as RFC6570 URI templates. Tested with Rails 6.1, 7.0, 7.1 and Ruby 2.7, 3.0, 3.1, 3.2.

Installation

Add this line to your application's Gemfile:

gem 'rails-rfc6570', '~> 3.0'

Usage

Rails::RFC6570 gives you direct access to your Rails routes as RFC6570 URI templates using the addressable gem. It further patches Addressable::Template with a #as_json and #to_s so that you can simply pass the template objects or even partial expanded templates to your render call, decorator or serializer.

The following examples print a JSON index resource just like https://api.github.com:

class ApplicationController < ActionController::API
  def index
    render json: rfc6570_routes(ignore: %w(format), path_only: false)
  end
end

Pro Tip: Append _url to the route names: rfc6570_routes.transform_keys {|k| "#{k}_url" }.

By default, the format placeholder is ignored and the HTTP host will be included in the URI template.

Additionally, you can specify a list of query parameters in your controllers:

class UserController < ApplicationController

  rfc6570_params index: [:query, :email, :active]
  def index
    # ...
  end

  def show
    # ...
  end

  # ...
end

Given the above and this routes

Rails::Application.routes.draw do
  resources :users, except: [:new, :edit]
  root to: 'application#index'
end

the root action will return something similar to the following JSON:

{
  "users": "http://localhost:3000/users{?query,email,active}",
  "user": "http://localhost:3000/users/{id}",
  "root": "http://localhost:3000/"
}

You can also access your RFC6570 routes pragmatically everywhere you can access Rails' URL helpers e.g. in a decorator.

You can use this to e.g. partial expand templates for nested resources:

module ApplicationHelpers
  include Rails.application.routes.url_helpers
end

class UserDecorator < Draper::Decorator
  def as_json(opts)
    {
      id: object.id,
      self_url: user_url(object),
      posts_url: user_posts_rfc6570.partial_expand(user_id: object.id),
    }
  end
end

This gem does not support every construct possible with route matchers especially nested groups cannot be expressed in URI templates. They are expanded into separate groups. It also makes some assumptions when converting splat matchers like swallowing a multiple slashes. An error is raised when routes with OR-clauses are tried to be converted.

You can also combine Rails::RFC6570 with rack-link_headers and provide hypermedia linking everywhere!

class UserController < ApplicationController
  respond_to :json

  def show
    @user = User.find
    response.link user_url(@user), rel: :self
    response.link user_posts_rfc6570.partial_expand(user_id: @user.id), rel: :posts
    response.link profile_rfc6570.expand(user_id: @user.id), rel: :profile

    respond_with @user
  end
end

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Add specs
  4. Commit your changes (git commit -am 'Add some feature')
  5. Push to the branch (git push origin my-new-feature)
  6. Create new Pull Request

rails-rfc6570's People

Contributors

dependabot-preview[bot] avatar dependabot-support avatar jgraichen avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

rails-rfc6570's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): lock file maintenance

Detected dependencies

bundler
Gemfile
  • rspec '~> 3.0'
  • rake-release '~> 1.0'
github-actions
.github/workflows/test.yml
  • ruby/setup-ruby v1
  • ruby/setup-ruby v1
  • ubuntu 22.04
  • ubuntu 22.04
regex
rails-rfc6570.gemspec
  • actionpack >= 4.2
  • addressable ~> 2.3

  • Check this box to trigger a request for Renovate to run again on this repository

NoMethodError

When starting the server I get the following error:

.../gems/rails-rfc6570-0.1.2/lib/rails/rfc6570.rb:110:in `block (2 levels) in <class:Railtie>': private method `include' called for #<Module:0x00000002cd5eb8> (NoMethodError)

Ignore query parameters if same name already exists as a path parameter

When reusing controllers on different paths identically named placeholders might be added. See this example:

  get '/users/:user_id/permissions' => 'permissions#index'
  get '/permissions' => 'permissions#index'

The same controller is used for both actions as the user_id is just an optional filter for the permissions controller. Nevertheless the controller describes it as a param:

class PermissionsController < ApplicationController
  rfc6570_params index: %i[context user_id]
end

This will generate the following URI template for user_permissions:

/users/{user_id}/permissions{?context}{&user_id}

This will insert the User ID twice when expanding:

/users/fd32a10b-e900-4fdb-a4fd-6fe7002fb87c/permissions?user_id=fd32a10b-e900-4fdb-a4fd-6fe7002fb87c{&context}
Proposal

The query parameter user_id might just be skipped while kept for other routes:

user_permissions => /users/{user_id}/permissions{?context}
permissions => /permissions{?context}{&user_id}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.