Class: BxBuilderChain::Loader

Inherits:
Object
  • Object
show all
Defined in:
lib/bx_builder_chain/loader.rb

Defined Under Namespace

Classes: FileNotFound, UnknownFormatError

Constant Summary collapse

URI_REGEX =
%r{\A[A-Za-z][A-Za-z0-9+\-.]*://}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, options = {}) ⇒ BxBuilderChain::Loader

Initialize BxBuilderChain::Loader

Parameters:

  • path (String | Pathname)

    path to file or URL

  • options (Hash) (defaults to: {})

    options passed to the processor class used to process the data



40
41
42
43
# File 'lib/bx_builder_chain/loader.rb', line 40

def initialize(path, options = {})
  @options = options
  @path = path
end

Class Method Details

.load(path, options = {}, &block) ⇒ Data

Load data from a file or URL. Shorthand for ‘BxBuilderChain::Loader.new(path).load`

Examples

 # load a URL
 data = BxBuilderChain::Loader.load("https://example.com/docs/README.md")

 # load a file
 data = BxBuilderChain::Loader.load("README.md")

# Load data using a custom processor
data = BxBuilderChain::Loader.load("README.md") do |raw_data, options|
  # your processing code goes here
  # return data at the end here
end

Parameters:

  • path (String | Pathname)

    path to file or URL

  • options (Hash) (defaults to: {})

    options passed to the processor class used to process the data

Returns:

  • (Data)

    data loaded from path



32
33
34
# File 'lib/bx_builder_chain/loader.rb', line 32

def self.load(path, options = {}, &block)
  new(path, options).load(&block)
end

Instance Method Details

#directory?Boolean

Is the path a directory

Returns:

  • (Boolean)

    true if path is a directory



57
58
59
# File 'lib/bx_builder_chain/loader.rb', line 57

def directory?
  File.directory?(@path)
end

#load {|String, Hash| ... } ⇒ Data

Load data from a file or URL

loader = BxBuilderChain::Loader.new("README.md")
# Load data using default processor for the file
loader.load

# Load data using a custom processor
loader.load do |raw_data, options|
  # your processing code goes here
  # return data at the end here
end

Yields:

  • (String, Hash)

    handle parsing raw output into string directly

Yield Parameters:

  • raw_data (String)

    from the loaded URL or file

Yield Returns:

  • (String)

    parsed data, as a String

Returns:

  • (Data)

    data that was loaded



78
79
80
81
82
83
# File 'lib/bx_builder_chain/loader.rb', line 78

def load(&block)
  return process_data(load_from_url, &block) if url?
  return load_from_directory(&block) if directory?

  process_data(load_from_path, &block)
end

#url?Boolean

Is the path a URL?

Returns:

  • (Boolean)

    true if path is URL



48
49
50
51
52
# File 'lib/bx_builder_chain/loader.rb', line 48

def url?
  return false if @path.is_a?(Pathname)

  !!(@path =~ URI_REGEX)
end