Class: Monolens::Jsonpath
- Inherits:
-
Object
- Object
- Monolens::Jsonpath
- Defined in:
- lib/monolens/jsonpath.rb
Constant Summary collapse
- INTERPOLATE_RXS =
{ '$' => interpolate_rx("\\" + '$'), '<' => interpolate_rx('<'), }
- DEFAULT_OPTIONS =
{ root_symbol: '$', use_symbols: true, }
Class Method Summary collapse
- .interpolate(str, input, options = {}) ⇒ Object
- .interpolate_detect_rx(symbol) ⇒ Object
- .interpolate_rx(symbol) ⇒ Object
- .one(path, input, options = {}) ⇒ Object
- .one_detect_rx(symbol) ⇒ Object
Instance Method Summary collapse
-
#initialize(path, options = {}) ⇒ Jsonpath
constructor
A new instance of Jsonpath.
- #interpolate(str, input) ⇒ Object
- #one(input) ⇒ Object
Constructor Details
#initialize(path, options = {}) ⇒ Jsonpath
Returns a new instance of Jsonpath.
34 35 36 37 38 39 |
# File 'lib/monolens/jsonpath.rb', line 34 def initialize(path, = {}) @path = path @options = DEFAULT_OPTIONS.merge() @interpolate_rx = INTERPOLATE_RXS[@options[:root_symbol]] raise ArgumentError, "Unknown root symbol #{@options.inspect}" unless @interpolate_rx end |
Class Method Details
.interpolate(str, input, options = {}) ⇒ Object
45 46 47 |
# File 'lib/monolens/jsonpath.rb', line 45 def self.interpolate(str, input, = {}) Jsonpath.new('', ).interpolate(str, input) end |
.interpolate_detect_rx(symbol) ⇒ Object
8 9 10 11 |
# File 'lib/monolens/jsonpath.rb', line 8 def self.interpolate_detect_rx(symbol) symbol = "\\" + symbol if symbol == '$' %r{#{symbol}[.(]} end |
.interpolate_rx(symbol) ⇒ Object
13 14 15 16 17 18 19 20 21 22 |
# File 'lib/monolens/jsonpath.rb', line 13 def self.interpolate_rx(symbol) %r{ #{symbol} ( (\.([a-zA-Z0-9.-_\[\]])+) | (\([^)]+\)) ) }x.freeze end |
.one(path, input, options = {}) ⇒ Object
41 42 43 |
# File 'lib/monolens/jsonpath.rb', line 41 def self.one(path, input, = {}) Jsonpath.new(path, ).one(input) end |
.one_detect_rx(symbol) ⇒ Object
3 4 5 6 |
# File 'lib/monolens/jsonpath.rb', line 3 def self.one_detect_rx(symbol) symbol = "\\" + symbol if symbol == '$' %r{^#{symbol}([.\[][^\s]+)?$} end |
Instance Method Details
#interpolate(str, input) ⇒ Object
70 71 72 73 74 |
# File 'lib/monolens/jsonpath.rb', line 70 def interpolate(str, input) str.gsub(@interpolate_rx) do |path| Jsonpath.one(path, input, @options) end end |
#one(input) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/monolens/jsonpath.rb', line 49 def one(input) use_symbols = @options[:use_symbols] parts = @path .gsub(/[.\[\]\(\)]/, ';') .split(';') .reject{|p| p.nil? || p.empty? || p == '$' || p == '<' } .map{|p| case p when /^'[^']+'$/ use_symbols ? p[1...-1].to_sym : p[1...-1] when /^\d+$/ p.to_i else use_symbols ? p.to_sym : p end } parts.empty? ? input : input.dig(*parts) end |