Skip to content

Commit

Permalink
AS core_ext refactoring pt.2
Browse files Browse the repository at this point in the history
  • Loading branch information
gazay committed Apr 28, 2012
1 parent 1946d7b commit 9257224
Show file tree
Hide file tree
Showing 20 changed files with 110 additions and 86 deletions.
94 changes: 50 additions & 44 deletions activesupport/lib/active_support/core_ext/array/conversions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,32 @@ class Array
# * <tt>:two_words_connector</tt> - The sign or word used to join the elements in arrays with two elements (default: " and ")
# * <tt>:last_word_connector</tt> - The sign or word used to join the last element in arrays with three or more elements (default: ", and ")
def to_sentence(options = {})
options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale)

default_connectors = {
:words_connector => ', ',
:two_words_connector => ' and ',
:last_word_connector => ', and '
}
if defined?(I18n)
default_words_connector = I18n.translate(:'support.array.words_connector', :locale => options[:locale])
default_two_words_connector = I18n.translate(:'support.array.two_words_connector', :locale => options[:locale])
default_last_word_connector = I18n.translate(:'support.array.last_word_connector', :locale => options[:locale])
else
default_words_connector = ", "
default_two_words_connector = " and "
default_last_word_connector = ", and "
namespace = 'support.array.'
default_connectors.each_key do |name|
i18n_key = (namespace + name.to_s).to_sym
default_connectors[name] = I18n.translate i18n_key, :locale => options[:locale]
end
end

options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale)
options.reverse_merge! :words_connector => default_words_connector, :two_words_connector => default_two_words_connector, :last_word_connector => default_last_word_connector
options.reverse_merge! default_connectors

case length
when 0
""
when 1
self[0].to_s.dup
when 2
"#{self[0]}#{options[:two_words_connector]}#{self[1]}"
else
"#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}"
when 0
''
when 1
self[0].to_s.dup
when 2
"#{self[0]}#{options[:two_words_connector]}#{self[1]}"
else
"#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}"
end
end

Expand All @@ -45,14 +49,14 @@ def to_sentence(options = {})
# Blog.all.to_formatted_s(:db) # => "1,2,3"
def to_formatted_s(format = :default)
case format
when :db
if respond_to?(:empty?) && empty?
"null"
else
collect { |element| element.id }.join(",")
end
when :db
if empty?
'null'
else
to_default_s
collect { |element| element.id }.join(',')
end
else
to_default_s
end
end
alias_method :to_default_s, :to_s
Expand Down Expand Up @@ -86,20 +90,20 @@ def to_formatted_s(format = :default)
# </project>
# </projects>
#
# Otherwise the root element is "records":
# Otherwise the root element is "objects":
#
# [{:foo => 1, :bar => 2}, {:baz => 3}].to_xml
#
# <?xml version="1.0" encoding="UTF-8"?>
# <records type="array">
# <record>
# <objects type="array">
# <object>
# <bar type="integer">2</bar>
# <foo type="integer">1</foo>
# </record>
# <record>
# </object>
# <object>
# <baz type="integer">3</baz>
# </record>
# </records>
# </object>
# </objects>
#
# If the collection is empty the root element is "nil-classes" by default:
#
Expand Down Expand Up @@ -139,26 +143,28 @@ def to_xml(options = {})
options = options.dup
options[:indent] ||= 2
options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
options[:root] ||= if first.class.to_s != "Hash" && all? { |e| e.is_a?(first.class) }
underscored = ActiveSupport::Inflector.underscore(first.class.name)
ActiveSupport::Inflector.pluralize(underscored).tr('/', '_')
else
"objects"
end
options[:root] ||= \
if first.class != Hash && all? { |e| e.is_a?(first.class) }
underscored = ActiveSupport::Inflector.underscore(first.class.name)
ActiveSupport::Inflector.pluralize(underscored).tr('/', '_')
else
'objects'
end

builder = options[:builder]
builder.instruct! unless options.delete(:skip_instruct)

root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)
children = options.delete(:children) || root.singularize
attributes = options[:skip_types] ? {} : {:type => 'array'}

attributes = options[:skip_types] ? {} : {:type => "array"}
return builder.tag!(root, attributes) if empty?

builder.__send__(:method_missing, root, attributes) do
each { |value| ActiveSupport::XmlMini.to_tag(children, value, options) }
yield builder if block_given?
if empty?
builder.tag!(root, attributes)
else
builder.__send__(:method_missing, root, attributes) do
each { |value| ActiveSupport::XmlMini.to_tag(children, value, options) }
yield builder if block_given?
end
end
end

end
6 changes: 2 additions & 4 deletions activesupport/lib/active_support/core_ext/array/grouping.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,9 @@ def in_groups(number, fill_with = nil)
#
# [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]]
# (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
def split(value = nil)
using_block = block_given?

def split(value = nil, &block)
inject([[]]) do |results, element|
if (using_block && yield(element)) || (value == element)
if block && block.call(element) || value == element
results << []
else
results.last << element
Expand Down
6 changes: 2 additions & 4 deletions activesupport/lib/active_support/core_ext/array/uniq_by.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,15 @@ class Array
# [1, 2, 3, 4].uniq_by { |i| i.odd? } # => [1, 2]
#
def uniq_by(&block)
ActiveSupport::Deprecation.warn "uniq_by " \
"is deprecated. Use Array#uniq instead", caller
ActiveSupport::Deprecation.warn 'uniq_by is deprecated. Use Array#uniq instead', caller
uniq(&block)
end

# *DEPRECATED*: Use +Array#uniq!+ instead.
#
# Same as +uniq_by+, but modifies +self+.
def uniq_by!(&block)
ActiveSupport::Deprecation.warn "uniq_by! " \
"is deprecated. Use Array#uniq! instead", caller
ActiveSupport::Deprecation.warn 'uniq_by! is deprecated. Use Array#uniq! instead', caller
uniq!(&block)
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,11 @@ def readable_inspect
# Attempts to convert self to a Ruby Time object; returns self if out of range of Ruby Time class.
# If self has an offset other than 0, self will just be returned unaltered, since there's no clean way to map it to a Time.
def to_time
self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec, sec_fraction * 1000000) : self
if offset == 0
::Time.utc_time(year, month, day, hour, min, sec, sec_fraction * 1000000)
else
self
end
end

# Returns DateTime with local offset for given year if format is local else offset is zero
Expand Down
8 changes: 5 additions & 3 deletions activesupport/lib/active_support/core_ext/date_time/zones.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ class DateTime
#
# DateTime.new(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
def in_time_zone(zone = ::Time.zone)
return self unless zone

ActiveSupport::TimeWithZone.new(utc? ? self : getutc, ::Time.find_zone!(zone))
if zone
ActiveSupport::TimeWithZone.new(utc? ? self : getutc, ::Time.find_zone!(zone))
else
self
end
end
end
9 changes: 6 additions & 3 deletions activesupport/lib/active_support/core_ext/enumerable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,11 @@ def sum(identity = 0, &block)
# => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}
#
def index_by
return to_enum :index_by unless block_given?
Hash[map { |elem| [yield(elem), elem] }]
if block_given?
Hash[map { |elem| [yield(elem), elem] }]
else
to_enum :index_by
end
end

# Returns true if the enumerable has more than 1 element. Functionally equivalent to enum.to_a.size > 1.
Expand All @@ -48,7 +51,7 @@ def many?
cnt > 1
end
else
any?{ (cnt += 1) > 1 }
any? { (cnt += 1) > 1 }
end
end

Expand Down
10 changes: 8 additions & 2 deletions activesupport/lib/active_support/core_ext/file/atomic.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,14 @@ def self.atomic_write(file_name, temp_dir = Dir.tmpdir)
old_stat = stat(file_name)
rescue Errno::ENOENT
# No old permissions, write a temp file to determine the defaults
check_name = join(dirname(file_name), ".permissions_check.#{Thread.current.object_id}.#{Process.pid}.#{rand(1000000)}")
open(check_name, "w") { }
temp_file_name = [
'.permissions_check',
Thread.current.object_id,
Process.pid,
rand(1000000)
].join('.')
check_name = join(dirname(file_name), temp_file_name)
open(check_name, 'w') { }
old_stat = stat(check_name)
unlink(check_name)
end
Expand Down
6 changes: 4 additions & 2 deletions activesupport/lib/active_support/core_ext/hash/diff.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ class Hash
# {1 => 2}.diff(1 => 3) # => {1 => 2}
# {}.diff(1 => 2) # => {1 => 2}
# {1 => 2, 3 => 4}.diff(1 => 2) # => {3 => 4}
def diff(h2)
dup.delete_if { |k, v| h2[k] == v }.merge!(h2.dup.delete_if { |k, v| has_key?(k) })
def diff(other)
dup.
delete_if { |k, v| other[k] == v }.
merge!(other.dup.delete_if { |k, v| has_key?(k) })
end
end
5 changes: 2 additions & 3 deletions activesupport/lib/active_support/core_ext/hash/keys.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def symbolize_keys
end
result
end
alias_method :to_options, :symbolize_keys

# Destructively convert all keys to symbols, as long as they respond
# to +to_sym+.
Expand All @@ -34,8 +35,6 @@ def symbolize_keys!
end
self
end

alias_method :to_options, :symbolize_keys
alias_method :to_options!, :symbolize_keys!

# Validate all keys in a hash match *valid keys, raising ArgumentError on a mismatch.
Expand All @@ -49,7 +48,7 @@ def symbolize_keys!
def assert_valid_keys(*valid_keys)
valid_keys.flatten!
each_key do |k|
raise(ArgumentError, "Unknown key: #{k}") unless valid_keys.include?(k)
raise ArgumentError.new("Unknown key: #{k}") unless valid_keys.include?(k)
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,5 @@ def reverse_merge!(other_hash)
# right wins if there is no left
merge!( other_hash ){|key,left,right| left }
end

alias_method :reverse_update, :reverse_merge!
end
2 changes: 1 addition & 1 deletion activesupport/lib/active_support/core_ext/hash/slice.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,6 @@ def slice!(*keys)
# Removes and returns the key/value pairs matching the given keys.
# {:a => 1, :b => 2, :c => 3, :d => 4}.extract!(:a, :b) # => {:a => 1, :b => 2}
def extract!(*keys)
keys.each_with_object({}) {|key, result| result[key] = delete(key) }
keys.each_with_object({}) { |key, result| result[key] = delete(key) }
end
end
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'rbconfig'

module Kernel
# Sets $VERBOSE to nil for the duration of the block and back to its original value afterwards.
#
Expand Down
15 changes: 8 additions & 7 deletions activesupport/lib/active_support/core_ext/module/aliasing.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,19 @@ def alias_method_chain(target, feature)
aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1
yield(aliased_target, punctuation) if block_given?

with_method, without_method = "#{aliased_target}_with_#{feature}#{punctuation}", "#{aliased_target}_without_#{feature}#{punctuation}"
with_method = "#{aliased_target}_with_#{feature}#{punctuation}"
without_method = "#{aliased_target}_without_#{feature}#{punctuation}"

alias_method without_method, target
alias_method target, with_method

case
when public_method_defined?(without_method)
public target
when protected_method_defined?(without_method)
protected target
when private_method_defined?(without_method)
private target
when public_method_defined?(without_method)
public target
when protected_method_defined?(without_method)
protected target
when private_method_defined?(without_method)
private target
end
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ def attr_internal_accessor(*attrs)
attr_internal_reader(*attrs)
attr_internal_writer(*attrs)
end

alias_method :attr_internal, :attr_internal_accessor

class << self; attr_accessor :attr_internal_naming_format end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def delegate(*methods)
raise ArgumentError, "Can only automatically set the delegation prefix when delegating to a method."
end

method_prefix =
method_prefix = \
if prefix
"#{prefix == true ? to : prefix}_"
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ class Module
#
# M::N.parent_name # => "M"
def parent_name
unless defined? @parent_name
if defined? @parent_name
@parent_name
else
@parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil
end
@parent_name
end

# Returns the module which contains this one according to its name.
Expand Down Expand Up @@ -73,7 +74,7 @@ def local_constants #:nodoc:
# This method is useful for forward compatibility, since Ruby 1.8 returns
# constant names as strings, whereas 1.9 returns them as symbols.
def local_constant_names
ActiveSupport::Deprecation.warn('Module#local_constant_names is deprecated, use Module#local_constants instead', caller)
ActiveSupport::Deprecation.warn 'Module#local_constant_names is deprecated, use Module#local_constants instead', caller
local_constants.map { |c| c.to_s }
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
#++
module QualifiedConstUtils
def self.raise_if_absolute(path)
raise NameError, "wrong constant name #$&" if path =~ /\A::[^:]+/
raise NameError.new("wrong constant name #$&") if path =~ /\A::[^:]+/
end

def self.names(path)
Expand Down
2 changes: 1 addition & 1 deletion activesupport/lib/active_support/core_ext/string/access.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require "active_support/multibyte"
require 'active_support/multibyte'

class String
def at(position)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,10 @@ def safe_constantize
# "active_record/errors".camelize(:lower) # => "activeRecord::Errors"
def camelize(first_letter = :upper)
case first_letter
when :upper then ActiveSupport::Inflector.camelize(self, true)
when :lower then ActiveSupport::Inflector.camelize(self, false)
when :upper
ActiveSupport::Inflector.camelize(self, true)
when :lower
ActiveSupport::Inflector.camelize(self, false)
end
end
alias_method :camelcase, :camelize
Expand Down
Loading

0 comments on commit 9257224

Please sign in to comment.