Some Ways ActiveSupport Helps Ruby Developers

Share this article

Ruby is an object-oriented, interpreted language invented by Yukihiro Matsumoto in 1993 that is heavily inspired by Perl and Lisp. Since its inception, Ruby has been designed to be a “joy to use” – meaning a strong focus on readability and elegance.

Ruby on Rails, often simply Rails, is an open source web application framework which runs on the Ruby programming language. Ruby on Rails is intended to emphasize Convention over Configuration (CoC), and the rapid development principle of Don’t Repeat Yourself (DRY). Rails is a powerful framework that can help you become more productive and confident.

Rails uses various gems, many that are frameworks in their own right, to give you abstractions that help write clean and DRY code. One of those gems is ActiveSupport, which defines itself on Rubygems.org as:

A toolkit of support libraries and Ruby core extensions extracted from the Rails framework. Rich support for multibyte strings, internationalization, time zones, and testing.

Essentially, ActiveSupport extends many of the core Ruby classes to give the syntactic sugar that Rails uses. Let’s take a look at some of these abstractions and see how they help (and hurt) you as a developer.

Hash in Ruby

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type.

Example of a Hash:

#initialize an empty hash colors
colors = { }

#add a color with key as red
colors[:red] = "Red Color"

#add a color with key as blue
colors[:blue] = "Blue Color"

#display the hash
colors  #=> {:red=>"Red Color", :blue=>"Blue Color"}

The value of a particular key can be fetched from the hash by:

Hash[key]    
or
Hash.fetch(:key)

If we want to fetch the value for the key :red, then

colors[:red]  #=> "Red Color"

But if we try colors['red'] we will get the value as nil.

colors['red'] #=> nil

This is because Hash treats symbols and string in keys differently. This can be explained further if we add another key-value to our hash.

colors['red'] = "Red color, here key is not a symbol"

Now, if we try to fetch the value for the key, it will return our new value.

colors['red'] #=> "Red color, but key is not a symbol"
colors[:red] #=> "Red Color"

Consider an example where we have two hashes, a = {"red": "Red color"} and b = {:red => "Red color"}.

If we merge these two hashes, like so

a.merge! b   #=> {"red" => "Red color, :red => "RED COLOR"}

and try to fetch the values from hash

a['red']  #=> "Red color"
a[:red]   #=> "RED COLOR"

the result is not ideal, to say the least.

This can be a bit confusing at times, especially if you have worked with Rails. Rails allows you to access, for example, params[:name] or params['name'] in a controller action receive the same value. This is due to Rails use of ActiveSupport::HashWithIndifferentAccess instead of the normal Hash.

HashWithIndifferentAccess

HashWithIndifferentAccess is a class defined inside the ActiveSupport gem that helps us overcome the aforementioned issue. Here, the symbols in the keys will be converted to strings, so we can fetch the values from a hash using both symbols as well as strings.

Example:

(If you arent using Rails then dont forget to require active_support)

require 'active_support/core_ext/hash/indifferent_access'
colors = HashWithIndifferentAccess.new
colors[:red] = "Red color"

#Fetch the value using symbol
colors[:red]  #=> "Red color"

#Fetch the value using string
colors["red"]  #=> "Red color"

If we want to convert an existing Hash to HashWithIndifferentAccess

colors = { blue: 'Blue color', white: 'Red Color' }.with_indifferent_access

HashWithIndifferentAccess is used by all Rails developers, sometimes unknowlingly.

ActiveSupport::Inflectors

Inflectors is a module that ships along with the ActiveSupport and is included in your Rails app. Inflectors offers many methods that are helpful for developers. If we want to use the module independently in our ruby scripts, we need to include the module inside our ruby code as:

require 'active_support/inflector'

Some of the commonly used and beneficial inflectors are explained here.

Camelize

It converts strings to CamelCase strings. These are mostly beneficial when working with Ruby constants.

Example:

'manu'.camlize #=> 'Manu'

Humanize

This method uses regular expressions to convert the strings to more human readable strings. These can be used in urls, among other things.

Example:

'author_id'.humanize #=> 'Author'

Titelize

This will generate a nice and clean, title-like output after removing special characters from the string

Example:

'x-men: the last stand'.titleize #=> "X Men: The Last Stand"

More methods can be found in the Rails API guide and details on the code can be found on github

ActiveSupport Extensions

ActiveSupport::Extensions offer utilities for extending Ruby. These extensions are part of the ActiveSupport core and can be loaded into a Rails app by including active_support. If you only want a particular method, then include that by cherry-picking it, like so:

require 'active_support/core_ext/object/try.rb'

Some useful methods that are part of the ActiveSupport::Extensions are described below:

try method

The try method is one of the most useful methods included with ActiveSupport. You can use this method to in place of a block that checks if an object is nil before calling a method on that object.

Example:

# without try
if @user.first_name
  puts @user.first_name
end    

# with try
@user.try(:first_name)

Thus try would help us to avoid the unnecessary conditional statements.

Extensions to Numeric

Formatting

Using this method, numbers can be formatted in a variety of ways.

Phone Numbers:

Example:

5551234.to_s(:phone)
# => 555-1234
1235551234.to_s(:phone)
# => 123-555-1234
1235551234.to_s(:phone, area_code: true)
# => (123) 555-1234
1235551234.to_s(:phone, delimiter: " ")
# => 123 555 1234
1235551234.to_s(:phone, area_code: true, extension: 555)
# => (123) 555-1234 x 555
1235551234.to_s(:phone, country_code: 1)
# => +1-123-555-1234

Currency

Example:

1234567890.50.to_s(:currency)                 # => $1,234,567,890.50
1234567890.506.to_s(:currency)                # => $1,234,567,890.51
1234567890.506.to_s(:currency, precision: 3)  # => $1,234,567,890.506

Percentage

Example:

100.to_s(:percentage)
# => 100.000%
100.to_s(:percentage, precision: 0)
# => 100%
1000.to_s(:percentage, delimiter: '.', separator: ',')
# => 1.000,000%
302.24398923423.to_s(:percentage, precision: 5)
# => 302.24399%

Human Readable Values

Example:

123.to_s(:human)               # => "123"
1234.to_s(:human)              # => "1.23 Thousand"
12345.to_s(:human)             # => "12.3 Thousand"
1234567.to_s(:human)           # => "1.23 Million"
1234567890.to_s(:human)        # => "1.23 Billion"
1234567890123.to_s(:human)     # => "1.23 Trillion"
1234567890123456.to_s(:human)  # => "1.23 Quadrillion"

Conversions

to_sentence

This methods converts an array of words into a sentence.

Example:

%w().to_sentence                # => ""
%w(Earth).to_sentence           # => "Earth"
%w(Earth Wind).to_sentence      # => "Earth and Wind"
%w(Earth Wind Fire).to_sentence # => "Earth, Wind, and Fire"

More methods and a detailed explanation can be found by browsing the source code of ActiveSupport itself.

Conclusion

Many of the methods that are part of Rails or its included modules are under-utilized. One of the best resources to explore these are by browsing the source code itself.

Manu S Ajith

@manusajith

Frequently Asked Questions (FAQs) about ActiveSupport and Ruby Development

What is ActiveSupport and how does it help Ruby developers?

ActiveSupport is a utility library in Ruby on Rails that provides Ruby language extensions, utilities, and other transversal stuff. It enriches the Ruby language by providing additional methods and classes, making it more powerful and easier to use. For instance, it provides methods to manipulate time, dates, numbers, and strings, among other things. It also offers a way to organize code better through its concern module.

How can I install and use ActiveSupport in my Ruby project?

ActiveSupport can be installed by adding it to your Gemfile and running the bundle install command. Once installed, you can use it in your Ruby project by requiring it at the top of your Ruby files. For example, to use the time extensions, you would add require ‘active_support/time’ to your file.

What are some common use cases for ActiveSupport in Ruby development?

ActiveSupport is commonly used in Ruby development for tasks such as manipulating time and dates, formatting strings, and handling JSON data. It also provides a way to organize code better through its concern module, which allows you to group related methods together.

How does ActiveSupport compare to other Ruby libraries?

ActiveSupport is a part of the Ruby on Rails framework, but it can also be used independently in any Ruby project. It is more comprehensive than most other Ruby libraries, providing a wide range of utilities and extensions. However, it may be overkill for simple projects that don’t require its full range of features.

What are the benefits of using ActiveSupport over native Ruby methods?

While native Ruby methods are powerful, ActiveSupport provides additional methods that make certain tasks easier and more intuitive. For example, it provides methods for manipulating time and dates that are more intuitive than the native Ruby methods. It also provides a way to organize code better through its concern module.

How can I contribute to the ActiveSupport library?

ActiveSupport is an open-source project, so anyone can contribute to its development. You can contribute by submitting bug reports, suggesting new features, or writing code. To get started, you can check out the project on GitHub and follow the contribution guidelines.

What are some resources for learning more about ActiveSupport?

The official Ruby on Rails guides are a great resource for learning more about ActiveSupport. There are also many tutorials and blog posts available online that cover specific aspects of ActiveSupport. Additionally, the source code for ActiveSupport is available on GitHub, which can be a valuable resource for understanding how it works.

Can I use ActiveSupport in non-Rails Ruby projects?

Yes, ActiveSupport can be used in any Ruby project, not just Rails projects. You can add it to your Gemfile and require it in your Ruby files to use its features.

What are some alternatives to ActiveSupport?

While ActiveSupport is very comprehensive, there are other Ruby libraries that provide similar functionality. For example, the Facets gem provides many of the same extensions to the Ruby language. However, these alternatives may not be as comprehensive or well-documented as ActiveSupport.

How does ActiveSupport handle time zones?

ActiveSupport provides comprehensive support for time zones. It allows you to set a default time zone for your application and to convert times between different time zones. It also provides methods for parsing dates and times in different formats.

Manu AjithManu Ajith
View Author

Tech Entrepreneur. Writes Elixir, Ruby, Go for a living. Into functional paradigms DDD/CQRS/EventSourcing architecture these days. @manusajith on the interwebs. Lazy blogger who scribbles at Til.Codes

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week