Rename hash keys
If you want to rename a key of a Ruby hash, this could help you out.
Just put it into something like config/initializers/hash_move.rb
.
Related cards:
Enhanced error messages when hash keys are missing
Hash#fetch
is a great way to ensure that a hash key is present. The error message when a key is missing though is rather useless if you don't have immediate access to the object and want to debug why keys are missing, e.g. in the parsed JSON res...
Security issues with hash conditions in Rails 2 and Rails 3
Find conditions for scopes can be given either as an array (:conditions => ['state = ?', 'draft']
) or a hash (:conditions => { 'state' => 'draft' }
). The later is nicer to read, but has horrible security implications in some versions of Ru...
JavaScript: Hash/Object with default value
You can easily have a JavaScript hash/object that returns a default value for unset keys/properties -- as long as you need to support only recent browsers.
The key are [JavaScript proxies](https://developer.mozilla.org/en/docs/Web/JavaScript/Refe...
Infinitely nested hashes in Javascript (Coffeescript)
The NestedHash
class allows you to read and write hashes of any depth. Examples:
hash = {}
NestedHash.write hash, 'a', 'b', 'c', 'value' # => { a: { b: { c: 'value' } } }
NestedHash.read hash, 'a', 'b', 'c' # => 'value'
NestedHash.read hash...
RSpec's hash_including matcher does not support nesting
You can not use the hash_including
argument matcher with a nested hash:
describe 'user' do
let(:user) { {id: 1, name: 'Foo', thread: {...
How to collect a Hash from an Array
There are many different methods that allow mapping an Array to a Hash in Ruby.
Enumerable#index_by
(any Rails)
users = User.all
users_by_id = users.index_by(&:id)
{
1 => #<User id: 1, name: "Alice">,
2 => #<User id...
Test that a hash contains a partial hash with RSpec
To test whether a hash includes an expected sub-hash:
expect(user.attributes).to match(hash_including('name' => 'Bruce Wayne'))
expect(User).to receive(:create!).with(hash_including('name' => 'Bruce Wayne'))
How to fix: Session hash does not get updated when using "merge!"
tl;dr: Do not use merge!
for session hashes. Use update
instead.
Outline
Let's assume you're modifying the Rails session. For simplicity, let's also assume your session is empty when you start (same effect when there is data):
# In o...
Slice a nested hash
The attached initializer gives your hashes a #deep_slice
method that lets you recursively slice their contents by a given whitelist of allowed keys and sub-keys:
{ :a => { ...
Using #deep_dup for copying whole hashes and array
"Everything in Ruby is an object". This is also true for nested hashes and arrays. If you copy a hash with #clone
or #dup
and you modify the copy, you will run into the following behavior:
original_hash = { foo: { bar: 'original value...