SimpleSymbolize takes a string and transforms it into a symbol. Why? Because working with symbols in Ruby makes for a good time.
Wait, doesn't String already have a to_sym
method?
Correct! However, this gem takes it one step further by transforming special characters and whitespace to give you a simple easy to work with Symbol.
It works by removing special characters in a String like '!'
and underscoring any whitespace.
# to_sym
'hello world!'.to_sym # => :"hello world!"
# Symbolize gem
'hello world!'.simple_symbolize # => :hello_world
Add this line to your application's Gemfile:
gem 'simple_symbolize'
And then execute:
$ bundle install
Or install it yourself as:
$ gem install simple_symbolize
There are two ways to symbolize your String.
require 'simple_symbolize'
SimpleSymbolize.symbolize('hello world!') # => :hello_world
require 'simple_symbolize'
String.include SimpleSymbolize::CoreExt::String
'hello world!'.simple_symbolize # => :hello_world
Something not underscored or removed? Or even something underscored/removed that you didn't want transformed?
No sweat, you can configure this gem to underscore and remove to your hearts content!
SimpleSymbolize.translate do |trans|
trans.to_underscore = '!'
trans.to_remove = ' '
trans.to_omit = '@'
end
SimpleSymbolize is safe to use with other gems, particularly the popular ActiveSupport gem which SimpleSymbolize use to share certain methods names with.
You now need to deliberatly mixin the methods on the String class:
String.include SimpleSymbolize::CoreExt::String
To make them easier to spot, the method names on the String class have been prefixed with simple_
to avoid confusion.
'Hello World!'.simple_symbolize #=> :hello_world
'Hello World!'.simple_elementize #=> 'hello_world'
'Hello World!'.simple_camelize #=> :helloWorld
'Hello World!'.simple_snakeize #=> :hello_world
The #snakeize
method will return your object in snake_case.
This is the default behaviour of the #symbolize
method however #snakeize
will always return thr Symbol in snake_case.
#to_snake_case
extends the String class to return you your String object in snake_case format.
SimpleSymbolize.symbolize('helloWorld!') # => :hello_world
This is the default behaviour and can be switched off by setting #handle_camel_case
to false
SimpleSymbolize.translate { |trans| trans.handle_camel_case = false }
Arrays are now supported when configuring the gem
SimpleSymbolize.translate { |trans| trans.to_underscore = %w[!&*] }
SimpleSymbolize has got new friends!
Introducing elementize
and camelize
.
Sometimes you just want a simple String obj without all the fuss. Elementize takes your String obj, removes that fuss and returns you a simple-to-use String.
SimpleSymbolize.elementize('hello world!') # => "hello_world"
Great for working with APIs that require fields in a JSON format. Camelize clears away the clutter and returns you a Symbolized object in camelCase.