15
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rails console から API を簡単に叩けるようにする

Last updated at Posted at 2013-07-26
api.rb
module MyApp
  module API
    class Railtie < Rails::Railtie
      class Command
        attr_accessor :user

        def initialize(user = nil)
          @user = user || User.first
        end

        %i(get post patch put delete head).each do |method|
          define_method(method) do |path, parameters = {}, headers_or_env = {}|
            app.__send__ method, path, default_params.merge(parameters), default_headers.merge(headers_or_env)
            ActiveSupport::JSON.decode app.response.body
          end
        end

        private

        def default_params
          {}.tap do |h|
            h[:api_key] = @user.api_key if @user
          end
        end

        def default_headers
          {}.tap do |h|
            h['Accept'] = 'application/json'
          end
        end

        def app
          TOPLEVEL_BINDING.eval('app')
        end
      end

      module ClassMethods
        def api
          @api ||= Command.new
        end
      end

      console do
        TOPLEVEL_BINDING.eval('self').extend ClassMethods
      end
    end
  end
end
console
api.get 'users' #=> [{"id"=>1, "name"=>"foo"}, {"id"=>2, "name"=>"bar"}]
api.user = nil
api.get 'users' #=> {"status"=>401, "message"=>"Unauthorized"}

api_key はそれぞれのサービスの認証に必要なパラメータ名に変えてください。

15
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?