ActionSupport in Rails4 Part2

Continue ActionSupport useful record

Extensions to Numeric


Defined in active_support/core_ext/numeric/bytes.rb.

Bytes

All number respond to these methods

1
2
3
4
2.kilobytes   # => 2048
3.megabytes   # => 3145728
3.5.gigabytes # => 3758096384
-4.exabytes   # => -4611686018427387904

Defined in active_support/core_ext/numeric/time.rb.

Time

1
2
3
4
5
6
7
8
# equivalent to Time.current.advance(months: 1)
1.month.from_now

# equivalent to Time.current.advance(years: 2)
2.years.from_now

# equivalent to Time.current.advance(months: 4, years: 5)
(4.months + 5.years).from_now

Extensions to Integer


Defined in active_support/core_ext/integer/multiple.rb.

multiple_of

1
2
2.multiple_of?(1) # => true
1.multiple_of?(2) # => false

Extensions to Enumerable


Defined in active_support/core_ext/enumerable.rb.

sum

1
2
[1, 2, 3].sum # => 6
(1..100).sum  # => 5050

If a block is given, sum becomes an iterator that yields the elements of the collection and sums the returned values:

1
2
(1..5).sum {|n| n * 2 } # => 30
[2, 4, 6, 8, 10].sum    # => 30

many?

The method many? is shorthand for collection.size > 1:

1
2
3
<% if pages.many? %>
  <%= pagination_links %>
<% end %>

Extensions to Array


Defined in active_support/core_ext/array/access.rb.

1
2
3
4
%w(a b c d).to(2) # => %w(a b c)
[].to(7)          # => []
%w(a b c d).from(2)  # => %w(c d)
%w(a b c d).from(10) # => []

Defined in active_support/core_ext/array/prepend_and_append.rb.

prepend and append

1
2
3
4
%w(a b c d).prepend('e')  # => %w(e a b c d)
[].prepend(10)            # => [10]
%w(a b c d).append('e')  # => %w(a b c d e)
[].append([1,2])         # => [[1,2]]

Defined in active_support/core_ext/array/grouping.rb

in_groups_of(number, fill_with = nil)

The method in_groups_of splits an array into consecutive groups of a certain size.

1
2
3
[1, 2, 3].in_groups_of(2) # => [[1, 2], [3, nil]]
[1, 2, 3].in_groups_of(2, false) # => [[1, 2], [3]]
[1, 2, 3].in_groups_of(2, 0) # => [[1, 2], [3, 0]]

in_groups(number, fill_with = nil)

The method in_groups splits an array into a certain number of groups.

1
2
%w(1 2 3 4 5 6 7).in_groups(3)
# => [["1", "2", "3"], ["4", "5", nil], ["6", "7", nil]]

Comments