Class: Dommy::Resources::FileSystem

Inherits:
Object
  • Object
show all
Defined in:
lib/dommy/resources.rb

Instance Method Summary collapse

Constructor Details

#initialize(root, base_url) ⇒ FileSystem

Returns a new instance of FileSystem.



141
142
143
144
# File 'lib/dommy/resources.rb', line 141

def initialize(root, base_url)
  @root = ::File.expand_path(root.to_s)
  @base = base_url.to_s.sub(%r{/\z}, "")
end

Instance Method Details

#get(url, headers: {}) ⇒ Object



146
# File 'lib/dommy/resources.rb', line 146

def get(url, headers: {}) = request(method: "GET", url: url, headers: headers)

#request(method:, url:, headers: {}, body: nil) ⇒ Object



148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/dommy/resources.rb', line 148

def request(method:, url:, headers: {}, body: nil)
  path = Pathing.path_of(url)
  return nil unless @base.empty? || path.start_with?("#{@base}/") || path == @base

  rel = @base.empty? ? path : path[@base.length..]
  file = ::File.expand_path(rel.sub(%r{\A/}, ""), @root)
  # Containment guard: never escape `root`.
  return nil unless file == @root || file.start_with?("#{@root}/")
  return nil unless ::File.file?(file)

  Response.new(status: 200, status_text: "OK", headers: {}, body: ::File.read(file), url: url.to_s, redirected: false)
end