GithubHelp home page GithubHelp logo

hashie / hashie Goto Github PK

View Code? Open in Web Editor NEW
3.0K 40.0 312.0 1.24 MB

Hashie is a collection of classes and mixins that make Ruby hashes more powerful.

License: MIT License

Ruby 99.95% Shell 0.05%
ruby hash-extensions hacktoberfest

hashie's Introduction

Hashie

Join the chat at https://gitter.im/hashie/hashie Gem Version Build Status

eierlegende Wollmilchsau Hashie is a growing collection of tools that extend Hashes and make them more useful.

Table of Contents

Installation

Hashie is available as a RubyGem:

$ gem install hashie

Stable Release

You're reading the documentation for the next release of Hashie, which should be 5.0.1. The current stable release is 5.0.0.

Hash Extensions

The library is broken up into a number of atomically includable Hash extension modules as described below. This provides maximum flexibility for users to mix and match functionality while maintaining feature parity with earlier versions of Hashie.

Any of the extensions listed below can be mixed into a class by include-ing Hashie::Extensions::ExtensionName.

Logging

Hashie has a built-in logger that you can override. By default, it logs to STDOUT but can be replaced by any Logger class. The logger is accessible on the Hashie module, as shown below:

# Set the logger to the Rails logger
Hashie.logger = Rails.logger

Coercion

Coercions allow you to set up "coercion rules" based either on the key or the value type to massage data as it's being inserted into the Hash. Key coercions might be used, for example, in lightweight data modeling applications such as an API client:

class Tweet < Hash
  include Hashie::Extensions::Coercion
  include Hashie::Extensions::MergeInitializer
  coerce_key :user, User
end

user_hash = { name: "Bob" }
Tweet.new(user: user_hash)
# => automatically calls User.coerce(user_hash) or
#    User.new(user_hash) if that isn't present.

Value coercions, on the other hand, will coerce values based on the type of the value being inserted. This is useful if you are trying to build a Hash-like class that is self-propagating.

class SpecialHash < Hash
  include Hashie::Extensions::Coercion
  coerce_value Hash, SpecialHash

  def initialize(hash = {})
    super
    hash.each_pair do |k,v|
      self[k] = v
    end
  end
end

Coercing Collections

class Tweet < Hash
  include Hashie::Extensions::Coercion
  coerce_key :mentions, Array[User]
  coerce_key :friends, Set[User]
end

user_hash = { name: "Bob" }
mentions_hash= [user_hash, user_hash]
friends_hash = [user_hash]
tweet = Tweet.new(mentions: mentions_hash, friends: friends_hash)
# => automatically calls User.coerce(user_hash) or
#    User.new(user_hash) if that isn't present on each element of the array

tweet.mentions.map(&:class) # => [User, User]
tweet.friends.class # => Set

Coercing Hashes

class Relation
  def initialize(string)
    @relation = string
  end
end

class Tweet < Hash
  include Hashie::Extensions::Coercion
  coerce_key :relations, Hash[User => Relation]
end

user_hash = { name: "Bob" }
relations_hash= { user_hash => "father", user_hash => "friend" }
tweet = Tweet.new(relations: relations_hash)
tweet.relations.map { |k,v| [k.class, v.class] } # => [[User, Relation], [User, Relation]]
tweet.relations.class # => Hash

# => automatically calls User.coerce(user_hash) on each key
#    and Relation.new on each value since Relation doesn't define the `coerce` class method

Coercing Core Types

Hashie handles coercion to the following by using standard conversion methods:

type method
Integer #to_i
Float #to_f
Complex #to_c
Rational #to_r
String #to_s
Symbol #to_sym

Note: The standard Ruby conversion methods are less strict than you may assume. For example, :foo.to_i raises an error but "foo".to_i returns 0.

You can also use coerce from the following supertypes with coerce_value:

  • Integer
  • Numeric

Hashie does not have built-in support for coercing boolean values, since Ruby does not have a built-in boolean type or standard method for coercing to a boolean. You can coerce to booleans using a custom proc.

Coercion Proc

You can use a custom coercion proc on either #coerce_key or #coerce_value. This is useful for coercing to booleans or other simple types without creating a new class and coerce method. For example:

class Tweet < Hash
  include Hashie::Extensions::Coercion
  coerce_key :retweeted, ->(v) do
    case v
    when String
      !!(v =~ /\A(true|t|yes|y|1)\z/i)
    when Numeric
      !v.to_i.zero?
    else
      v == true
    end
  end
end

A note on circular coercion

Since coerce_key is a class-level method, you cannot have circular coercion without the use of a proc. For example:

class CategoryHash < Hash
  include Hashie::Extensions::Coercion
  include Hashie::Extensions::MergeInitializer

  coerce_key :products, Array[ProductHash]
end

class ProductHash < Hash
  include Hashie::Extensions::Coercion
  include Hashie::Extensions::MergeInitializer

  coerce_key :categories, Array[CategoriesHash]
end

This will fail with a NameError for CategoryHash::ProductHash because ProductHash is not defined at the point that coerce_key is happening for CategoryHash.

To work around this, you can use a coercion proc. For example, you could do:

class CategoryHash < Hash
  # ...
  coerce_key :products, ->(value) do
    return value.map { |v| ProductHash.new(v) } if value.respond_to?(:map)

    ProductHash.new(value)
  end
end

KeyConversion

The KeyConversion extension gives you the convenience methods of symbolize_keys and stringify_keys along with their bang counterparts. You can also include just stringify or just symbolize with Hashie::Extensions::StringifyKeys or Hashie::Extensions::SymbolizeKeys.

Hashie also has a utility method for converting keys on a Hash without a mixin:

Hashie.symbolize_keys! hash # => Symbolizes all string keys of hash.
Hashie.symbolize_keys hash # => Returns a copy of hash with string keys symbolized.
Hashie.stringify_keys! hash # => Stringifies keys of hash.
Hashie.stringify_keys hash # => Returns a copy of hash with keys stringified.

MergeInitializer

The MergeInitializer extension simply makes it possible to initialize a Hash subclass with another Hash, giving you a quick short-hand.

MethodAccess

The MethodAccess extension allows you to quickly build method-based reading, writing, and querying into your Hash descendant. It can also be included as individual modules, i.e. Hashie::Extensions::MethodReader, Hashie::Extensions::MethodWriter and Hashie::Extensions::MethodQuery.

class MyHash < Hash
  include Hashie::Extensions::MethodAccess
end

h = MyHash.new
h.abc = 'def'
h.abc  # => 'def'
h.abc? # => true

MethodAccessWithOverride

The MethodAccessWithOverride extension is like the MethodAccess extension, except that it allows you to override Hash methods. It aliases any overridden method with two leading underscores. To include only this overriding functionality, you can include the single module Hashie::Extensions::MethodOverridingWriter.

class MyHash < Hash
  include Hashie::Extensions::MethodAccess
end

class MyOverridingHash < Hash
  include Hashie::Extensions::MethodAccessWithOverride
end

non_overriding = MyHash.new
non_overriding.zip = 'a-dee-doo-dah'
non_overriding.zip #=> [[['zip', 'a-dee-doo-dah']]]

overriding = MyOverridingHash.new
overriding.zip = 'a-dee-doo-dah'
overriding.zip   #=> 'a-dee-doo-dah'
overriding.__zip #=> [[['zip', 'a-dee-doo-dah']]]

MethodOverridingInitializer

The MethodOverridingInitializer extension will override hash methods if you pass in a normal hash to the constructor. It aliases any overridden method with two leading underscores. To include only this initializing functionality, you can include the single module Hashie::Extensions::MethodOverridingInitializer.

class MyHash < Hash
end

class MyOverridingHash < Hash
  include Hashie::Extensions::MethodOverridingInitializer
end

non_overriding = MyHash.new(zip: 'a-dee-doo-dah')
non_overriding.zip #=> []

overriding = MyOverridingHash.new(zip: 'a-dee-doo-dah')
overriding.zip   #=> 'a-dee-doo-dah'
overriding.__zip #=> [[['zip', 'a-dee-doo-dah']]]

IndifferentAccess

This extension can be mixed in to your Hash subclass to allow you to use Strings or Symbols interchangeably as keys; similar to the params hash in Rails.

In addition, IndifferentAccess will also inject itself into sub-hashes so they behave the same.

class MyHash < Hash
  include Hashie::Extensions::MergeInitializer
  include Hashie::Extensions::IndifferentAccess
end

myhash = MyHash.new(:cat => 'meow', 'dog' => 'woof')
myhash['cat'] # => "meow"
myhash[:cat]  # => "meow"
myhash[:dog]  # => "woof"
myhash['dog'] # => "woof"

# Auto-Injecting into sub-hashes.
myhash['fishes'] = {}
myhash['fishes'].class # => Hash
myhash['fishes'][:food] = 'flakes'
myhash['fishes']['food'] # => "flakes"

To get back a normal, not-indifferent Hash, you can use #to_hash on the indifferent hash. It exports the keys as strings, not symbols:

myhash = MyHash.new
myhash["foo"] = "bar"
myhash[:foo]  #=> "bar"

normal_hash = myhash.to_hash
myhash["foo"]  #=> "bar"
myhash[:foo]  #=> nil

IgnoreUndeclared

This extension can be mixed in to silently ignore undeclared properties on initialization instead of raising an error. This is useful when using a Trash to capture a subset of a larger hash.

class Person < Trash
  include Hashie::Extensions::IgnoreUndeclared
  property :first_name
  property :last_name
end

user_data = {
  first_name: 'Freddy',
  last_name: 'Nostrils',
  email: '[email protected]'
}

p = Person.new(user_data) # 'email' is silently ignored

p.first_name # => 'Freddy'
p.last_name  # => 'Nostrils'
p.email      # => NoMethodError

DeepMerge

This extension allows you to easily include a recursive merging system into any Hash descendant:

class MyHash < Hash
  include Hashie::Extensions::DeepMerge
end

h1 = MyHash[{ x: { y: [4,5,6] }, z: [7,8,9] }]
h2 = MyHash[{ x: { y: [7,8,9] }, z: "xyz" }]

h1.deep_merge(h2) # => { x: { y: [7, 8, 9] }, z: "xyz" }
h2.deep_merge(h1) # => { x: { y: [4, 5, 6] }, z: [7, 8, 9] }

Like with Hash#merge in the standard library, a block can be provided to merge values:

class MyHash < Hash
  include Hashie::Extensions::DeepMerge
end

h1 = MyHash[{ a: 100, b: 200, c: { c1: 100 } }]
h2 = MyHash[{ b: 250, c: { c1: 200 } }]

h1.deep_merge(h2) { |key, this_val, other_val| this_val + other_val }
# => { a: 100, b: 450, c: { c1: 300 } }

DeepFetch

This extension can be mixed in to provide for safe and concise retrieval of deeply nested hash values. In the event that the requested key does not exist a block can be provided and its value will be returned.

Though this is a hash extension, it conveniently allows for arrays to be present in the nested structure. This feature makes the extension particularly useful for working with JSON API responses.

user = {
  name: { first: 'Bob', last: 'Boberts' },
  groups: [
    { name: 'Rubyists' },
    { name: 'Open source enthusiasts' }
  ]
}

user.extend Hashie::Extensions::DeepFetch

user.deep_fetch :name, :first # => 'Bob'
user.deep_fetch :name, :middle # => 'KeyError: Could not fetch middle'

# using a default block
user.deep_fetch(:name, :middle) { |key| 'default' }  # =>  'default'

# a nested array
user.deep_fetch :groups, 1, :name # => 'Open source enthusiasts'

DeepFind

This extension can be mixed in to provide for concise searching for keys within a deeply nested hash.

It can also search through any Enumerable contained within the hash for objects with the specified key.

Note: The searches are depth-first, so it is not guaranteed that a shallowly nested value will be found before a deeply nested value.

user = {
  name: { first: 'Bob', last: 'Boberts' },
  groups: [
    { name: 'Rubyists' },
    { name: 'Open source enthusiasts' }
  ]
}

user.extend Hashie::Extensions::DeepFind

user.deep_find(:name)   #=> { first: 'Bob', last: 'Boberts' }
user.deep_detect(:name) #=> { first: 'Bob', last: 'Boberts' }

user.deep_find_all(:name) #=> [{ first: 'Bob', last: 'Boberts' }, 'Rubyists', 'Open source enthusiasts']
user.deep_select(:name)   #=> [{ first: 'Bob', last: 'Boberts' }, 'Rubyists', 'Open source enthusiasts']

DeepLocate

This extension can be mixed in to provide a depth first search based search for enumerables matching a given comparator callable.

It returns all enumerables which contain at least one element, for which the given comparator returns true.

Because the container objects are returned, the result elements can be modified in place. This way, one can perform modifications on deeply nested hashes without the need to know the exact paths.

books = [
  {
    title: "Ruby for beginners",
    pages: 120
  },
  {
    title: "CSS for intermediates",
    pages: 80
  },
  {
    title: "Collection of ruby books",
    books: [
      {
        title: "Ruby for the rest of us",
        pages: 576
      }
    ]
  }
]

books.extend(Hashie::Extensions::DeepLocate)

# for ruby 1.9 leave *no* space between the lambda rocket and the braces
# http://ruby-journal.com/becareful-with-space-in-lambda-hash-rocket-syntax-between-ruby-1-dot-9-and-2-dot-0/

books.deep_locate -> (key, value, object) { key == :title && value.include?("Ruby") }
# => [{:title=>"Ruby for beginners", :pages=>120}, {:title=>"Ruby for the rest of us", :pages=>576}]

books.deep_locate -> (key, value, object) { key == :pages && value <= 120 }
# => [{:title=>"Ruby for beginners", :pages=>120}, {:title=>"CSS for intermediates", :pages=>80}]

StrictKeyAccess

This extension can be mixed in to allow a Hash to raise an error when attempting to extract a value using a non-existent key.

class StrictKeyAccessHash < Hash
  include Hashie::Extensions::StrictKeyAccess
end

>> hash = StrictKeyAccessHash[foo: "bar"]
=> {:foo=>"bar"}
>> hash[:foo]
=> "bar"
>> hash[:cow]
  KeyError: key not found: :cow

Mash

Mash is an extended Hash that gives simple pseudo-object functionality that can be built from hashes and easily extended. It is intended to give the user easier access to the objects within the Mash through a property-like syntax, while still retaining all Hash functionality.

mash = Hashie::Mash.new
mash.name? # => false
mash.name # => nil
mash.name = "My Mash"
mash.name # => "My Mash"
mash.name? # => true
mash.inspect # => <Hashie::Mash name="My Mash">

mash = Hashie::Mash.new
# use bang methods for multi-level assignment
mash.author!.name = "Michael Bleigh"
mash.author # => <Hashie::Mash name="Michael Bleigh">

mash = Hashie::Mash.new
# use under-bang methods for multi-level testing
mash.author_.name? # => false
mash.inspect # => <Hashie::Mash>

Note: The ? method will return false if a key has been set to false or nil. In order to check if a key has been set at all, use the mash.key?('some_key') method instead.

How does Mash handle conflicts with pre-existing methods?

Please note that a Mash will not override methods through the use of the property-like syntax. This can lead to confusion if you expect to be able to access a Mash value through the property-like syntax for a key that conflicts with a method name. However, it protects users of your library from the unexpected behavior of those methods being overridden behind the scenes.

mash = Hashie::Mash.new
mash.name = "My Mash"
mash.zip = "Method Override?"
mash.zip # => [[["name", "My Mash"]], [["zip", "Method Override?"]]]

Since Mash gives you the ability to set arbitrary keys that then act as methods, Hashie logs when there is a conflict between a key and a pre-existing method. You can set the logger that this logs message to via the global Hashie logger:

Hashie.logger = Rails.logger

You can also disable the logging in subclasses of Mash:

class Response < Hashie::Mash
  disable_warnings
end

The default is to disable logging for all methods that conflict. If you would like to only disable the logging for specific methods, you can include an array of method keys:

class Response < Hashie::Mash
  disable_warnings :zip, :zap
end

This behavior is cumulative. The examples above and below behave identically.

class Response < Hashie::Mash
  disable_warnings :zip
  disable_warnings :zap
end

Disable warnings will honor the last disable_warnings call. Calling without parameters will override the ignored methods list, and calling with parameters will create a new ignored methods list. This includes child classes that inherit from a class that disables warnings.

class Message < Hashie::Mash
  disable_warnings :zip, :zap
  disable_warnings
end

# No errors will be logged
Message.new(merge: 'true', compact: true)
class Message < Hashie::Mash
  disable_warnings
end

class Response < Message
  disable_warnings :zip, :zap
end

# 2 errors will be logged
Response.new(merge: 'true', compact: true, zip: '90210', zap: 'electric')

If you would like to create an anonymous subclass of a Hashie::Mash with key conflict warnings disabled:

Hashie::Mash.quiet.new(zip: '90210', compact: true) # no errors logged
Hashie::Mash.quiet(:zip).new(zip: '90210', compact: true) # error logged for compact

How does the wrapping of Mash sub-Hashes work?

Mash duplicates any sub-Hashes that you add to it and wraps them in a Mash. This allows for infinite chaining of nested Hashes within a Mash without modifying the object(s) that are passed into the Mash. When you subclass Mash, the subclass wraps any sub-Hashes in its own class. This preserves any extensions that you mixed into the Mash subclass and allows them to work within the sub-Hashes, in addition to the main containing Mash.

mash = Hashie::Mash.new(name: "Hashie", dependencies: { rake: "< 11", rspec: "~> 3.0" })
mash.dependencies.class #=> Hashie::Mash

class MyGem < Hashie::Mash; end
my_gem = MyGem.new(name: "Hashie", dependencies: { rake: "< 11", rspec: "~> 3.0" })
my_gem.dependencies.class #=> MyGem

How does Mash handle key types which cannot be symbolized?

Mash preserves keys which cannot be converted directly to both a string and a symbol, such as numeric keys. Since Mash is conceived to provide pseudo-object functionality, handling keys which cannot represent a method call falls outside its scope of value.

Hashie::Mash.new('1' => 'one string', :'1' => 'one sym', 1 => 'one num')
# => {"1"=>"one sym", 1=>"one num"}

The symbol key :'1' is converted the string '1' to support indifferent access and consequently its value 'one sym' will override the previously set 'one string'. However, the subsequent key of 1 cannot directly convert to a symbol and therefore not converted to the string '1' that would otherwise override the previously set value of 'one sym'.

What else can Mash do?

Mash allows you also to transform any files into a Mash objects.

#/etc/config/settings/twitter.yml
development:
  api_key: 'api_key'
production:
  api_key: <%= ENV['API_KEY'] %> #let's say that ENV['API_KEY'] is set to 'abcd'
mash = Mash.load('settings/twitter.yml')
mash.development.api_key # => 'localhost'
mash.development.api_key = "foo" # => <# RuntimeError can't modify frozen ...>
mash.development.api_key? # => true

You can also load with a Pathname object:

mash = Mash.load(Pathname 'settings/twitter.yml')
mash.development.api_key # => 'localhost'

You can access a Mash from another class:

mash = Mash.load('settings/twitter.yml')[ENV['RACK_ENV']]
Twitter.extend mash.to_module # NOTE: if you want another name than settings, call: to_module('my_settings')
Twitter.settings.api_key # => 'abcd'

You can use another parser (by default: YamlErbParser):

#/etc/data/user.csv
id | name          | lastname
---|------------- | -------------
1  |John          | Doe
2  |Laurent       | Garnier
mash = Mash.load('data/user.csv', parser: MyCustomCsvParser)
# => { 1 => { name: 'John', lastname: 'Doe'}, 2 => { name: 'Laurent', lastname: 'Garnier' } }
mash[1] #=> { name: 'John', lastname: 'Doe' }

The Mash#load method calls YAML.safe_load(path, [], [], true).

Specify permitted_symbols, permitted_classes and aliases options as needed.

Mash.load('data/user.csv', permitted_classes: [Symbol], permitted_symbols: [], aliases: false)

KeepOriginalKeys

This extension can be mixed into a Mash to keep the form of any keys passed directly into the Mash. By default, Mash converts symbol keys to strings to give indifferent access. This extension still allows indifferent access, but keeps the form of the keys to eliminate confusion when you're not expecting the keys to change.

class KeepingMash < ::Hashie::Mash
  include Hashie::Extensions::Mash::KeepOriginalKeys
end

mash = KeepingMash.new(:symbol_key => :symbol, 'string_key' => 'string')
mash.to_hash == { :symbol_key => :symbol, 'string_key' => 'string' }  #=> true
mash.symbol_key  #=> :symbol
mash[:symbol_key]  #=> :symbol
mash['symbol_key']  #=> :symbol
mash.string_key  #=> 'string'
mash['string_key']  #=> 'string'
mash[:string_key]  #=> 'string'

PermissiveRespondTo

By default, Mash only states that it responds to built-in methods, affixed methods (e.g. setters, underbangs, etc.), and keys that it currently contains. That means it won't state that it responds to a getter for an unset key, as in the following example:

mash = Hashie::Mash.new(a: 1)
mash.respond_to? :b  #=> false

This means that by default Mash is not a perfect match for use with a SimpleDelegator since the delegator will not forward messages for unset keys to the Mash even though it can handle them.

In order to have a SimpleDelegator-compatible Mash, you can use the PermissiveRespondTo extension to make Mash respond to anything.

class PermissiveMash < Hashie::Mash
  include Hashie::Extensions::Mash::PermissiveRespondTo
end

mash = PermissiveMash.new(a: 1)
mash.respond_to? :b  #=> true

This comes at the cost of approximately 20% performance for initialization and setters and 19KB of permanent memory growth for each such class that you create.

SafeAssignment

This extension can be mixed into a Mash to guard the attempted overwriting of methods by property setters. When mixed in, the Mash will raise an ArgumentError if you attempt to write a property with the same name as an existing method.

class SafeMash < ::Hashie::Mash
  include Hashie::Extensions::Mash::SafeAssignment
end

safe_mash = SafeMash.new
safe_mash.zip   = 'Test' # => ArgumentError
safe_mash[:zip] = 'test' # => still ArgumentError

SymbolizeKeys

This extension can be mixed into a Mash to change the default behavior of converting keys to strings. After mixing this extension into a Mash, the Mash will convert all string keys to symbols. It can be useful to use with keywords argument, which required symbol keys.

class SymbolizedMash < ::Hashie::Mash
  include Hashie::Extensions::Mash::SymbolizeKeys
end

symbol_mash = SymbolizedMash.new
symbol_mash['test'] = 'value'
symbol_mash.test  #=> 'value'
symbol_mash.to_h  #=> {test: 'value'}

def example(test:)
  puts test
end

example(symbol_mash) #=> value

There is a major benefit and coupled with a major trade-off to this decision (at least on older Rubies). As a benefit, by using symbols as keys, you will be able to use the implicit conversion of a Mash via the #to_hash method to destructure (or splat) the contents of a Mash out to a block. This can be handy for doing iterations through the Mash's keys and values, as follows:

symbol_mash = SymbolizedMash.new(id: 123, name: 'Rey')
symbol_mash.each do |key, value|
  # key is :id, then :name
  # value is 123, then 'Rey'
end

However, on Rubies less than 2.0, this means that every key you send to the Mash will generate a symbol. Since symbols are not garbage-collected on older versions of Ruby, this can cause a slow memory leak when using a symbolized Mash with data generated from user input.

DefineAccessors

This extension can be mixed into a Mash so it makes it behave like OpenStruct. It reduces the overhead of method_missing? magic by lazily defining field accessors when they're requested.

class MyHash < ::Hashie::Mash
  include Hashie::Extensions::Mash::DefineAccessors
end

mash = MyHash.new
MyHash.method_defined?(:foo=) #=> false
mash.foo = 123
MyHash.method_defined?(:foo=) #=> true

MyHash.method_defined?(:foo) #=> false
mash.foo #=> 123
MyHash.method_defined?(:foo) #=> true

You can also extend the existing mash without defining a class:

mash = ::Hashie::Mash.new.with_accessors!

Dash

Dash is an extended Hash that has a discrete set of defined properties and only those properties may be set on the hash. Additionally, you can set defaults for each property. You can also flag a property as required. Required properties will raise an exception if unset. Another option is message for required properties, which allow you to add custom messages for required property. A property with a proc value will be evaluated lazily upon retrieval.

You can also conditionally require certain properties by passing a Proc or Symbol. If a Proc is provided, it will be run in the context of the Dash instance. If a Symbol is provided, the value returned for the property or method of the same name will be evaluated. The property will be required if the result of the conditional is truthy.

class Person < Hashie::Dash
  property :name, required: true
  property :age, required: true, message: 'must be set.'
  property :email
  property :phone, required: -> { email.nil? }, message: 'is required if email is not set.'
  property :pants, required: :weekday?, message: 'are only required on weekdays.'
  property :occupation, default: 'Rubyist'
  property :genome

  def weekday?
    [ Time.now.saturday?, Time.now.sunday? ].none?
  end
end

p = Person.new # => ArgumentError: The property 'name' is required for this Dash.
p = Person.new(name: 'Bob') # => ArgumentError: The property 'age' must be set.

p = Person.new(name: "Bob", age: 18)
p.name         # => 'Bob'
p.name = nil   # => ArgumentError: The property 'name' is required for this Dash.
p.age          # => 18
p.age = nil    # => ArgumentError: The property 'age' must be set.
p.email = '[email protected]'
p.occupation   # => 'Rubyist'
p.email        # => '[email protected]'
p[:awesome]    # => NoMethodError
p[:occupation] # => 'Rubyist'
p.update_attributes!(name: 'Trudy', occupation: 'Evil')
p.occupation   # => 'Evil'
p.name         # => 'Trudy'
p.update_attributes!(occupation: nil)
p.occupation   # => 'Rubyist'
p.genome = -> { Genome.sequence } # Some expensive operation
p.genome       # => 'GATTACA'

Properties defined as symbols are not the same thing as properties defined as strings.

class Tricky < Hashie::Dash
  property :trick
  property 'trick'
end

p = Tricky.new(trick: 'one', 'trick' => 'two')
p.trick # => 'one', always symbol version
p[:trick] # => 'one'
p['trick'] # => 'two'

Note that accessing a property as a method always uses the symbol version.

class Tricky < Hashie::Dash
  property 'trick'
end

p = Tricky.new('trick' => 'two')
p.trick # => NoMethodError

If you would like to update a Dash and use any default values set in the case of a nil value, use #update_attributes!.

class WithDefaults < Hashie::Dash
  property :description, default: 'none'
end

dash = WithDefaults.new
dash.description  #=> 'none'

dash.description = 'You committed one of the classic blunders!'
dash.description  #=> 'You committed one of the classic blunders!'

dash.description = nil
dash.description  #=> nil

dash.description = 'Only slightly less known is ...'
dash.update_attributes!(description: nil)
dash.description  #=> 'none'

Potential Gotchas

Because Dashes are subclasses of the built-in Ruby Hash class, the double-splat operator takes the Dash as-is without any conversion. This can lead to strange behavior when you use the double-splat operator on a Dash as the first part of a keyword list or built Hash. For example:

class Foo < Hashie::Dash
  property :bar
end

foo = Foo.new(bar: 'baz')      #=> {:bar=>"baz"}
qux = { **foo, quux: 'corge' } #=> {:bar=> "baz", :quux=>"corge"}
qux.is_a?(Foo)                 #=> true
qux[:quux]
#=> raise NoMethodError, "The property 'quux' is not defined for Foo."
qux.key?(:quux) #=> true

You can work around this problem in two ways:

  1. Call #to_h on the resulting object to convert it into a Hash.
  2. Use the double-splat operator on the Dash as the last argument in the Hash literal. This will cause the resulting object to be a Hash instead of a Dash, thereby circumventing the problem.
qux = { **foo, quux: 'corge' }.to_h #=> {:bar=> "baz", :quux=>"corge"}
qux.is_a?(Hash)                     #=> true
qux[:quux]                          #=> "corge"

qux = { quux: 'corge', **foo } #=> {:quux=>"corge", :bar=> "baz"}
qux.is_a?(Hash)                #=> true
qux[:quux]                     #=> "corge"

PropertyTranslation

The Hashie::Extensions::Dash::PropertyTranslation mixin extends a Dash with the ability to remap keys from a source hash.

Property translation is useful when you need to read data from another application -- such as a Java API -- where the keys are named differently from Ruby conventions.

class PersonHash < Hashie::Dash
  include Hashie::Extensions::Dash::PropertyTranslation

  property :first_name, from: :firstName
  property :last_name, from: :lastName
  property :first_name, from: :f_name
  property :last_name, from: :l_name
end

person = PersonHash.new(firstName: 'Michael', l_name: 'Bleigh')
person[:first_name]  #=> 'Michael'
person[:last_name]   #=> 'Bleigh

You can also use a lambda to translate the value. This is particularly useful when you want to ensure the type of data you're wrapping.

class DataModelHash < Hashie::Dash
  include Hashie::Extensions::Dash::PropertyTranslation

  property :id, transform_with: ->(value) { value.to_i }
  property :created_at, from: :created, with: ->(value) { Time.parse(value) }
end

model = DataModelHash.new(id: '123', created: '2014-04-25 22:35:28')
model.id.class          #=> Integer (Fixnum if you are using Ruby 2.3 or lower)
model.created_at.class  #=> Time

Mash and Rails 4 Strong Parameters

To enable compatibility with Rails 4 use the hashie-forbidden_attributes gem.

Coercion

If you want to use Hashie::Extensions::Coercion together with Dash then you may probably want to use Hashie::Extensions::Dash::Coercion instead. This extension automatically includes Hashie::Extensions::Coercion and also adds a convenient :coerce option to property so you can define coercion in one line instead of using property and coerce_key separate:

class UserHash < Hashie::Dash
  include Hashie::Extensions::Coercion

  property :id
  property :posts

  coerce_key :posts, Array[PostHash]
end

This is the same as:

class UserHash < Hashie::Dash
  include Hashie::Extensions::Dash::Coercion

  property :id
  property :posts, coerce: Array[PostHash]
end

PredefinedValues

The Hashie::Extensions::Dash::PredefinedValues mixin extends a Dash with the ability to accept predefined values on a property.

class UserHash < Hashie::Dash
  include Hashie::Extensions::Dash::PredefinedValues

  property :gender, values: %i[male female prefer_not_to_say]
  property :age, values: (0..150)
end

Trash

A Trash is a Dash that allows you to translate keys on initialization. It mixes in the PropertyTranslation mixin by default and is used like so:

class Person < Hashie::Trash
  property :first_name, from: :firstName
end

This will automatically translate the firstName key to first_name when it is initialized using a hash such as through:

Person.new(firstName: 'Bob')

Trash also supports translations using lambda, this could be useful when dealing with external API's. You can use it in this way:

class Result < Hashie::Trash
  property :id, transform_with: lambda { |v| v.to_i }
  property :created_at, from: :creation_date, with: lambda { |v| Time.parse(v) }
end

this will produce the following

result = Result.new(id: '123', creation_date: '2012-03-30 17:23:28')
result.id.class         # => Integer (Fixnum if you are using Ruby 2.3 or lower)
result.created_at.class # => Time

Clash

Clash is a Chainable Lazy Hash that allows you to easily construct complex hashes using method notation chaining. This will allow you to use a more action-oriented approach to building options hashes.

Essentially, a Clash is a generalized way to provide much of the same kind of "chainability" that libraries like Arel or Rails 2.x's named_scopes provide.

c = Hashie::Clash.new
c.where(abc: 'def').order(:created_at)
c # => { where: { abc: 'def' }, order: :created_at }

# You can also use bang notation to chain into sub-hashes,
# jumping back up the chain with _end!
c = Hashie::Clash.new
c.where!.abc('def').ghi(123)._end!.order(:created_at)
c # => { where: { abc: 'def', ghi: 123 }, order: :created_at }

# Multiple hashes are merged automatically
c = Hashie::Clash.new
c.where(abc: 'def').where(hgi: 123)
c # => { where: { abc: 'def', hgi: 123 } }

Rash

Rash is a Hash whose keys can be Regexps or Ranges, which will map many input keys to a value.

A good use case for the Rash is an URL router for a web framework, where URLs need to be mapped to actions; the Rash's keys match URL patterns, while the values call the action which handles the URL.

If the Rash's value is a proc, the proc will be automatically called with the regexp's MatchData (matched groups) as a block argument.

# Mapping names to appropriate greetings
greeting = Hashie::Rash.new( /^Mr./ => "Hello sir!", /^Mrs./ => "Evening, madame." )
greeting["Mr. Steve Austin"] # => "Hello sir!"
greeting["Mrs. Steve Austin"] # => "Evening, madame."

# Mapping statements to saucy retorts
mapper = Hashie::Rash.new(
  /I like (.+)/ => proc { |m| "Who DOESN'T like #{m[1]}?!" },
  /Get off my (.+)!/ => proc { |m| "Forget your #{m[1]}, old man!" }
)
mapper["I like traffic lights"] # => "Who DOESN'T like traffic lights?!"
mapper["Get off my lawn!"]      # => "Forget your lawn, old man!"

Auto-Optimized

Note: The Rash is automatically optimized every 500 accesses (which means that it sorts the list of Regexps, putting the most frequently matched ones at the beginning).

If this value is too low or too high for your needs, you can tune it by setting: rash.optimize_every = n.

Mascot

eierlegende Wollmilchsau Meet Hashie's "official" mascot, the eierlegende Wollmilchsau!

Contributing

See CONTRIBUTING.md

Copyright

Copyright (c) 2009-2020 Intridea, Inc., and contributors.

MIT License. See LICENSE for details.

hashie's People

Contributors

7even avatar andrehjr avatar aried3r avatar arthwood avatar benschwarz avatar biinari avatar bobbymcwho avatar boffbowsh avatar camelmasa avatar dblock avatar erol avatar fabn avatar gregory avatar jch avatar jimeh avatar jrochkind avatar koic avatar markiz avatar marshall-lee avatar maxim-filimonov avatar maxlinc avatar mbleigh avatar michaelherold avatar mislav avatar msievers avatar pboling avatar petergoldstein avatar sazor avatar steved avatar teliosdev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hashie's Issues

Coercion problems with Hashie::Mash

I noticed the Coercion extension recently added to hashie, and think it's a great idea. However, I've had some problems getting it to play nice with Hashie::Mash. For example, given these class definitions:

class User < Hashie::Mash
end

class Tweet < Hashie::Mash
  include Hashie::Extensions::Coercion
  coerce_key :user, User
end

If I create a new Tweet, passing a :user hash, coercion is not done; I end up with an embedded Tweet instance:

> tweet = Tweet.new(:msg => 'Hello', :user => {:email => '[email protected]'})
 => #<Tweet msg="Hello" user=#<Tweet email="[email protected]">> 

Setting user via attribute reference (via Hashie::Mash#method_missing) does the same:

> tweet.user = {:email => '[email protected]'}
 => {:email=>"[email protected]"} 
> tweet
 => #<Tweet msg="Hello" user=#<Tweet email="[email protected]">>

As does string-indexing:

> tweet['user'] = {:email => '[email protected]'}
 => {:email=>"[email protected]"}
> tweet
 => #<Tweet msg="Hello" user=#<Tweet email="[email protected]">>

However, with symbolic indexing, coercion does work as expected, and the embedded user object becomes a User instance:

> tweet[:user] = {:email => '[email protected]'}
 => {:email=>"[email protected]"} 
> tweet
 => #<Tweet msg="Hello" user=#<User email="[email protected]">>

I think it would be awesome if coercion worked with the other key-indexing methods (attribute, string, and initialize-based attributes) in addition to symbolic-key indexing, but I do wonder if there's a technical or compatibility reason this is not already the case. Is there?

If not, would there be any objection to me implementing this and submitting a pull request?

beta gem

Can you release a beta gem with a developer version to rubygems.org, so that the 2.0 version can be used with a simple gemfile entry?

Thanks...

Fixed and optimized Dash

I noticed Dash code is dangerously unoptimized and that tests are lacking. Fixed in my forkโ€”full explanation in related commit.

Because this changes the return values of properties and defaults class methods, it might not be a good idea for a patch release, but might be a good fit for 0.4.0

Hashie::to_hash argument options

Seems you removed the argument in the to_hash method, which cause other Gems to break (e.g. the Omniauth, when trying Facebook connect)

#replace method not working as expected.

I'm using Hashie::Mash (v1.2.0) to create a couple custom inheritable "results" classes which are used like hashes with extra logic attached to it.

I came across an issue with the #replace method. Namely it doesn't act as it does for a normal Hash. Old keys seems to be removed, and new ones added, but all values are nil, and the #key_name? helper methods all return false.

I couldn't find any issues reported about the #replace method, and it doesn't seem defined within Hashie. I don't have time right now to properly familiarize myself with the codebase and submit a pull request. I'll have time in the next few days though if that's preferred :)

For the time being, here's the quick work-around I threw into my own base-class:

def replace(hash)
  (keys - hash.keys).each { |key| delete(key) }
  hash.each { |key, value| self[key] = value }
end

Mash#fetch with no default and Mash#fetch with nil default are different cases

Using hashie 2.0.3

1.9.3p392 :001 > require 'hashie'
true
1.9.3p392 :002 > h = Hashie::Mash.new
{}
1.9.3p392 :003 > h.fetch(:a, nil)
KeyError: key not found: :a

Expected: nil (consistent with what ruby Hash does)
Got: KeyError

Suggested solution: either use *args and count number of arguments or use some singleton object for NO_VALUE constant case instead of nil.
Also possible: transform first argument and use super a-la HashExtensions::IndifferentAccess.

Workaround for current version: use block defaults

Hashie::Mash doesn't play well with Rails and strong_parameters

I upgraded an app from Hashie::Mash 1.2 to 2.0 and I started to notice an incompatibility when using strong_parameters (thus Rails 4).

Have a look at the following example:

settings = { foo: "1", attributes: { title: "Value" } } 

# Mash 1.2
record.attributes = settings.attributes
# it works

# Mash 2.x
record.attributes = settings.attributes
# raises ActiveModel::ForbiddenAttributes

This happens because in the 2.x version, when a key is a Hash, it is automatically converted into a Mash.

The Mash instance responds to :permit? thus it triggers the ActiveModel forbidden attribute check.

  module ForbiddenAttributesProtection
    def sanitize_for_mass_assignment(*options)
      new_attributes = options.first
      if !new_attributes.respond_to?(:permitted?) || new_attributes.permitted?
        super
      else
        raise ActiveModel::ForbiddenAttributes
      end
    end
  end

But because there is no attribute permit, then #permit? returns false and the error is raised.

Is it intentional? Any suggestion? Any chance that the implementation of Hashie::Mash#respond_to? would not return true for #attribute? unless attribute exists in the Mash table?

Hashie::Trash not working?

I'm on OS X 10.8.2 running RVM 1.16.11 with Ruby 1.9.3p194 and Hashie::Trash does not work for me at all.

This is my irb input and output, straight from the examples in the README:

1.9.3-p194 :001 > require 'hashie'
 => true 
1.9.3-p194 :002 > class Result < Hashie::Trash
1.9.3-p194 :003?>     property :id, :transform_with => lambda { |v| v.to_i }
1.9.3-p194 :004?>     property :created_at, :from => :creation_date, :with => lambda { |v| Time.parse(v) }
1.9.3-p194 :005?>   end
 => nil 
1.9.3-p194 :006 > 
1.9.3-p194 :007 >   result = Result.new(:id => '123', :creation_date => '2012-03-30 17:23:28')
 => #<Result created_at="2012-03-30 17:23:28" id="123"> 
1.9.3-p194 :008 > result.id.class         # => Fixnum
 => String 
1.9.3-p194 :009 > result.created_at.class # => Time
 => String 

Require structure?

Um, with the gem, how do I require the extensions . . . should the autoload bring everything in? This doesn't seem to work.

  require 'hashie'
  require 'hashie/hash_extensions'

  class IndifferentHash < Hash
    include Hashie::Extensions::IndifferentAccess
    include Hashie::Extensions::MergeInitializer
  end

Produces:

  in `<class:IndifferentHash>': uninitialized constant Hashie::Extensions (NameError)

(I'm sure this is obvious. Even if it is, it might be something to add to the readme.)

Behavior of mash.foo?

Not sure if this is the recommended place to leave issues as no one's left any, but I'll try anyway...

I noticed that saying mash.foo? only checks to see whether foo exists in mash. I'm using Mash to wrap query results (array of hashes) and it would be more intuitive in my case for mash.foo? to also check if foo is a truthy value like ActiveRecord does (technically, return value.present?). I wonder if you guys think this would be useful too. I realize this would break people's code if they aren't expecting this behavior, but I figure I'd ask anyway.

Inheriting from a Hashie::Dash based class

Consider the following:
class A < Hashie::Dash
property :id
end
A.new # works

 class B < A
 end

 B.new # boom! 
 NoMethodError: undefined method `collect' for nil:NilClass

Hashie::Dash does not accept properties that end in bang ("!")

In version 2.0.5 on master branch

class Example < Hashie::Dash
  property :bang!
end

throws and error (at least in rubys 1.9.3 and 1.8.7), something about

SyntaxError: (eval):5: syntax error, unexpected tNEQ, expecting ';' or '\n'
def bang!=(value)
^
(eval):7: syntax error, unexpected keyword_end, expecting $end

My understanding is that tNEQ relates to the not equal operator ("!=").

I think that this is because Dash.property relies on class_eval "def ..." to define methods, and could be solved by using ruby's #define_method.

I will submit a pull request soon.

Hashie::Mash#dup blindly tries to initialize subclasses with two arguments.

The fix for #1 caused some unfortunate side effects that breaks subclasses of Hashie::Mash that override initialize to take different parameters than Hashie::Mash. (Specifically, I encountered this issue within Redfinger's link.rb )

class Foo < Hashie::Mash
  def initialize(message)
    self[:message] = message
  end
end

f = Foo.new('hello')
f.dup

yields

ArgumentError: wrong number of arguments (2 for 1)
    from [...]/hashie-1.0.0/lib/hashie/mash.rb:97:in `initialize'
    from [...]/hashie-1.0.0/lib/hashie/mash.rb:97:in `new'
    from [...]/hashie-1.0.0/lib/hashie/mash.rb:97:in `dup'
    [snip]

because Hashie::Mash redefines dup as

alias_method :regular_dup, :dup
def dup
  self.class.new(self, self.default)
end

Reserved words

Hi,

Here is an example :

h = Hashie::Mash.new({:size => 10, :count => 5})
# => {"count"=>5, "size"=>10}
h.size
# => 2
h.count
# => 2
h[:size]
# => 10
h[:count]
# => 5

Is there a generic way to use the method way without the risk of hitting "native" Ruby methods ?

PS : Thank you very much for making and maintaining Hashie. I love it and appreciate your effort.

does symbolize_keys not work in ruby 1.9?

In hashie 1.2, when updating my app to ruby 1.9.2, hashie is no longer symbolizing keys correctly. It seems pretty unlikely that there would be such a big difference in behavior but I can't find any other explanation, and some commits between head and 1.2 seem to be regarding this. (i'm not very familiar with the hashie code, it's used by a library i'm using)

Is there a workaround for 1.2 to solve this problem?

Perhaps the difference in behavior should be documented in the readme?

Thanks!

Provide an easy way to get `NoMethodError` instead of `nil` on undefined keys.

My request is similar to #17. Hashie::Mash, out of the box, doesn't provide a way to distinguish between a fat-fingered/typo'd key and a key that exists but is set to nil. I saw @mbleigh's comment on #17 saying that Hashie::Mash is meant to work like a hash, and since that's how a hash works, that's how a Hashie::Mash works. I get that. The suggested he suggested in that thread works OK for flat hash but falls apart once you start working with nested hashes:

1.9.3p194 :001 > require 'hashie/mash'
 => true 
1.9.3p194 :002 > h = Hashie::Mash.new('a' => { 'b' => 3 }) { raise NoMethodError }
 => #<Hashie::Mash a=#<Hashie::Mash b=3>> 
1.9.3p194 :003 > h.a
 => #<Hashie::Mash b=3> 
1.9.3p194 :004 > h.a.c
 => nil 
1.9.3p194 :005 > h.b
NoMethodError: NoMethodError
    from (irb):2:in `block in irb_binding'
    from /Users/myron/code/interpol/bundle/ruby/1.9.1/gems/hashie-1.2.0/lib/hashie/mash.rb:173:in `yield'
    from /Users/myron/code/interpol/bundle/ruby/1.9.1/gems/hashie-1.2.0/lib/hashie/mash.rb:173:in `default'
    from /Users/myron/code/interpol/bundle/ruby/1.9.1/gems/hashie-1.2.0/lib/hashie/mash.rb:173:in `method_missing'
    from (irb):5
    from /Users/myron/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'

I came up with a version that does work, but it feels like a lot of code for something that should be simpler:

require 'hashie/mash'

module Interpol
  module DynamicStruct
    DEFAULT_PROC = lambda do |hash, key|
      raise NoMethodError, "undefined method `#{key}' for #{hash.inspect}"
    end 

    def self.new(source)
      hash = Hashie::Mash.new(source)
      recursively_freeze(hash)
      hash
    end 

    def self.recursively_freeze(object)
      case object
        when Array
          object.each { |obj| recursively_freeze(obj) }
        when Hash
          object.default_proc = DEFAULT_PROC
          recursively_freeze(object.values)
      end 
    end 
  end 
end

On top of that, it took me several hours to come up with this working version; I had several previous attempts that did things like subclass Hashie::Mash but I kept getting errors on instantiation that I couldn't work around. This version I've come up with also suffers from a potential perf issue: it has to walk the entire nested hash tree to ensure every level gets this behavior.

Ideally, I'd love if Hashie supported one of these two things out of the box:

# A subclass of `Hashie::Mash` that raises errors on undefined keys.
mash = Hashie::ConservatieMash.new("a" => { "b" => 3 }) # or some better name

# ...or, have `Hashie::Mash` propogate the default proc to all levels of the hash (including to hashes w/in nested arrays)
mash = Hashie::Mash.new("a" => { "b" => 3 }) { raise NoMethodError }

JSON.generate: undefined method `merge'

> mash = Hashie::Mash.new
> mash[:name] = 'asd'
> JSON.generate(mash)
NoMethodError: undefined method `merge' for #<JSON::Ext::Generator::State:0x4e392db8>

No worries however, for there is #to_json

Regular Hash#update doesn't work with Dash

Hi, could you help to explain why this spec is failing? I almost broke my mind, but cannot find the cause.

diff --git a/spec/hashie/dash_spec.rb b/spec/hashie/dash_spec.rb
index 2de5490..b2e37cd 100644
--- a/spec/hashie/dash_spec.rb
+++ b/spec/hashie/dash_spec.rb
@@ -27,6 +27,11 @@ describe DashTest do
     subject.email = '[email protected]'
     subject.inspect.should == '<#DashTest count=0 email="[email protected]" first_name="Bob">'
   end
+
+  it 'update properties with regular Hash#update method' do
+    subject.update(:first_name => 'Bob', :email => '[email protected]')
+    subject.inspect.should == '<#DashTest count=0 email="[email protected]" first_name="Bob">'
+  end

   its(:count) { should be_zero }

Add DSL-like functionality

This looks really ugly:

c = Hashie::Clash.new.where!.abc('def').ghi(123)._end!.order(:created_at)

I realized that you could do this:

c = Hashie::Clash.new.instance_eval do
  where!.instance_eval do
    abc 'def'
    ghi 123
  end
  order :created_at
end

Would it be possible to make it so you can write code like this?

c = Hashie::Clash.new do
  where do
    abc 'def'
    ghi 123
  end
  order :created_at
end

Also, would it be possible to put Mash and Clash together in something separate, with this functionality?

Dash with default hash will use singleton shared amongst all instances

Here's a simple test case:

require 'hashie'
class Foobar < Hashie::Dash
  property :b, default: Hash.new
end

a = Foobar.new
a.b[:bar] = 'cat'

b = Foobar.new

I'd expect b to be {}, but actually is {b: { bar: 'cat'}}

Deferred defaults (issue #34) would help, but the default objects should probably be cloned by each new instance.

Prettyprint better

How can we get hashies to prettyprint better, the way pp(rubu_hash) does?

Accessing a key named 'key' throws an error

I get an argumentError when trying to access a key named key in a hash I'm using. I've looked through the documentation, and it's looking like I'm out of luck right now. Is there any way around this that I haven't found yet?

Hashie::Mash deep_merge is super O(2^n) slow

Mash's deep_merge is recursively invoked 2^n times, where n is the depth of the other_hash parameter. For instance,

 x = Hashie::Mash.new()
 x.a!.b!.c!.d!.e!.f!.g!.h!.i!.j!.k!.l!.m!.n!.o!.p!.q!.r!.s!.t = 0
 y = Hashie::Mash.new(x)

...will call deep_merge over a million times (2^20), taking 10-15 seconds to complete.

I've made an a O(n) fix in which deep_merge is only invoked 20 times for the above example, with sub-millisecond response. Will submit a pull request momentarily.

to_hash does not recurse into arrays

In version 2.0.5, master branch

to_hash should be symmetric with the recursive construction of Mash objects.

> Hashie::Mash.new({:key => [{}]})
=> #<Hashie::Mash key=[#<Hashie::Mash>]>

>_.to_hash
=> {"key"=>[#<Hashie::Mash>]}

I think that calling to_hash should recurse into arrays, so that the result for the example above would be
=> {"key"=>[{}]}

alternatively, there could be a #deep_to_hash method or something that recurses appropriately.

Use of fetch() method with Mash

With Ruby's standart Hash you can use fetch method to fetch key or get a KeyError exception if the key does not exist.

Like this:

hash = { :one => 1 }
hash.fetch(:one)  # => 1
hash.fetch(:two)  # => KeyError: key not found: :two

However, you can not do this with Mash:

require 'hashie'
mash = Hashie::Mash.new(:one => 1)
mash.fetch(:one)  # => KeyError: key not found: :one
mash.fetch(:two)  # => KeyError: key not found: :two
mash.fetch("one") # => 1

Irb example:

irb(main):001:0> require 'hashie'
=> true
irb(main):002:0> mash = Hashie::Mash.new(:one => 1)
=> #<Hashie::Mash one=1>
irb(main):003:0> mash.fetch(:one)
KeyError: key not found: :one
        from ...
irb(main):004:0> mash.fetch(:two)
KeyError: key not found: :two
        from ...
irb(main):005:0> mash.fetch("one")
=> 1

Docs here: http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-fetch

Can you plaese fix the behavior of fetch method?

Why should Hashie alwasy take a back seat?

The protective #included in HashExtensions seems like overkill to me. This code:

    def self.included(base)
      # Don't tread on existing extensions of Hash by
      # adding methods that are likely to exist.
      %w(stringify_keys stringify_keys!).each do |hashie_method|
        base.send :alias_method, hashie_method, "hashie_#{hashie_method}" unless base.instance_methods.include?(hashie_method)
      end
    end

It basically means that Hashie's extensions always take a backseat to any other library's extensions. What if I want Hashie's to take precedence? If you left the above code out I could decide which extensions take precedence by the order in which I load them.

Custom ArgumentError messages for Dash

It would be nice to provide custom errors messages so that:

ArgumentError: The property 'req_attr' is required for this Dash.

could be made into something like:

ArgumentError: The property 'req_attr" is required for the credentials hash.

Seems like it could be done as simple as:

class Credentials < Hashie::Dash
  property :req_attr, :required =>  true, :message => "is required for the credentials hash"
end

or something like that. Just an idea...

Strange Key Behavior

This one is kind of weird. I'm not sure what the issue is, other than when I try and access a method on a Mash, it responds strangely.

For example:

a = order.billing_address
=> #<Hashie::Mash address1="1234 Roslyn Road" address2="" city="Some Harbor" company="" country="United States" country_code="US" first_name="Joe" last_name="Public" latitude="42.14955" longitude="-86.349679" name="Joe Public" phone="555-555-1212" province="Michigan" province_code="MI" zip="49000"> 

a.city
=> "Some Harbor" 

a.zip
=> [[["address1", "1234 Roslyn Road"]], [["address2", ""]], [["city", "Some Harbor"]], [["company", ""]], [["country", "United States"]], [["first_name", "Joe"]], [["last_name", "Public"]], [["latitude", "42.14955"]], [["longitude", "-86.349679"]], [["phone", "555-555-1212"]], [["province", "Michigan"]], [["zip", "49000"]], [["name", "Joe Public"]], [["country_code", "US"]], [["province_code", "MI"]]]

As you can see, for some reason the zip attribute returns an array or everything in the Mash. Is this just a naming thing? Any ideas about what might be causing this?

Thanks for your help.

Objects that extend Hashie::Mash get turned back into Hashie::Mash objects upon assignment

hi, love the gem, but i found a small problem:

steps to reproduce:

irb(main):003:0> require 'hashie'
=> true
irb(main):004:0> class Record < Hashie::Mash
irb(main):005:1> end
=> nil
irb(main):006:0> r = Record.new
=> <#Record>
irb(main):007:0> r.child = Record.new
=> <#Record>
irb(main):008:0> r
=> <#Record child=<#Hashie::Mash>>

expected behavior: r.child would not get transformed back into a Hashie::Mash object.

Initialize being called extraneously

$ irb -r rubygems -r hashie
irb(main):001:0> class X < Hashie::Mash
irb(main):002:1> def initialize(*options)
irb(main):003:2>   puts "x"
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> x=X.new
x
x
=> <#X>
irb(main):007:0> x
x
=> <#X>
irb(main):008:0> x
x
=> <#X>

Happens with version 0.3.1 and above.

Support for respond_to?

Mash returns false for respond_to?(:key) even when defined in Hash. Perhaps a respond_to? should be implemented. Something like this:

def self.respond_to?(method_sym, include_private = false)
if key?(method_sym)
return true
else
super
end
end

Issue/question with nested hashes/arrays

Hi,

Using Hashie 1.0.0

I appologize if this is the worse issue or question ever ahead of time. But has anyone else reported an issue with Hashie incorrectly merging nested records to json?
I have an application where I've been using hashie to make a very large object consisting of nested arrays and other hashes. Everything looks fine, but when I send the hash over the wire, the params on the other side are incorrectly placed.

The hash is something like the following
{ :company => {:some_attribute => "foo", :some_nested_array => [{:x => 1, :y => 2}, {:x => 3, :z => 4}]}}

The params on the server side will have :some_nested_array => [{:x => 1, :y => 2, :z => 4}, {:x => 3}]

Was this a known issue, and possibly fixed? Or has anyone else come across this?

'h[:key] = []' returns [] but stores _copy of_ [] so '(h[:key] ||= []) << value' doesn't work

(h[:key] ||= []) << value
doesn't work - it loses the first value - because, unlike Hash, Hashies return the value passed in but don't store that value if it's an array or hash.

It would work if Hashies returned the converted value. I don't know if that would break anything else.

This is a nice compact idiom and it's a shame we can't use it - and it's a bit subtle to debug.

Mash and object_id

on ruby 1.9.3 and latest Hashie I get this message :
hashie/mash.rb:80: warning: redefining `object_id' may cause serious problems

This happend in irb or with rubymine

Seems to work but affect debugging in Rubymine

If i'm only using mash, suppressing this method seems not to affect the program;

So I need a little help

my code is

# encoding: utf-8

require 'hashie/mash'

class AppConfig

  class ConfigError < StandardError;
  end

  attr_reader :config
  # load the configuration file
  def initialize(env)
    @config = Hashie::Mash.new YAML::load_file(File.join(APP_ROOT, 'config.yml'))[env]
    unless @config
      App.log("Environment '#{env}' not found in config file. Aborting!", Logger::FATAL)
      raise ConfigError
    end
  end

end

Default block doesn't recurse

>> h = Hashie::Mash.new({:foo => {}}){raise 'missing method'}
=> <#Hashie::Mash foo=<#Hashie::Mash>>
>> h.foo
=> <#Hashie::Mash>
>> h.bar
RuntimeError: missing method
>> h.foo.bar
=> nil

I believe that last line should throw an exception.

Extend Dash to accept only predefined values

Hey,

I was wanting the ability to pass a method, collection, or lambda/proc to a hashie property. What it should do is limit the options that the property can take.

property :gender, options: [:male, :female, :meat_popsicle]
property :age, options: age_range
property :hair_color, options: ->{ hex_color? }

def age_range
18...25
#more logic, I guess
end

Or something similar.

Version differences

I have two gems that require different versions of hashie. If I change the dependency to the current version, will these gems break?

Essentially, are new versions of hashie backward compatible with old one?

Bundler could not find compatible versions for gem "hashie":
In Gemfile:

congress (>= 0) ruby depends on
  hashie (~> 1.0.0) ruby

transparency_data (~> 0.0.4) ruby depends on
  hashie (0.2.0)

Mash#fetch doesn't respect existing keys

Hashie 2.0.3

1.9.3p392 :001 > require 'hashie'
true
1.9.3p392 :002 > h = Hashie::Mash.new
{}
1.9.3p392 :003 > h[:key] = nil
nil
1.9.3p392 :004 > h.fetch(:key, 123)
123

Expected: nil (consistent with what ruby Hash does)
Got: 123

fetch should check, whether key is present in the Mash.

falsy values are values like any other.

deep_merge throws an exception when it encounters integers

require 'hashie'

class Hash
  include Hashie::Extensions::DeepMerge
end

{ x: 1 }.deep_merge({ x: 1})

Expected results: { x: 1 }

Actual results:

TypeError: can't define singleton
    from /Users/jkeiser/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/hashie-2.0.5/lib/hashie/extensions/deep_merge.rb:14:in `block in deep_merge!'
    from /Users/jkeiser/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/hashie-2.0.5/lib/hashie/extensions/deep_merge.rb:13:in `each'
    from /Users/jkeiser/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/hashie-2.0.5/lib/hashie/extensions/deep_merge.rb:13:in `deep_merge!'
    from /Users/jkeiser/.rbenv/versions/1.9.3-p125/lib/ruby/gems/1.9.1/gems/hashie-2.0.5/lib/hashie/extensions/deep_merge.rb:7:in `deep_merge'
    from (irb):13
    from /Users/jkeiser/.rbenv/versions/1.9.3-p125/bin/irb:12:in `<main>'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.