Class: Conifer::File

Inherits:
Object
  • Object
show all
Defined in:
lib/conifer/file.rb

Constant Summary collapse

NotFoundError =
Class.new(StandardError)
UnsupportedFormatError =
Class.new(StandardError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, dir:, prefix: nil, format: :yml, allowed_classes: []) ⇒ File

Returns a new instance of File.



13
14
15
16
17
18
19
# File 'lib/conifer/file.rb', line 13

def initialize(name, dir:, prefix: nil, format: :yml, allowed_classes: [])
  @name = name
  @dir = dir
  @prefix = prefix
  @format = format
  @allowed_classes = allowed_classes
end

Instance Attribute Details

#allowed_classesObject (readonly)

Returns the value of attribute allowed_classes.



11
12
13
# File 'lib/conifer/file.rb', line 11

def allowed_classes
  @allowed_classes
end

#dirObject (readonly)

Returns the value of attribute dir.



11
12
13
# File 'lib/conifer/file.rb', line 11

def dir
  @dir
end

#formatObject (readonly)

Returns the value of attribute format.



11
12
13
# File 'lib/conifer/file.rb', line 11

def format
  @format
end

#nameObject (readonly)

Returns the value of attribute name.



11
12
13
# File 'lib/conifer/file.rb', line 11

def name
  @name
end

#prefixObject (readonly)

Returns the value of attribute prefix.



11
12
13
# File 'lib/conifer/file.rb', line 11

def prefix
  @prefix
end

Instance Method Details

#[](key) ⇒ Object



21
22
23
24
# File 'lib/conifer/file.rb', line 21

def [](key)
  args = key.split('.').tap { |v| v.prepend(prefix) if prefix }
  parsed.dig(*args)
end

#exists?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/conifer/file.rb', line 43

def exists?
  !path.nil?
end

#filenameObject



47
48
49
# File 'lib/conifer/file.rb', line 47

def filename
  "#{::File.basename(name.to_s, ".#{format}")}.#{format}"
end

#parsedObject



26
27
28
29
30
31
32
33
34
35
# File 'lib/conifer/file.rb', line 26

def parsed
  @parsed ||= case format
              when :yml, :yaml
                YAML.safe_load(ERB.new(::File.read(path)).result, allowed_classes)
              when :json
                JSON.parse(ERB.new(::File.read(path)).result)
              else
                raise UnsupportedFormatError, "Format '#{format}' is not supported"
              end
end

#pathObject



37
38
39
40
41
# File 'lib/conifer/file.rb', line 37

def path
  return @path if defined? @path

  @path = find_path
end

#validate!Object

Raises:



51
52
53
# File 'lib/conifer/file.rb', line 51

def validate!
  raise NotFoundError, "Could not find file #{filename}" if path.nil?
end