lib/phony_rails.rb in phony_rails-0.14.5 vs lib/phony_rails.rb in phony_rails-0.14.6
- old
+ new
@@ -108,17 +108,12 @@
COMMON_EXTENSIONS = /[ ]*(ext|ex|x|xt|#|:)+[^0-9]*\(?([-0-9]{1,})\)?#?$/i
def self.extract_extension(number_and_ext)
return [nil, nil] if number_and_ext.nil?
- # :nocov:
- if subbed = number_and_ext.sub(COMMON_EXTENSIONS, '')
- [subbed, Regexp.last_match(2)]
- else
- [number_and_ext, nil]
- end
- # :nocov:
+ subbed = number_and_ext.sub(COMMON_EXTENSIONS, '')
+ [subbed, Regexp.last_match(2)]
end
def self.format_extension(number, ext)
ext.present? ? "#{number} x#{ext}" : number
end
@@ -160,19 +155,21 @@
#
# It checks your model object for a a country_code attribute (eg. 'NL') to do the normalizing so make sure
# you've geocoded before calling this method!
def phony_normalize(*attributes)
options = attributes.last.is_a?(Hash) ? attributes.pop : {}
- options.assert_valid_keys :country_number, :default_country_number, :country_code, :default_country_code, :add_plus, :as, :enforce_record_country
+ options.assert_valid_keys :country_number, :default_country_number, :country_code, :default_country_code, :add_plus, :as, :enforce_record_country, :if, :unless
if options[:as].present?
raise ArgumentError, ':as option can not be used on phony_normalize with multiple attribute names! (PhonyRails)' if attributes.size > 1
end
options[:enforce_record_country] = true if options[:enforce_record_country].nil?
+ conditional = create_before_validation_conditional_hash(options)
+
# Add before validation that saves a normalized version of the phone number
- before_validation do
+ before_validation conditional do
set_phony_normalized_numbers(attributes, options)
end
end
# Usage:
@@ -190,15 +187,48 @@
options[:country_code] ||= country_code if respond_to?(:country_code)
PhonyRails.normalize_number(send(attribute), options)
end
end
end
+
+ private
+
+ # Creates a hash representing a conditional for before_validation
+ # This allows conditional normalization
+ # Returns something like `{ unless: -> { attribute == 'something' } }`
+ # If no if/unless options passed in, returns `{ if: -> { true } }`
+ def create_before_validation_conditional_hash(options)
+ if options[:if].present?
+ type = :if
+ source = options[:if]
+ elsif options[:unless].present?
+ type = :unless
+ source = options[:unless]
+ else
+ type = :if
+ source = true
+ end
+
+ conditional = {}
+ conditional[type] = if source.respond_to?(:call)
+ source
+ elsif source.respond_to?(:to_sym)
+ -> { send(source.to_sym) }
+ else
+ -> { source }
+ end
+ conditional
+ end
end
end
end
# check whether it is ActiveRecord or Mongoid being used
-ActiveRecord::Base.send :include, PhonyRails::Extension if defined?(ActiveRecord)
+if defined?(ActiveRecord)
+ ActiveSupport.on_load(:active_record) do
+ ActiveRecord::Base.send :include, PhonyRails::Extension
+ end
+end
ActiveModel::Model.send :include, PhonyRails::Extension if defined?(ActiveModel::Model)
if defined?(Mongoid)
module Mongoid::Phony