Skip to content

Instantly share code, notes, and snippets.

@Signum
Created February 20, 2023 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Signum/bfbf1d75d47a76c396fceb7362a3c717 to your computer and use it in GitHub Desktop.
Save Signum/bfbf1d75d47a76c396fceb7362a3c717 to your computer and use it in GitHub Desktop.
Using Rack::Static in Hanami 2
# 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