Created
February 20, 2023 19:58
-
-
Save Signum/bfbf1d75d47a76c396fceb7362a3c717 to your computer and use it in GitHub Desktop.
Using Rack::Static in Hanami 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# routes.rb: | |
```ruby | |
get '/api', to: ->(env) { [200, {}, ["A Rack compatible response"]] } | |
get '/*path', to: ::Imc::MyStatic.new("frontend/build") | |
``` | |
# lib/imc/staticserve.rb: | |
```ruby | |
require "rack" | |
module Imc | |
class MyStatic < Rack::Files | |
def get(env) | |
request = Rack::Request.new env | |
unless ALLOWED_VERBS.include? request.request_method | |
return fail(405, "Method Not Allowed", { 'allow' => ALLOW_HEADER }) | |
end | |
path_info = Rack::Utils.unescape_path request.path_info | |
return fail(400, "Bad Request") unless Rack::Utils.valid_path?(path_info) | |
clean_path_info = Rack::Utils.clean_path_info(path_info) | |
path = ::File.join(@root, clean_path_info) | |
if (::File.file?(path) && ::File.readable?(path)) | |
return serving(request, path) | |
end | |
# Not found? Try loading 'index.html' | |
path = File.join(path, 'index.html') | |
if (::File.file?(path) && ::File.readable?(path)) | |
return serving(request, path) | |
end | |
fail(404, "File not found: #{path_info}") | |
end | |
end | |
end | |
``` | |
"Imc" is the name of my application. | |
I am overriding the Rack::Files class's get() method so that an index.html would be found. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment