More Related Content Similar to Active Support Improvements in Rails 5 (20) Active Support Improvements in Rails 53. ©2014
• days_in_year
class Time
include DateAndTime::Calculations
COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
class << self
# Returns the number of days in the given month.
# If no year is specified, it will use the current year.
def days_in_month(month, year = current.year)
if month == 2 && ::Date.gregorian_leap?(year)
29
else
COMMON_YEAR_DAYS_IN_MONTH[month]
end
end
# Returns the number of days in the given year.
# If no year is specified, it will use the current year.
def days_in_year(year = current.year)
days_in_month(2, year) + 337
end
end
end
Improvements in Date, Time and DateTime
4. ©2014
• Pluck ( https://goo.gl/yjuBki )
module Enumerable
# Convert an enumerable to an array based on the given key.
#
# [{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pluck(:name)
# => ["David", "Rafael", "Aaron"]
#
# [{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pluck(:id, :name)
# => [[1, "David"], [2, "Rafael"]]
def pluck(*keys)
if keys.many?
map { |element| keys.map { |key| element[key] } }
else
map { |element| element[keys.first] }
end
end
end
5. ©2014
• Without ( https://goo.gl/etJN7h )
class Array
# Returns a copy of the Array without the specified elements.
#
# people = ["David", "Rafael", "Aaron", "Todd"]
# people.without "Aaron", "Todd"
# => ["David", "Rafael"]
#
# Note: This is an optimization of `Enumerable#without` that uses `Array#-`
# instead of `Array#reject` for performance reasons.
def without(*elements)
self - elements
end
end
6. ©2014
• second_to_last (https://goo.gl/Ig0pOY )
• third_to_last
class Array
# Equal to <tt>self[-3]</tt>.
#
# %w( a b c d e ).third_to_last # => "c"
def third_to_last
self[-3]
end
# Equal to <tt>self[-2]</tt>.
#
# %w( a b c d e ).second_to_last # => "d"
def second_to_last
self[-2]
end
end
7. ©2014
• positive? (https://goo.gl/UsTnWl )
• negative?
class Integer
# Returns true if the number is positive.
#
# 1.positive? # => true
# 0.positive? # => false
# -1.positive? # => false
def positive?
self > 0
end
# Returns true if the number is negative.
#
# -1.positive? # => true
# 0.positive? # => false
# 1.positive? # => false
def negative?
self < 0
end
end
8. ©2014
• Inquiry ( https://goo.gl/47bjv7 , https://goo.gl/QpVmU3 )
class ArrayInquirer < Array
def any?(*candidates, &block)
if candidates.none?
super
else
candidates.any? do |candidate|
include?(candidate) || include?(candidate.to_sym)
end
end
end
private
def respond_to_missing?(name, include_private = false)
name[-1] == '?'
end
def method_missing(name, *args)
if name[-1] == '?'
any?(name[0..-2])
else
super
end
end
end