Skip to content

Repository files navigation

This gem monkey patches Object and Array with methods that allow querying and slicing nested records and attributes.

  • Object (and therefore also Array) gains:
    • attrs - Slice nested attributes/method evaluations in specified structure
    • oattrs - Alias for attrs in case of name conflict
    • attrs_match? - Check, with indifferent access, if evaluating two attributes/methods match or evaluate to true
  • Array return item where attrs_match? is true
    • where - Return all items
    • find_by - Return first item

See examples under Usage

Installation

From RubyGems.org

Globally

gem i omg-attrs

In Gemfile

gem 'omg-attrs'

Locally

# Build gem
gem build omg-attrs.gemspec

# Install gem
gem i -l /path/to/this/folder/omg-attrs-<version>.gem

Or in a Gemfile

gem 'omg-attrs', path: '/path/to/this/folder'

Usage

require 'omg-attrs'

# Given this object:

dad_hash = {
  age: 36,
  hair_color: 'brown',
  children: [
    { age: 4, hair_color: 'blonde' },
    { age: 8, hair_color: 'brown' }
  ],
  wife: { age: 37, hair_color: 'brown' }
}

# Examples

## Single attribute
dad_hash.attrs(:age) # => { age: 36 }

## Multiple attributes, attributes on collections, attributes on items
dad_hash.attrs(wife: :age, children: [:count, :age])
# => {
#   wife: {
#     age: 36
#   },
#   children: {
#     count: 2,
#     items: [
#       { age: 8 },
#       { age: 4 },
#     ],
#   },
# }

## Additional helper methods on Objects
dad_hash.attrs_match?(age: 36, hair_color: 'brown') # => true
dad_hash.children.find_by(age: 4) # => { age: 4, hair_color: 'brown' }
dad_hash.children.where(hair_color: 'brown') # => [{ age: 4, hair_color: 'brown' }]

## COMING SOON: Transformations via procs
dad_hash.attrs(children: [-> { deep_stringify_keys }, -> { sort_by(&:age).reverse }, :age])
[{ 'age' => 8 }, { 'age' => 4 }]

Indifferent access

Development

Installation

bin/install

Console

bin/console

Test

rspec
# or
bundle exec rspec
# or
guard

About

A simple Ruby object/attribute querying tool, kind of like jq.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages