Skip to content
Simple Hash extension to make working with nested hashes (e.g. for configuration) easier and less error-prone.
Branch: master
Clone or download
Latest commit e257624 Apr 12, 2017
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
lib
spec Detect and cast values with int & float defaults Apr 11, 2017
.gitignore
.travis.yml
Gemfile convert to rspec Oct 4, 2015
MIT-LICENSE
README.md re-add env defaults support Oct 4, 2015
hashr.gemspec

README.md

Build Status

Hashr

Hashr is a very simple and tiny class which makes using nested hashes for configuration (and other purposes) easier.

It supports the following features:

  • method read and write access
  • automatic predicate (boolean, i.e. ?) methods
  • easy defaults
  • indifferent (strings vs symbols) keys

Usage

Directly use Hashr instances like this:

config = Hashr.new(foo: { bar: 'bar' })

config.foo?     # => true
config.foo      # => { bar: 'bar' }

config.foo.bar? # => true
config.foo.bar  # => 'bar'

config.foo.bar = 'bar'
config.foo.bar # => 'bar'

config.foo.baz = 'baz'
config.foo.baz # => 'baz'

Hash core methods are not available but assume you mean to look up keys with the same name:

config = Hashr.new(count: 1, key: 'key')
config.count # => 1
config.key   # => 'key'

In order to check a hash stored on a certain key you can convert it to a Ruby Hash:

config = Hashr.new(count: 1, key: 'key')
config.to_h.count # => 2
config.to_h.key   # => raises ArgumentError: "wrong number of arguments (0 for 1)"

Missing keys won't raise an exception but instead behave like Hash access:

config = Hashr.new
config.foo? # => false
config.foo  # => nil

Defaults

Defaults can be defined per class:

class Config < Hashr
  default boxes: { memory: '1024' }
end

config = Config.new
config.boxes.memory # => 1024

Or passed to the instance:

data = {}
defaults = { boxes: { memory: '1024' } }

config = Hashr.new(data, defaults)
config.boxes.memory # => 1024

Environment defaults

Hashr includes a simple module that makes it easy to overwrite configuration defaults from environment variables:

class Config < Hashr
  extend Hashr::Env

  self.env_namespace = 'foo'

  default boxes: { memory: '1024' }
end

Now when an environment variable is defined then it will overwrite the default:

ENV['FOO_BOXES_MEMORY'] = '2048'
config = Config.new
config.boxes.memory # => '2048'

Other libraries

You also might want to check out OpenStruct and Hashie.

  • OpenStruct does less but comes as a Ruby standard library.
  • Hashie has a bunch of support classes (like Mash, Dash, Trash) which all support different features that you might need.

License

MIT License

You can’t perform that action at this time.