amatsuda / jb

A simple and fast JSON API template engine for Ruby on Rails
MIT License
1.29k stars 43 forks source link

JSONP support? #19

Open waruboy opened 6 years ago

waruboy commented 6 years ago

Hi~ First, thank you for this gem. I started to use this gem in my projects because the syntax is enjoyable.

I want to ask, if there is jsonp support with this? so the output can be wrapped in function, defined by params[:callback] for example.

Thank you

peterxjang commented 5 years ago

I believe you should be able to support jsonp in your controller directly without making changes to the jb gem. This StackOverflow answer has a possible approach. Here's what some example code would look like:

class Api::ProductsController < ApplicationController
  after_action { |controller| handle_jsonp(controller) }

  def index
    @products = Product.all
    render "index.json.jb"
  end

  private

  def handle_jsonp(controller)
    if controller.params[:callback]
      controller.response['Content-Type'] = 'application/javascript'
      controller.response.body = "/**/#{controller.params[:callback]}(#{controller.response.body})"
    end
  end
end

Lemme know if that makes sense, thanks!

waruboy commented 5 years ago

@peterxjang thanks for the reply! Yes, we definitely can do it via the controller. I just think that it will be nice if it comes out of the box from the gem. For example RABL support it out of the box: https://github.com/nesquena/rabl/issues/16