Class: Settings::DataSource::File

Inherits:
Settings::DataSource show all
Defined in:
lib/settings/data_source/file.rb

Defined Under Namespace

Modules: Defaults, Directory

Instance Attribute Summary

Attributes inherited from Settings::DataSource

#source

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Settings::DataSource

build, #initialize

Constructor Details

This class inherits a constructor from Settings::DataSource

Class Method Details

.canonize(source) ⇒ Object



4
5
6
7
8
9
# File 'lib/settings/data_source/file.rb', line 4

def self.canonize(source)
  canonized_filepath = canonize_filepath(source)
  validate(canonized_filepath)

  canonized_filepath
end

.canonize_filepath(source) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/settings/data_source/file.rb', line 11

def self.canonize_filepath(source)
  return default_filepath if source.nil?
  return source if full_path?(source)

  dirpath = nil
  filepath = nil

  if file?(source)
    dirpath = Pathname.new(Directory::Defaults.pathname)
  else
    filepath = Pathname.new(Defaults.filename)
  end

  dirpath ||= Pathname.new(source)
  filepath ||= Pathname.new(source)

  pathname(filepath, dirpath)
end

.default_filepathObject



30
31
32
33
34
35
# File 'lib/settings/data_source/file.rb', line 30

def self.default_filepath
  dirpath = Pathname.new(Directory::Defaults.pathname)
  filepath = Pathname.new(Defaults.filename)

  pathname(filepath, dirpath)
end

.dir?(dirpath) ⇒ Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/settings/data_source/file.rb', line 49

def self.dir?(dirpath)
  ::File.dirname(dirpath) != "."
end

.file?(filepath) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/settings/data_source/file.rb', line 45

def self.file?(filepath)
  ::File.extname(filepath) != ""
end

.full_path?(source) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/settings/data_source/file.rb', line 41

def self.full_path?(source)
  file?(source) && dir?(source)
end

.pathname(filepath, dirpath) ⇒ Object



37
38
39
# File 'lib/settings/data_source/file.rb', line 37

def self.pathname(filepath, dirpath)
  (dirpath + filepath).to_s
end

.validate(pathname) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/settings/data_source/file.rb', line 53

def self.validate(pathname)
  pathname = Pathname.new(pathname)

  unless pathname.file?
    raise Settings::Error, "Settings cannot be read from #{pathname}. The file doesn't exist."
  end
end

Instance Method Details

#get_dataObject



61
62
63
64
65
66
67
68
# File 'lib/settings/data_source/file.rb', line 61

def get_data
  file = ::File.open(source)

  data = JSON.load(file)

  hash_data_source = Hash.build data
  hash_data_source.get_data
end