ActiveSupport
The ActiveSupport filter provides JavaScript equivalents for common Rails ActiveSupport core extensions. These methods are frequently used in Rails templates and views.
Supported Methods
Object Methods
blank?
Returns true if the object is null, empty, or a blank string.
name.blank?
name == null || name.length === 0 || name === ""
present?
The opposite of blank? - returns true if the object has meaningful content.
user.email.present?
user.email != null && user.email.length != 0 && user.email != ""
presence
Returns the object if it’s present?, otherwise returns null.
name.presence || "Anonymous"
(name != null && name.length != 0 && name != "" ? name : null) || "Anonymous"
try
Calls a method on the receiver, returning null if the receiver is null or undefined. Uses JavaScript optional chaining (?.).
user.try(:name)
user.try(:fetch, :key)
user?.name()
user?.fetch("key")
in?
Checks if the object is included in a collection. The inverse of include?.
status.in?(["active", "pending"])
["active", "pending"].includes(status)
String Methods
squish
Removes leading/trailing whitespace and collapses internal whitespace to single spaces.
" hello world ".squish
" hello world ".trim().replace(/\s+/g, " ")
truncate
Truncates a string to a specified length, adding an omission marker (default: "...").
title.truncate(50)
description.truncate(100, omission: "…")
title.length > 50 ? title.slice(0, 47) + "..." : title
description.length > 100 ? description.slice(0, 99) + "…" : description
Array Methods
to_sentence
Converts an array to a comma-separated sentence with “and” before the last element.
["Alice", "Bob", "Carol"].to_sentence
// Returns: "Alice, Bob and Carol"
arr.length === 0 ? "" :
arr.length === 1 ? arr[0] :
arr.slice(0, -1).join(", ") + " and " + arr[arr.length - 1]
Usage with ERB Filter
The ActiveSupport filter pairs well with the ERB filter for converting Rails templates to JavaScript:
require "ruby2js"
require "ruby2js/filter/active_support"
require "ruby2js/filter/erb"
require "ruby2js/erubi"
template = <<~ERB
<% if @user.name.present? %>
<h1><%= @user.name.truncate(30) %></h1>
<% end %>
ERB
src = Ruby2JS::Erubi.new(template).src
puts Ruby2JS.convert(src, filters: [:erb, :active_support], eslevel: 2020)
Limitations
These methods provide simplified JavaScript equivalents. Some edge cases may behave differently from Rails:
blank?checks fornull, empty length, or empty string. It doesn’t handle other “blank” values likefalseor whitespace-only strings.to_sentenceuses hardcoded “and” connector (no internationalization support)truncatedoesn’t support:separatoroption for word boundaries