Class: Decant::Collection

Inherits:
Object
  • Object
show all
Defined in:
lib/decant/collection.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dir:, ext: nil) ⇒ Collection

Returns a new instance of Collection.

Parameters:

  • dir (Pathname, String)
  • ext (String, nil) (defaults to: nil)


15
16
17
18
# File 'lib/decant/collection.rb', line 15

def initialize(dir:, ext: nil)
  self.dir = dir
  self.ext = ext
end

Instance Attribute Details

#dirPathname

Returns:

  • (Pathname)


8
9
10
# File 'lib/decant/collection.rb', line 8

def dir
  @dir
end

#extString?

Returns:

  • (String, nil)


11
12
13
# File 'lib/decant/collection.rb', line 11

def ext
  @ext
end

Instance Method Details

#entriesArray<Pathname>

Returns:

  • (Array<Pathname>)


21
22
23
# File 'lib/decant/collection.rb', line 21

def entries
  glob('**/*')
end

#find(pattern) ⇒ Pathname?

If #ext is defined then pattern MUST NOT include the file’s extension as it will automatically be added, if #ext is nil then pattern MUST include the file’s extension - essentially becoming the file’s full relative path within #dir.

Technically pattern can be any pattern supported by Dir.glob though it’s more likely to simply be a file name.

Parameters:

  • pattern (String)

Returns:

  • (Pathname, nil)


36
37
38
# File 'lib/decant/collection.rb', line 36

def find(pattern)
  glob(pattern).first
end

#glob(pattern) ⇒ Array<Pathname>

Parameters:

  • pattern (String)

Returns:

  • (Array<Pathname>)


43
44
45
# File 'lib/decant/collection.rb', line 43

def glob(pattern)
  dir.glob("#{pattern}#{ext}").select { |path| path.file? }
end

#relative_path_for(path) ⇒ String

The relative path of path within #dir.

Parameters:

  • path (Pathname)

Returns:

  • (String)


52
53
54
# File 'lib/decant/collection.rb', line 52

def relative_path_for(path)
  path.relative_path_from(dir).to_s
end

#slug_for(path) ⇒ String

The extension-less relative path of path within #dir.

Parameters:

  • path (Pathname)

Returns:

  • (String)


61
62
63
64
65
66
67
68
69
# File 'lib/decant/collection.rb', line 61

def slug_for(path)
  relative_path = relative_path_for(path)

  # The collection has no configured extension, files are identified by
  # their full (relative) path so there's no extension to remove.
  return relative_path if @delete_ext_regexp.nil?

  relative_path.sub(@delete_ext_regexp, '')
end