Module: PhonyRails::ActiveRecordExtension::ClassMethods

Defined in:
lib/phony_rails.rb

Instance Method Summary collapse

Instance Method Details

#phony_normalize(*attributes) ⇒ Object

Use this method on the class level like:

phony_normalize :phone_number, :fax_number, :default_country_code => 'NL'

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!

Raises:

  • (ArgumentError)


66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/phony_rails.rb', line 66

def phony_normalize(*attributes)
  options = attributes.last.is_a?(Hash) ? attributes.pop : {}
  options.assert_valid_keys :country_code, :default_country_code, :as
  raise ArgumentError, ':as option can not be used on phony_normalize with multiple attribute names! (PhonyRails)' if !options[:as].blank? && attributes.size > 1
  attributes.each do |attribute|
    raise ArgumentError, "No attribute #{attribute} found on #{self.class.name} (PhonyRails)" if not self.attribute_method?(attribute)
    # Add before validation that saves a normalized version of the phone number
    self.before_validation do 
      set_phony_normalized_numbers(attributes, options)
    end
  end
end

#phony_normalized_method(*attributes) ⇒ Object

Usage:

phony_normalized_method :fax_number, :default_country_code => 'US'

Creates a normalized_fax_number method.



82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/phony_rails.rb', line 82

def phony_normalized_method(*attributes)
  main_options = attributes.last.is_a?(Hash) ? attributes.pop : {} 
  main_options.assert_valid_keys :country_code, :default_country_code
  attributes.each do |attribute|
    raise StandardError, "Instance method normalized_#{attribute} already exists on #{self.name} (PhonyRails)" if self.instance_methods.include?(:"normalized_#{attribute}")
    define_method :"normalized_#{attribute}" do |options = {}|
      raise ArgumentError, "No attribute/method #{attribute} found on #{self.class.name} (PhonyRails)" if not self.respond_to?(attribute)
      options[:country_code] ||= self.country_code if self.respond_to?(:country_code)
      PhonyRails.normalize_number(self.send(attribute), main_options.merge(options))
    end
  end
end