Skip to content

Instantly share code, notes, and snippets.

@bswinnerton
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bswinnerton/65df38cd0f1ab95bbff7 to your computer and use it in GitHub Desktop.
Save bswinnerton/65df38cd0f1ab95bbff7 to your computer and use it in GitHub Desktop.
# Toto, we're not in Kansas anymore.
#
# This singleton is used to deeply convert all instances of a String into a
# Symbol given an Array, Hash, or a lonesome String.
module Symbolizer
def self.deep_symbolize(object)
case object
when Array
deep_symbolize_array(object)
when Hash
deep_symbolize_hash(object)
else
symbolize_string(object)
end
end
def self.deep_symbolize_array(array)
array.map { |element| deep_symbolize(element) }
end
def self.deep_symbolize_hash(hash)
hash.each_with_object({}) do |(key, value), symbolized_hash|
symbolized_hash[deep_symbolize(key)] = deep_symbolize(value)
end
end
def self.symbolize_string(string)
string.to_sym
end
end
require 'rspec'
RSpec.describe Symbolizer do
subject(:symbolize) { Symbolizer.deep_symbolize(input) }
context 'string' do
let(:input) { 'kittens' }
it 'converts to a symbol' do
expect(symbolize).to eq :kittens
end
end
context 'hash' do
let(:input) do
{
'names' => ['dee'],
'favorite_colors' => ['blue']
}
end
it 'converts keys to symbols' do
expect(symbolize.keys).to eq [:names, :favorite_colors]
end
it 'converts values to symbols' do
expect(symbolize.values).to eq [[:dee], [:blue]]
end
it 'keeps the structure of the hash' do
expect(symbolize).to eq(
{ names: [:dee], favorite_colors: [:blue] }
)
end
end
context 'array of strings' do
let(:input) { ['dee', 'charlie', 'mac', 'dennis'] }
it 'converts to array of symbols' do
expect(symbolize).to eq [:dee, :charlie, :mac, :dennis]
end
end
context 'array of strings and symbols' do
let(:input) { ['dee', :charlie, 'mac', :dennis] }
it 'converts to array of symbols' do
expect(symbolize).to eq [:dee, :charlie, :mac, :dennis]
end
end
context 'array of strings, symbols and arrays' do
let(:input) { ['dee', :mac, ['charlie', 'dennis']] }
it 'converts to array of arrays with symbols' do
expect(symbolize).to eq [:dee, :mac, [:charlie, :dennis]]
end
end
context 'array of strings, symbols, hashes and arrays' do
let(:input) { ['dee', :mac, ['charlie'], { 'name' => ['dennis'] }] }
it 'converts to array of arrays of symbols and hashes' do
expect(symbolize).to eq([
:dee, :mac, [:charlie], { name: [:dennis] }
])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment