Search code examples
rackgrape-api

rackup grape with environment


I have a grape api that I mount directly using rackup and I would like to use an environment option to specify different url when deploying my api in production or development

my config.ru

#\-p 4000 -s puma
require 'grape'

#require all module
modules = Dir.glob('**/api/*/*/module/*.rb')
modules.each do |m|
  require './'+m
end
#require all table
bases = Dir.glob('**/api/*/*/*.rb')
bases.each do |b|
  require './'+b
end
#require all api versions
apis = Dir.glob('**/api/*.rb')
apis.each do |a|
  require './'+a
end

run DataRetriever::API

Solution

  • I took inspiration from rails for the structure and use SettingsLogic to manage environment settings. in your rackup file at the beginning add:

    ENV['RACK_ENV'] ||= 'development'
    

    if you want to execute some code only in some environment

    require_relative "config/environments/#{ENV['RACK_ENV']}"
    

    if you want to use different settings for each environment

    require 'settingslogic'
    class Settings < Settingslogic
      source File.join(File.dirname(__FILE__), 'config', 'settings.yml')
      namespace ENV['RACK_ENV']
    end
    

    you can watch my starter app https://github.com/scauglog/grape_starter_api