Class: JsonParser
- Inherits:
-
Object
- Object
- JsonParser
- Defined in:
- lib/json_parser.rb
Instance Attribute Summary collapse
-
#db ⇒ Object
readonly
Returns the value of attribute db.
-
#path ⇒ Object
readonly
Returns the value of attribute path.
Instance Method Summary collapse
- #delete(key, symbols = nil) ⇒ Object
- #exist? ⇒ Boolean
-
#initialize(path, auto_write = true) ⇒ JsonParser
constructor
A new instance of JsonParser.
- #on(symbol, value) ⇒ Object
- #on_handler(symbol, handler, &block) ⇒ Object
- #parse(symbols, value = nil, delete = nil) ⇒ Object
Constructor Details
#initialize(path, auto_write = true) ⇒ JsonParser
Returns a new instance of JsonParser.
7 8 9 10 11 |
# File 'lib/json_parser.rb', line 7 def initialize path, auto_write = true @path = path @db = open @path @auto_write = auto_write end |
Instance Attribute Details
#db ⇒ Object (readonly)
Returns the value of attribute db.
5 6 7 |
# File 'lib/json_parser.rb', line 5 def db @db end |
#path ⇒ Object (readonly)
Returns the value of attribute path.
5 6 7 |
# File 'lib/json_parser.rb', line 5 def path @path end |
Instance Method Details
#delete(key, symbols = nil) ⇒ Object
66 67 68 |
# File 'lib/json_parser.rb', line 66 def delete key, symbols = nil parse(symbols, nil, key) end |
#exist? ⇒ Boolean
62 63 64 |
# File 'lib/json_parser.rb', line 62 def exist? @db.empty? end |
#on(symbol, value) ⇒ Object
13 14 15 16 17 |
# File 'lib/json_parser.rb', line 13 def on symbol, value unless @db.include?(symbol.to_s) parse symbol, value end end |
#on_handler(symbol, handler, &block) ⇒ Object
19 20 21 22 23 24 25 26 27 28 |
# File 'lib/json_parser.rb', line 19 def on_handler symbol, handler, &block unless @db.include?(symbol.to_s) block.call(false) if block value = handler.call() if value parse symbol, value block.call(true, value) if block end end end |
#parse(symbols, value = nil, delete = nil) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/json_parser.rb', line 30 def parse symbols, value = nil, delete = nil symbols_join = "" if symbols.class.name == "Array" symbols_join = symbols.join("\"][\"") else symbols_join = symbols.to_s end symbols_join = "[\"#{symbols_join}\"]" unless delete unless value eval "@db#{ symbols_join }" else eval "@db#{ symbols_join } = value" if @auto_write write @path, @db end end else if symbols eval "@db#{ symbols_join }.delete('#{delete}')" else eval "@db.delete('#{delete}')" end if @auto_write write @path, @db end end end |