Class: Brief::Data::Wrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/brief/data.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Wrapper

Returns a new instance of Wrapper.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/brief/data.rb', line 21

def initialize(options={})
  @root = options.fetch(:root) { Pathname(Brief.pwd).join('data') }
  @sources = {}.to_mash

  load_files.each do |source, data|
    if data.is_a?(Hash)
      @sources[source] = data.keys.inject({}.to_mash) do |memo, key|
        memo[key] = Queryable.new(data[key])
        memo
      end
    elsif data.is_a?(Array)
      @sources[source] = Queryable.new(data)
    end
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object



37
38
39
40
# File 'lib/brief/data.rb', line 37

def method_missing(meth, *args, &block)
  return sources.send(meth, *args, &block) if sources.key?(meth)
  super
end

Instance Attribute Details

#rootObject

Returns the value of attribute root.



19
20
21
# File 'lib/brief/data.rb', line 19

def root
  @root
end

#sourcesObject

Returns the value of attribute sources.



19
20
21
# File 'lib/brief/data.rb', line 19

def sources
  @sources
end

Instance Method Details

#load_filesObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/brief/data.rb', line 42

def load_files
  files = Dir[root.join("**/*.yml")] + Dir[root.join("**/*.json")] + Dir[root.join("**/*.yaml")]

  files.map! do |file|
    path = Pathname(file)

    if path.extname == ".json"
      key = "#{path.basename.to_s.gsub(/\.json$/i, '')}"
      data = JSON.parse(path.read)
    elsif path.extname == '.yml' || path.extname == ".yaml"
      key = "#{path.basename.to_s.gsub(/\.ya?ml$/i, '')}"
      data = YAML.load(path.read)
    else
      nil
    end

    {key => data} if key && data
  end

  files.compact.reduce({}) {|memo, hash| memo.merge(hash) }
end