Posted over 8 years ago. Visible to the public.

Random list of ActiveSupport goodies

I recently browsed through the ActiveSupport code and found some nice stuff I did not know about:

ActiveSupport::Callbacks
ActiveRecord-like callbacks, if you need callbacks in non ActiveRecord objects
ActiveSupport::MessageEncryptor
encrypt and decrypt ruby objects
ActiveSupport::MessageVerifier
sign and verify ruby objects
ActiveSupport::OrderedOptions
like an ordered hash, but the keys can also be accessed like methods
Copy
h = ActiveSupport::OrderedOptions.new h['foo'] = 'bar' h.foo = 'bar' # same thing h['foo'] # => 'bar' h.foo # => 'bar'
in? (> 3.0 only)
reverse of Array#include?
Copy
characters = ["Konata", "Kagami", "Tsukasa"] "Konata".in?(characters) # => true
Array.wrap
wraps argument in an array, unless it is array-like already. The behaviour is a bit saner than Array[...].
Copy
Array.wrap(nil) # => [] Array.wrap([1,2,3]) # => [1,2,3] Array.wrap(1) # => [1] Array.wrap("foo \n bar") # => ["foo \n bar"]
Class.class_attributes (> 3.0 only)
inheritable class attributes. Subclasses inherit from their parents, but cannot override their values
Copy
class Base class_attribute :setting end class Subclass < Base end Base.setting = true Subclass.setting # => true Subclass.setting = false Subclass.setting # => false Base.setting # => true
Float#round
round to a given number of decimals
Copy
1.2345.round(2) # => 1.23 1.2345.round(3) # => 1.235
Hash#deep_merge(!)
merge hashes recursively
String#squish(!)
removes leading and trailing whitespace, and converts all internal whitespace to single spaces
Copy
%{ Multi-line string }.squish # => "Multi-line string" " foo bar \n \t boo".squish # => "foo bar boo"
Time.current, Date.current, DateTime.current
behaves like .now or .zone.now depending on whether a time zone is set
Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Avatar
Tobias Kraze
Last edit:
over 7 years ago
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Tobias Kraze to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more