Skip to content

Repository files navigation

HashCast

Build StatusGem VersionCode ClimatecodecovDependency Status

HashCast is a library for casting hash attributes

Installation

Add this line to your application's Gemfile:

gem'hashcast'

Usage

Create caster class and declare hash attributes inside:

classContactCasterincludeHashCast::Casterattributesdohash:contactdostring:nameinteger:age,optional: truefloat:weightdate:birthdaydatetime:last_logged_intime:last_visited_athash:companydostring:nameendarray:emails,each: :stringarray:social_accounts,each: :hashdostring:namesymbol:typeendendendend

Instantiate the caster and give your hash for casting:

ContactCaster.cast({contact: {name: "John Smith",age: "22",weight: "65.5",birthday: "2014-02-02",last_logged_in: "2014-02-02 10:10:00",last_visited_at: "2014-02-02 10:10:00",company: {name: "MyCo"},emails: ["test@example.com","test2@example.com"],social_accounts: [{name: "john_smith",type: "twitter"},{name: "John",type: :facebook}]}}})

The caster will cast your hash attributes to:

{contact: {name: "John Smith",age: 22,weight: 65.5,birthday: #<Date: 2014-02-02 ((2456691j,0s,0n),+0s,2299161j)>,last_logged_in: #<DateTime: 2014-02-02T10:10:00+00:00 ((2456691j,36600s,0n),+0s,2299161j)>,last_visited_at: 2014-02-0210:10:00 +0400,company: {name: "MyCo"},emails: ["test@example.com","test2@example.com"],social_accounts: [{name: "john_smith",type: :twitter" }, { name: "John",type: :facebook}]}}

if some of the attributes can't be casted the HashCast::Errors::CastingError is raised

Also you can provide options to every caster about expected keys type for input/output (:symbol / :string)

classSettingsCasterincludeHashCast::Casterattributesdostring:accountendendSettingsCaster.cast({account: "some"},input_keys: :symbol,output_keys: :string)# => {"account" => "some"}

Configuration

# expect all input keys to be stringsHashCast.config.input_keys=:string# expect all output keys to be symbolsHashCast.config.output_keys=:symbol

Authors

About

Hash attributes caster in declarative way

Resources

Stars

7 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages