Skip to content

Latest commit

 

History

History
81 lines (54 loc) · 2.27 KB

README.md

File metadata and controls

81 lines (54 loc) · 2.27 KB

Gem Version Maintainability Test Coverage Build Status

BetterDig

Another kind of hash/array lookup you'll like

Supports dig-like method for Ruby below 2.3

Table of Context

Installation

Add this line to your application's Gemfile:

gem 'better_dig'

And then execute:

$ bundle

Or install it yourself as:

$ gem install better_dig

Usage

Basic Examples

hash = { hello: 'world', nested: { hello: 'world' }, nested_array: ['hello', 'world'], is_cool: true }

# Fetch by digg
hash.digg(:hello)                #=> 'world'
hash.digg('hello')               #=> 'world'
hash.digg('nested', 'hello')     #=> 'world'
hash.digg('nested_array', 0)     #=> 'hello'
hash.digg('nested_array', '0')   #=> 'hello'
hash.digg(:hello, 0, :not_found) #=> nil

# Fetch by path
hash.fetch_path('nested/hello')                 #=> 'world'
hash.fetch_path('nested_array/0')               #=> 'hello'
hash.fetch_path('nested.hello', delimeter: '.') #=> 'hello'
hash.fetch_path('nested/hello/none', default: 'zh-tw.not_found') #=> 'zh-tw.not_found'
hash.fetch_path('is_cool') #=> true

# Since `nil` will be returned for not found value instead of TypeError if we are digging too far
# we can use conditional block without breaking the application

if hash.digg(:nested, :hello, :world) # => nil
  # DO SOMETHING WHEN FOUND
else
  # DO SOMETHING WHEN NOT FOUND
end

Or probably in the Rails views

<%= object.hash_data.digg(:snapshot, :price) %>

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/berniechiu/better_dig.

License

The gem is available as open source under the terms of the MIT License.