Simple gadget life programming diary

Simple gadget life の中の人によるプログラミングメモ

Ruby(Rails)にAPI作成支援ライブラリGrapeで任意の返却値を返す方法

サンプルを見ているとRailsのモデルをそのまま返すというサンプルが多く、モデルのなかでも必要な項目(idやタイムスタンプを除いて)を返すというサンプルがなかったのでメモ。

module TestApp
  class API < Grape::API
    prefix 'api'
    version 'v1', using: :path
    format :json
        
    resource :tweeturls do
      get do
        arrayUrl = Array.new(100)
        objs = Tweeturl.first(100)

        objs.each do |obj|
          arrayUrl.push({"url" => obj.url})
        end

        hashobj = Hash["urls" => arrayUrl]
        present hashobj
      end
    end
  end
end

モデルは以下

class CreateTweeturls < ActiveRecord::Migration
  def change
    create_table :tweeturls do |t|
      t.string :url
      t.timestamps
    end
  end
end

TwitterUrlsというモデルにはタイムスタンプとurl、自動で付与されるidを持っている。
そのモデルからurlだけを100個返却するのがAPIの内容。
自分でArrayやHashで組み立てて、presentで返却すれば作成完了。