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...
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...
Ruby: How to collect a Hash from an Array
There are many different methods that allow mapping an Array to a Hash in Ruby.
Array#to_h
with a block (Ruby 2.6+)
You can call an array with a block that is called with each element. The block must return a [key, value]
tuple.
This i...
Heads up: Ruby implicitly converts a hash to keyword arguments
When a method has keyword arguments, Ruby offers implicit conversion of a Hash
argument into keyword arguments. This conversion is perfo...
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 => { ...
Comparing Rails' flash hashes will not respect their internal lists of used entries
Rails flashes (FlashHash
) track a list of used keys, which is not respected when comparing flash hashes.
This does not concern you under most circumstances.
Basics
When ActionController
picks up a flash object, it will call the #sweep
m...
PSA: When Redis (on LRU noeviction) reaches memory limits, keys with (any) expiry are removed, and keys without are not
In production, you (or your ops team) should configure a maximum number of bytes that Redis can use to store data (maxmemory
setting).
They may even want to set maxmemory-policy
to noeviction
to avoid keys being removed that you want to keep...
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'))
YAML: Keys like "yes" or "no" evaluate to true and false
If you parse this Yaml ...
yes: 'Totally'
no: 'Nope'
... you get this Ruby hash:
{ true: 'Totally',
false: 'Nope' }
In order to use the strings 'yes' and 'no' as keys, you need to wrap them with quotes:
'yes'...