diff --git a/lib/rackstash/adapter/file.rb b/lib/rackstash/adapter/file.rb index fe2e6f6..8c030aa 100644 --- a/lib/rackstash/adapter/file.rb +++ b/lib/rackstash/adapter/file.rb @@ -57,11 +57,26 @@ module Rackstash # file was moved, you don't need to create the new file there nor should you # use the (potentially destructive) `copytruncate` option of logrotate. class File < BaseAdapter - register_for ::String, ::Pathname + register_for ::String, ::Pathname, 'file' # @return [String] the absolute path to the log file attr_reader :filename + def self.from_uri(uri) + uri = URI(uri) + + if (uri.scheme || uri.opaque) == 'file'.freeze + file_options = parse_uri_options(uri) + if file_options[:auto_reopen] =~ /\A(:?false|0)?\z/i + file_options[:auto_reopen] = false + end + + new(uri.path, **file_options) + else + raise ArgumentError, "Invalid URI: #{uri}" + end + end + # Create a new file adapter instance which writes logs to the log file # specified in `filename`. # diff --git a/spec/rackstash/adapter/file_spec.rb b/spec/rackstash/adapter/file_spec.rb index a211f9a..13c7952 100644 --- a/spec/rackstash/adapter/file_spec.rb +++ b/spec/rackstash/adapter/file_spec.rb @@ -22,6 +22,27 @@ describe Rackstash::Adapter::File do logfile.unlink end + describe 'from_uri' do + it 'creates a File adapter instance' do + expect(described_class.from_uri('file:/tmp/file_spec.log')) + .to be_instance_of described_class + expect(described_class.from_uri('file:///tmp/file_spec.log')) + .to be_instance_of described_class + end + + it 'sets the filename from the URI path' do + expect(described_class.from_uri('file:/tmp/file_spec.log').filename) + .to eql '/tmp/file_spec.log' + expect(described_class.from_uri('file:///tmp/file_spec.log').filename) + .to eql '/tmp/file_spec.log' + end + + it 'sets optional attributes' do + expect(described_class.from_uri('file:/tmp/file_spec.log?auto_reopen=false').auto_reopen?) + .to eql false + end + end + describe '#initialize' do it 'accepts a String' do expect(described_class.new(logfile.path).filename) @@ -35,7 +56,7 @@ describe Rackstash::Adapter::File do .and be_a String end - it 'rejects non-IO objects' do + it 'rejects other objects' do expect { described_class.new(nil) }.to raise_error TypeError expect { described_class.new(Object.new) }.to raise_error TypeError expect { described_class.new(23) }.to raise_error TypeError