Sha256: d6ea9f4a8dabf83efce7e2a0847e61b40966010442a8658aa2dba9b0d875be21

Contents?: true

Size: 1.5 KB

Versions: 1

Compression:

Stored size: 1.5 KB

Contents

# frozen_string_literal: true

class SelfData
  class << self
    attr_accessor :default_formats, :default_options

    def read(*args, **kargs)
      new.read(*args, **kargs)
    end

    def load(*args, **kargs)
      new.load(*args, **kargs)
    end

    def filters
      @filters ||= []
    end

    def add_filter(&block)
      filters << block
    end

    def converters
      @converters ||= {}
    end

    def add_converter(name, proc = nil, &block)
      converters[name] = proc || block
    end
  end

  attr_reader :file

  def initialize(file = caller_file)
    @file = file
  end

  def load(*formats, **options)
    formats = self.class.default_formats if formats.empty?
    options = self.class.default_options if options.empty?

    formats.reduce(read) do |data, format|
      raise ConverterNotFound, format unless self.class.converters[format]
      begin
        self.class.converters[format].call(data, options)
      rescue => error
        raise ConversionError.new(format, error)
      end
    end
  end

  def read
    File.read(file).scan(/\n__END__\n(.*)/m).flatten.first or raise NoDataFound, file
  end

  private

  def caller_file
    calls = caller.lazy
      .map { |call_string| call_string.split(":").first }
      .reject { |file| file == __FILE__ }
      .select { |x| File.exist?(x) }

    self.class.filters.each do |filter|
      calls = calls.select { |x| filter.call(x) }
    end

    calls.first
  end
end

require "self_data/errors"
require "self_data/version"
require "self_data/config"

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
self_data-1.3.0 lib/self_data.rb