It's possible, for example, to use ActiveRecord inline in a Ruby script. I like this a lot to report bugs, test features and share gists.
I'm wondering if the same could be done for a Rails webservice? (I'm mainly interested in getting the controller layer to work, the rest should be easy to add on demand.) Something along these lines:
begin
require "bundler/inline"
rescue LoadError => e
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
raise e
end
gemfile(true) do
source "https://rubygems.org"
gem 'rails', '~> 6.0.0'
end
require 'rails/commands'
APP_PATH = File.expand_path('config/application', __dir__)
Rails::Command.invoke('server')
When toying around with this it did seem that an external entry point (APP_PATH
) is required. So alternatively, an acceptable approach would be to cram all config into the single entry point. I couldn't get this to work so far.
The Rails Initialization Process is the best resource I found about this so far.
I produced a minimal Rails app to get started as follows:
rails new min-rails --skip-keeps --skip-action-mailer --skip-action-mailbox --skip-action-text --skip-active-record --skip-active-storage --skip-puma --skip-action-cable --skip-sprockets --skip-spring --skip-listen --skip-javascript --skip-turbolinks --skip-test --skip-system-test --skip-bootsnap --api
cd min-rails
rm -rf app/jobs app/models config/initializers config/locales lib log public tmp vendor config/environments/test.rb config/environments/production.rb config/credentials.yml.enc config/master.key bin/rake bin/setup bin/bundle
I ended up with the following script:
inline-rails.rb
begin
require "bundler/inline"
rescue LoadError => e
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
raise e
end
gemfile(true) do
source "https://rubygems.org"
gem 'rails', '~> 6.0.0'
end
require "action_controller/railtie"
class App < Rails::Application
routes.append do
get "/hello/world" => "hello#world"
end
config.consider_all_requests_local = true # display errors
end
class HelloController < ActionController::API
def world
render json: {hello: :world}
end
end
App.initialize!
Rack::Server.new(app: App, Port: 3000).start
Run it as:
ruby inline-rails.rb
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With