Class: TinyDot

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

Overview

this class gives you read-only access to Hases, JSON, and YAML files using dot notation. it makes clever use of #method_missing to allow you to do the following:

 > t = TinyDot.new({ 'foo' => { 'bar' => 'baz' }})
 > t.foo                                               # returns another instance of TinyDot
=> #<TinyDot:0x0201243 @data={ 'bar' => 'baz' }>
 > t.foo!                                              # ! returns the value under the chain of keys
=> { 'bar' => 'baz' }

… in other words, it gives you a convenient dot notation syntax for accessing nested hashes. you can chain calls to this and you’ll get a new object that’s essentially a #dig into the top-level hash.

if you add ‘!’ to the last method in a chain it will return the value under that key.

finally, you can use dot syntax as deep as you want, and if there’s no key at that level you’ll just get ‘nil’ back:

 > t.foo.bar.baz.whatever.as.deep.as.you.want
=> nil

… which is sort of safe navigation operator-like without the save navigation operator

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ TinyDot

give it a Hash and it’ll give you dot notation over it



41
42
43
# File 'lib/tiny_dot.rb', line 41

def initialize(hash)
  @data = hash
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m) ⇒ Object



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

def method_missing(m)
  ms = m.to_s

  case @data
  when Hash
    if ms.end_with?('!')
      @data[ms[0..-2]]
    else
      if @data.has_key?(ms)
        TinyDot.new(@data[ms])
      else
        TinyDot.new({})
      end
    end
  else
    TinyDot.new({})
  end
end

Class Method Details

.from_json_file(filename) ⇒ Object

returns a TinyDot instance after parsing the JSON in the named filename



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

def self.from_json_file(filename)
  TinyDot.new(JSON.parse(IO.read(filename)))
end

.from_yaml_file(filename) ⇒ Object

returns a TinyDot instance after parsing the YAML in the named filename



31
32
33
# File 'lib/tiny_dot.rb', line 31

def self.from_yaml_file(filename)
  TinyDot.new(YAML.safe_load_file(filename))
end