bit_hash

A simple class that can convert an option hash into a compact string.

Usage

When writing these config maps. Try to put the mose used options first so the string can be shorter.

require 'rubygems'
require 'bit_hash'

config_map = [
  {
    :name => :air,    # name of option
    :options => 2,    # number of options must be 2 or greater
  },
  {
    :name => :color, 
    :options => ['blue','green','red']    # bit_hash can map arrays of data, the default setting will be the first value in the array
  },
  {
    :name => :body_style, 
    :options => [:sedan,:mini_van,:suv],  # Array values can be anything that can be found using the Array#index function
    :default => :mini_van                 # for arrays the default is any array value
  },
  {
    :name => :transmission,     # name of option
    :options => 6,
    :default => 5               # for numbers the default must be between 0 and the options value
  },
  {
    :name => :min_price,
    :options => (50..100).to_a, # ( just a way to store ranges of numbers)
    :default => 60              # basically any default can be used as long as it is a valid option
  },
  {
    :name => :max_price,

    # intervals of 20 starting at 10000 (just a way to store ranges of numbers)
    :options => (1..5).to_a.map {|n| 10000+(n*20)},

    # you can use :default_index option to reference something in the option arrays but it really isn't suggested, :default take precedence
    :default_index =>  2
    }
]

# initialize
@config = BitHash.new(config_map)

# set a single value
@config[:color]='red'

# get a value
@config[:value]

# replace values in config with another hash
@config.replace({:air=>1})

# parse a string without saving
@config.parse('e')

# parse a string and save it
@config.save

# convert to small compact string
@config.to_s

TODO

  • Impliment more tests

  • Clone more Hash functions

  • Storage of strings

  • If binary options and default 1, user inverse

  • allow a hash for config_map for ruby 1.9

  • Add some sort of ActiveRecord extender

Contributing to bit_hash

  • Check out the latest master to make sure the feature hasn’t been implemented or the bug hasn’t been fixed yet

  • Check out the issue tracker to make sure someone already hasn’t requested it and/or contributed it

  • Fork the project

  • Start a feature/bugfix branch

  • Commit and push until you are happy with your contribution

  • Make sure to add tests for it. This is important so I don’t break it in a future version unintentionally.

  • Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

Credits

Ryan Ong - [email protected]

Developed for and with CarZen

Copyright © 2011 Ryan Ong. See LICENSE.txt for further details.