Giter Site home page Giter Site logo

joost / phony_rails Goto Github PK

View Code? Open in Web Editor NEW
554.0 7.0 111.0 488 KB

This Gem adds useful methods to your Rails app to validate, display and save phone numbers. It uses the super awesome Phony gem (https://github.com/floere/phony).

License: MIT License

Ruby 100.00%

phony_rails's Introduction

PhonyRails Build Status Coverage Status Dependencies Status

This small Gem adds useful methods to your Rails app to validate, display and save phone numbers. It uses the super awesome Phony gem (https://github.com/floere/phony).

Find version information in the CHANGELOG.

Installation

Add this line to your application's Gemfile (requires Ruby > 2.3):

gem 'phony_rails'

And then execute:

$ bundle

Or install it yourself as:

$ gem install phony_rails

Usage

Normalization / Model Usage

ActiveRecord

For ActiveRecord, in your model add:

class SomeModel < ActiveRecord::Base
  # Normalizes the attribute itself before validation
  phony_normalize :phone_number, default_country_code: 'US'

  # Normalizes attribute before validation and saves into other attribute
  phony_normalize :phone_number, as: :phone_number_normalized_version, default_country_code: 'US'

  # Creates method normalized_fax_number that returns the normalized version of fax_number
  phony_normalized_method :fax_number

  # Conditionally normalizes the attribute
  phony_normalize :recipient, default_country_code: 'US', if: -> { contact_method == 'phone_number' }
end

ActiveModel (models without database)

For Rails-like models without a database, add:

class SomeModel
  include ActiveModel::Model # we get AR-like attributes and validations
  include ActiveModel::Validations::Callbacks # a dependency for normalization

  # your attributes must be defined, they are not inherited from a DB table
  attr_accessor :phone_number, :phone_number_as_normalized

  # Once the model is set up, we have the same things as with ActiveRecord
  phony_normalize :phone_number, default_country_code: 'US'
end

Mongoid (DEPRECATED)

WARNING: From v0.15.0 Mongoid support has been removed!

General info

The :default_country_code options is used to specify a country_code when normalizing.

PhonyRails will also check your model for a country_code method to use when normalizing the number. So '070-12341234' with country_code 'NL' will get normalized to '+317012341234'.

You can also do-it-yourself and call:

# Options:
#   :country_code => The country code we should use (forced).
#   :default_country_code => Some fallback code (eg. 'NL') that can be used as default (comes from phony_normalize_numbers method).

PhonyRails.normalize_number('some number', country_code: 'NL')

PhonyRails.normalize_number('+4790909090', country_code: 'SE') # => '+464790909090' (forced to +46)
PhonyRails.normalize_number('+4790909090', default_country_code: 'SE') # => '+4790909090' (still +47 so not changed)

The country_code should always be a ISO 3166-1 alpha-2 (http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2).

Default for all models

You can set the default_country_code for all models using:

PhonyRails.default_country_code = "US"

Validation

In your model use the Phony.plausible method to validate an attribute:

validates :phone_number, phony_plausible: true

or the helper method:

validates_plausible_phone :phone_number

this method use other validators under the hood to provide:

  • presence validation using ActiveModel::Validations::PresenceValidator
  • format validation using ActiveModel::Validations::FormatValidator

so we can use:

validates_plausible_phone :phone_number, presence: true
validates_plausible_phone :phone_number, with: /\A\+\d+/
validates_plausible_phone :phone_number, without: /\A\+\d+/
validates_plausible_phone :phone_number, presence: true, with: /\A\+\d+/

the i18n key is :improbable_phone. Languages supported by default: de, en, es, fr, it, ja, kh, ko, nl, pt, tr, ua and ru.

You can also validate if a number has the correct country number:

validates_plausible_phone :phone_number, country_number: '61'

or correct country code:

validates_plausible_phone :phone_number, country_code: 'AU'

You can validate against the normalized input as opposed to the raw input:

phony_normalize :phone_number, as: :phone_number_normalized, default_country_code: 'US'
validates_plausible_phone :phone_number_normalized, presence: true, if: :phone_number?

Validation supports phone numbers with extension, such as +18181231234 x1234 or '+1 (818)151-5483 #4312' out-of-the-box.

Return original value after validation:

The flag normalize_when_valid (disabled by default), allows to return the original phone_number when is the object is not valid. When phone validation fails, normalization is not triggered at all. It could prevent a situation where user fills in the phone number and after validation, he gets back different, already normalized phone number value, even if phone number was wrong.

Example usage:

validates_plausible_phone :phone_number
phony_normalize :phone_number, country_code: :country_code, normalize_when_valid: true

Filling in the number will result with following:

When the number is incorrect (e.g. phone_number: +44 888 888 888 for country_code 'PL'), the original validation behavior is preserved, but if the number is still invalid, the original value is returned. When number is valid, it will save the normalized number (e.g. +48 888 888 888 will be saved as +48888888888).

Allowing records country codes to not match phone number country codes

You may have a record specifying one country (via a country_code attribute) but using a phone number from another country. For example, your record may be from Japan but have a phone number from the Philippines. By default, phony_rails will consider your record's country_code as part of the validation. If that country doesn't match the country code in the phone number, validation will fail.

Additionally, phony_normalize will always add the records country code as the country number (eg. the user enters '+81xxx' for Japan and the records country_code is 'DE' then phony_normalize will change the number to '+4981'). You can turn this off by adding enforce_record_country: false to the validation options. The country_code will then only be added if no country code is specified.

If you want to allow records from one country to have phone numbers from a different one, there are a couple of options you can use: ignore_record_country_number and ignore_record_country_code. Use them like so:

validates :phone_number, phony_plausible: { ignore_record_country_code: true, ignore_record_country_number: true }

Obviously, you don't have to use both, and you may not need or want to set either.

Display / Views

In your views use:

<%= "311012341234".phony_formatted(format: :international, spaces: '-') %>
<%= "+31-10-12341234".phony_formatted(format: :international, spaces: '-') %>
<%= "+31(0)1012341234".phony_formatted(format: :international, spaces: '-') %>

To first normalize the String to a certain country use:

<%= "010-12341234".phony_formatted(normalize: :NL, format: :international, spaces: '-') %>

To return nil when a number is not valid:

"123".phony_formatted(strict: true) # => nil

You can also use the bang method (phony_formatted!):

number = "010-12341234"
number.phony_formatted!(normalize: :NL, format: :international)
number # => "+31 10 123 41234"

You can also easily normalize a phone number String:

"+31 (0)30 1234 123".phony_normalized # => '31301234123'
"(0)30 1234 123".phony_normalized # => '301234123'
"(0)30 1234 123".phony_normalized(country_code: 'NL') # => '301234123'

Extensions are supported (identified by "ext", "ex", "x", "xt", "#", or ":") and will show at the end of the number:

"+31 (0)30 1234 123 x999".phony_normalized # => '31301234123 x999'
"+31 (0)30 1234 123 ext999".phony_normalized # => '31301234123 x999'
"+31 (0)30 1234 123 #999".phony_normalized # => '31301234123 x999'

Find by normalized number

Say you want to find a record by a phone number. Best is to normalize user input and compare to an attribute stored in the db.

Home.find_by_normalized_phone_number(PhonyRails.normalize_number(params[:phone_number]))

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Don't forget to add tests and run rspec before creating a pull request :)

See all contributors on https://github.com/joost/phony_rails/graphs/contributors.

phony_rails's People

Contributors

amatsuda avatar bdewater avatar berkos avatar cinconnu avatar dlikhten avatar espen avatar jcoleman avatar jeffltz avatar jell avatar jerryclinesmith avatar johnnyshields avatar jonathan-wheeler avatar kukunin avatar marcantonio avatar mattruzicka avatar monfresh avatar olivierpichon avatar pazaricha avatar pjg avatar ramaboo avatar robsonmafra avatar ross-hunter avatar rscnt avatar samda avatar shhavel avatar siong1987 avatar synion avatar toxix avatar toydestroyer avatar triskweline avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

phony_rails's Issues

Simple question about creating a record

Assuming I follow the README, am I supposed to be able open the rails console (rails c) and execute

User.first.update_attribute :phone_number, '<some phone string>'

and phony_rails will automatically normalize the string and save it into the table?

I seem to be missing something because no normalization is happening. Moreover, if I give it a clearly wrong phone number, e.g. User.first.update_attribute :phone_number, '1111', the commit is still successful.

In app/models/user.rb, I have:

  phony_normalize :phone_number, :default_country_code => 'US'
  validates :phone_number, phony_plausible: true

Thanks!

Make dependency on newer version of phony

Is there a reason that there's a pessimistic version constraint on phony version 1.7.7? I need a country that's included in v 1.8.4. I'm happy to make the change, but I wanted to ask first so I'm not breaking anything.

Allow validating against multiple countries

currently I can't figure out if it's possible to validate the country_code of a phone_number to be one of multiple country codes...

for example I was thinking

  # assume that by default the number is from US but allow numbers also from GB
  validates_plausible_phone :phone_number, country_code: ["GB", "US"]
  phony_normalize :phone_number, default_country_code: 'US'

so that I could validate if the number is a valid number in either the US or GB
but I'm not sure if that is possible under the current implementation or not

validator not included

Hi,
I'm quite new to ruby and rails but it seems that your validator is not required, so one cannot use it without an explicit :

require 'validators/phony_validator'

There is a typo in your doc :

validate :phone_number, :phony_plausible => true

should be (with an 's') :

validates :phone_number, :phony_plausible => true

French normalized number isn't good

PhonyRails.normalize_number("0606060606", default_country_code: 'FR')
=> "330606060606"
whereas it should give "33606060606". This output changed since updating phony from 1.9.0 to 2.0.2.

"06 06 06 06 06" is the local way of inputting numbers

Error with phony_normalize on migration

Hello,

Every time I run a migration concerning a model with a phony_normalize, the following exception is raised :

No attribute foo found on Model (PhonyRails)

The exception is raised from lib/phony_rails.rb:73.

A warning wouldn't be enough ? I have to comment every phony_normalize in my models before running a migration, then uncommenting them.

support for arrays in postgres

We store emails & phone numbers in arrays rather than in simple fields and use something like this to validate the array's attributes.

https://gist.github.com/ssimeonov/6519423

Which I'm attempting to use like so:

validates :phones, enum: { phony_plausible: true }

This works for other kinds of attributes but I can't get it to work with your gem.

I get the error

element 0 (7534721234) is an invalid number

However if I try 447534721234 it works fine.

I also double check that it worked on a single column and it worked fine. Any idea how I could fix this?

Thanks,

Nil return values for normalize cause validations to pass

Hi, I have in my User model:

phony_normalize :phone_number, default_country_code: 'US'
validates :phone_number, phony_plausible: true

One thing I noticed is that setting a string value that causes #normalize_number to return nil will pass validations:

u = User.find(blah)
u.phone_number = "Clearly invalid"
u.save!
=> true
u.phone_number
=> nil

However,

PhonyRails.plausible_number? nil
=> false

Am I doing the validation incorrectly? Setting a phone number like "12345" causes the validation to fail as expected.

default_country_code forces country code

Hi! I'm trying to use the default_country_code parameter while also making it possible for my users to type in an alternative country code themselves, the problem is that the default_country_code parameter seems to force the country code.

The below example is from the readme and is not working according to the documentation:

1.9.3p194 :005 > PhonyRails.normalize_number('+4790909090', :default_country_code => 'SE')
=> "464790909090"

It should yield "4790909090"

Some numbers not normalizing properly as of 0.12.1

Looks like a change causes some numbers to normalize incorrectly.

0.12.0

PhonyRails.normalize_number('2318725305', default_country_code: 'US')
 => "+12318725305"

0.12.1

PhonyRails.normalize_number('2318725305', default_country_code: 'US')
 => "+2318725305"

Phony 2.2.3 breaks test

Failures:

  1. PhonyRails PhonyRails#normalize_number should handle some edge cases
    Failure/Error: PhonyRails.normalize_number('0323-2269497', :country_code => 'BE').should eql('3232269497')
   expected: "3232269497"
        got: "323232269497"

   (compared using eql?)
 # ./spec/lib/phony_rails_spec.rb:151:in `block (3 levels) in <top (required)>'

Phone extension support

I was wondering if phone extensions are currently supported ?

When I try to enter a phone number, followed by a comma and a phone extension, I get a validation error.

Thanks !

Issue with brazilian numbers

When I put a brazilian number without its country code (55) like this (65) 3333-3333, it should be prefixed with brazil code +55, shouldn't it?

Following others examples the number above should be +556533333333.


I have this in my model:

    ...
    validates_plausible_phone :telephone, :presence => true, :normalized_country_code => 'pt-BR'
    validates_plausible_phone :cellphone, :presence => true, :normalized_country_code => 'pt-BR'

    phony_normalize :telephone, :country_code => 'pt-BR'
    phony_normalize :cellphone, :country_code => 'pt-BR'
    ...

Thanks in advance

Rails not recognizing phony_rails method

Rails 4.1
Ruby 2.0
Windows 8.1

I am using the phony_rails gem

In module models/concerns/sanitizable.rb, I have:

module Sanitizable
  extend ActiveSupport::Concern

  included do
    before_save :sanitize_phones_and_email
  end

  def sanitize_phones_and_email
    (self.email = email.downcase) if attribute_present?("email")
    (self.work_phone = phony_normalize work_phone, :default_country_code => 'US') if attribute_present?("work_phone")
    (self.mobile_phone = phony_normalize mobile_phone, :default_country_code => 'US') if attribute_present?("mobile_phone")
    (self.fax_phone = phony_normalize fax_phone, :default_country_code => 'US') if attribute_present?("fax_phone")
    (self.other_phone = phony_normalize :other_phone, :default_country_code => 'US') if attribute_present?("other_phone")
  end
end

In models/agent.rb, I have the following:

class Agent < ActiveRecord::Base
  include Sanitizable

  validates :first, presence: true
  validates :last, presence: true

end

In controllers/agents_controller, I have the following:

def new
  @agent = Agent.new
end

def create
  @agent = Agent.new(agent_params)
  respond_to do |format|
    if @agent.save
      format.html { redirect_to @agent, notice: 'Agent was successfully created.' }
      format.json { render :show, status: :created, location: @agent }
    else
      format.html { render :new }
      format.json { render json: @agent.errors, status: :unprocessable_entity }
    end
  end
end

In my helpers/agent_helper.file, I have the following method:

def create_new_agent_manually(row)
  agent = Hash.new
  agent['first'] = row[1]
  agent['last'] = row[2]
  agent['work_phone'] = row[5]
  agent['mobile_phone'] = row[6]
  agent['fax_phone'] = row[7]
  agent['other_phone'] = row[8]
  agent['email'] = row[9]
  new_agent = Agent.create(agent)
end

When create_new_agent_manually gets called, I get the following error message:

undefined method `phony_normalize' for #<Agent:0x00000006fcbdd0>      

and it provides a line number that corresponds to this line in sanitizable.rb:

(self.work_phone = phony_normalize work_phone, :default_country_code => 'US') if attribute_present?("work_phone")

The reason I have the before_save action in this separate module, is that it's used by at least three separate models and I don't want to repeat myself. In my application, I am importing data from an XLS spreadsheet (that part is working fine), and passing each row to the methods above. Any ideas?

Unable to run migrations if "as" attribute added

Sorry about the poor title, couldn't figure out a better way to succinctly describe this issue.

I've got a User model with a phone_number attribute, I now want to start normalising this phone number into a separate field, so I've added a formatted_phone_number column and:

class User < ActiveRecord::Base
  phony_normalize :phone_number, as: :formatted_phone_number, default_country_code: 'AU'
end

Then, trying to run migrations to actually add the column (or do anything else with rake) will fail with:

ArgumentError: 'formatted_phone_number' is not an attribute on User. You might want to use 'phony_normalized_method :phone_number' (PhonyRails)

Which means I can't add the attribute. I can comment out the phony_normalize and run migrations, then add it back in, but this causes issues with deployments and CI.

Use Phony 2.0

I noticed there were some errors with using Phony 2.0. Haven't started looking at the reasons yet but opening this issue to get some discussion on it.

Invalid numbers should not be formatted

"9090909".phony_formatted(:normalize => :NO, :format => :international)
=> "+47 909 09 09"

Phony.plausible?('+479090909')
=> false

Suggestion: Any number that is not plausible should return nil.

Clarify Indended Functionality and Require a Default Country Code

The phony gem only intends to operate on internationalized phone numbers (as non-discriminately written on that repo's README). I think that this fact should be directly and strongly stated on this README and I would be more than happy to assist in doing that.

Moreover, why isn't default_country_code a required argument to phony_normalize? If there is a country code specified in the input phone number, then that country code is used (overriding the default_country_code). If a country code isn't given in the phone number, then the default_country_code for the given country will be prepended and the resulting number will be properly parsed by phony (as it is now an internationalized phone number).

Phone numbers with extensions

I tried to use phony_rails a few minutes ago and I run into a problem validating phone numbers containing extensions.

Let's say my base phone number (in Luxembourg) is +352 123 456
This will be followed by 3 digits extensions, for example +352 123 456 777 is a valid number here but it fails to validate. +352 123 456 1 fails to validate too, even if it is a valid number, however, +352 123 456 77 works fine.

Are there any options to skip the length validation part of the numbers as this seems to be the issue ?

Validation fails if record country code does not match code in phone number

Use case: Suppose you moved to Thailand but still have a Japanese phone number (not contrived-- seeing this in production).

Heart of the issue: The validator has this line @record.errors.add(attribute, error_message) if not Phony.plausible?(value, cc: country_number). That call to country_number will first look to see if a country code was supplied in the options. Then it will check to see if the record has a country code. If it doesn't have that, then it checks to see if the record has a country, which it then uses to look up a country code.

So, passing in nil as the country_number option won't work, because the validator will fallback to looking things up on the record.

So, I realize I could rename columns on my models, but for obvious reasons I'd rather avoid that.

2 questions:

  • 1 - Am I off my rocker here and missing something simple?
  • 2 - Are you open to a PR that fixes this? I was thinking something along the lines of an option that allows the record's country and the number's to not match. I pick that direction, because it wouldn't change functionality for existing users. Something like, :allow_record_and_phone_country_mismatch. It's kind of long, but I think it communicates the issue.

Thanks!

TAG on release

Hi, can you use TAG in release process? Is more easy to upgrade with the diff.

UK 0203 numbers not handled correctly

0203 numbers (London, UK) seem to not be recognised as UK numbers

[13] pry(main)> PhonyRails.normalize_number('02031234567', default_country_code:'GB', add_plus:false)
=> "2031234567"

0207 numbers are handled correctly.

[14] pry(main)> PhonyRails.normalize_number('02071234567', default_country_code:'GB', add_plus:false)
=> "442071234567"

With country code this works fine.

[15] pry(main)> PhonyRails.normalize_number('02031234567', country_code:'GB', add_plus:false)

=> "442031234567"

The issue appears to be the following:

[24] pry(main)> Phony.plausible?('02031234567')
=> true
[25] pry(main)> Phony.plausible?('02071234567')
=> false
[22] pry(main)> PhonyRails.country_code_from_number('02031234567')
=> "20"
[23] pry(main)> PhonyRails.country_code_from_number('02071234567')
=> nil

Not sure how to stop Phony thinking that an 0203 number is from Egypt...?

Update README

Had an issue with eager_load and mongoid when using sidekiq that Mongoid::Phony is not found. The solution is to include phony_rails after mongoid in Gemfile.

Please write it somewhere in the README for future references.

Mongoid Error Message

The following is raised when using mongoid with phony_plausible: true

Mobile translation missing: en.mongoid.errors.models.user.attributes.mobile.improbable_phone

it's not very user friendly.

Country Number out of Country gem

You can use this to initialize your countries numbers ;)

PhonyRails::COUNTRY_NUMBER = ISO3166::Country::Data.map do |country, data| 
  [country, data['country_code']]
end.inject({}) do |hash, (name, code)| 
  hash[name] = code;
  hash
end

It will load all the countries data and codes into your hash.

gem countries https://github.com/hexorx/countries

Does not normalize when validations are skipped

This might be a uncommon use case, but I have an import function (via excel/csv sheets).

If the object (lets call it ContactPerson) is not valid (eg misses fields etc...) I want to be able to use contact_person.save(validate: false), but if it contains a mobile number still have it normalized.

This is currently not the case.

Note that I probably should override my presence validators when importing, instead of skipping ALL validations, but still I find it unexpected that phony_normalize runs before_validation, instead of before_save, or even on the setter.

Although I am not sure what I expect it to do when the number can not be normalized (eg, is invalid)...

My current proposal is
A) normalize the number in before_save
B1) if the number is not valid, just store the value as if (if validations are skipped)
B2) if the number is valid just store the normalization.

This is the most backwards compatible, without breaking most existing expectations. Although it isn't really the least suprise either.

My main concern is that when not running validations, numbers are not normalized which ruins my search methods....

Hoping this makes a little sense, as I am quite confused myself :)

Method phony_formatted return "undefined method `split' for 1:Fixnum"

Here is a screenshot from the console:
screen shot 2015-03-02 at 13 01 16

It should be returning nil or throwing an error in that case (depends on the behavior you want). I don't really know about every phone number possible but someone entered "8887716095" and it was wrong. He probably wanted: +1 888-771-6095 so it should work!

inconsistent normalization

Sample uses of normalization functions:

> '81234567'.phony_normalized country_code: 'SG'
 => "+6581234567"
> PhonyRails.normalize_number '81234567', country_code: 'SG'
 => "+6581234567"
> Phony.normalize '81234567', cc: '65'
 => "6581234567" 
> '81234567'.phony_normalized country_code: 'SG', add_plus: false
 => "+6581234567"
> PhonyRails.normalize_number '81234567', country_code: 'SG', add_plus: false
 => "6581234567"
> PhonyRails.normalize_number '81234567', add_plus: true
 => "+81234567"

There are a few problems:

  1. String#phony_normalized's behaviour is not consistent with PhonyRails.normalize_number
  2. add_plus doesn't verify whether the number includes a country code
  3. add_plus defaults to true while Phony#split and Phony#format don't work with pluses

ad 1.
Should be easily fixed by passing all options to PhonyRails.normalize_number instead of just country_code

ad 2.
PhonyRails should check whether phone number is Phony.plausible? before appending +

ad 3.
What's the rationale behind add_plus defaulting to true? Is it to make clear the numbers are international? While it makes perfect sense, I believe it should default to false for the sake of compatibility with Phony. It should at least be well documented on the front page.

Let me know whether you agree with my comments and I can submit pull requests for all three points.

uninitialized constant Listen::Turnstile

To reproduce the problem (Mac OS X):

$ git clone https://github.com/joost/phony_rails
$ cd phony_rails
$ bundle install
$ bundle exec guard

Produces the following error (even after bundle update):

/Users/mera/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/guard-1.2.3/lib/guard.rb:48:in `setup': uninitialized constant Listen::Turnstile (NameError)
    from /Users/mera/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/guard-1.2.3/lib/guard.rb:154:in `start'
    from /Users/mera/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/guard-1.2.3/lib/guard/cli.rb:100:in `start'
    from /Users/mera/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/thor-0.19.1/lib/thor/command.rb:27:in `run'
    from /Users/mera/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/thor-0.19.1/lib/thor/invocation.rb:126:in `invoke_command'
    from /Users/mera/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/thor-0.19.1/lib/thor.rb:359:in `dispatch'
    from /Users/mera/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/thor-0.19.1/lib/thor/base.rb:440:in `start'
    from /Users/mera/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/guard-1.2.3/bin/guard:6:in `<top (required)>'
    from /Users/mera/.rbenv/versions/2.0.0-p247/bin/guard:23:in `load'
    from /Users/mera/.rbenv/versions/2.0.0-p247/bin/guard:23:in `<main>'

License missing from gemspec

RubyGems.org doesn't report a license for your gem. This is because it is not specified in the gemspec of your last release.

via e.g.

spec.license = 'MIT'
# or
spec.licenses = ['MIT', 'GPL-2']

Including a license in your gemspec is an easy way for rubygems.org and other tools to check how your gem is licensed. As you can imagine, scanning your repository for a LICENSE file or parsing the README, and then attempting to identify the license or licenses is much more difficult and more error prone. So, even for projects that already specify a license, including a license in your gemspec is a good practice. See, for example, how rubygems.org uses the gemspec to display the rails gem license.

There is even a License Finder gem to help companies/individuals ensure all gems they use meet their licensing needs. This tool depends on license information being available in the gemspec. This is an important enough issue that even Bundler now generates gems with a default 'MIT' license.

I hope you'll consider specifying a license in your gemspec. If not, please just close the issue with a nice message. In either case, I'll follow up. Thanks for your time!

Appendix:

If you need help choosing a license (sorry, I haven't checked your readme or looked for a license file), GitHub has created a license picker tool. Code without a license specified defaults to 'All rights reserved'-- denying others all rights to use of the code.
Here's a list of the license names I've found and their frequencies

p.s. In case you're wondering how I found you and why I made this issue, it's because I'm collecting stats on gems (I was originally looking for download data) and decided to collect license metadata,too, and make issues for gemspecs not specifying a license as a public service :). See the previous link or my blog post about this project for more information.

Error when normalizing long telephone numbers with default country code

PhonyRails.normalize_number has a bug, where it will incorrectly normalize long telephone numbers.

actual behaviour / code:

irb(main):017:0> PhonyRails.normalize_number '01701234567890', :default_country_code => 'DE'
=> "4901701234567890"
irb(main):018:0> PhonyRails.normalize_number '0170123456789', :default_country_code => 'DE'
=> "49170123456789"

Expected behaviour:

The result of the first number should NOT start with "4901" but with "491"

add a wiki

so I can add some things, starting with a RSpec matcher
thanks

Already normalized numbers have default country code prepended

Scenario: A model has 3 phone number fields all with a default_country_code: 'AU'. Setting one of them to explicitly be a foreign number using a + in the number correctly normalises the value as expected. However, after modifying the model and saving it again, the number stored in the database will have the default country code prepended to the phone number that was already perfectly valid. Here's code to illustrate the problem:

class Person < ActiveRecord::Base
  phony_normalize :phone_home,   default_country_code: 'AU'
  phony_normalize :phone_mobile, default_country_code: 'AU'
  phony_normalize :phone_work,   default_country_code: 'AU'
end

Now, I'll create a person with an Australian mobile number and American home number.

When the model is saved, the numbers are correctly normalised. The Australian number is prefixed with 61 and the American number is prefixed with 1. Everything is perfect.

Then, I set the work phone number to another perfectly valid Australian number. When saving, the number is again correctly normalised with a leading 61. However, you'll notice that the home number, the American one, got 61 tacked onto the front of it! This is the problem.

If the assumption is that the numbers stored in the database are already normalised and start with the country code, why is the country code being added again?

irb(main):001:0> p = Person.new(phone_mobile: '0450 764 000', phone_home: '+1 978 555 0000')
=> #<Person id: nil, phone_home: "+1 978 555 0000", phone_mobile: "0450 764 000", phone_work: nil>
irb(main):002:0> p.save!
   (0.2ms)  begin transaction
  SQL (0.5ms)  INSERT INTO "people" ("phone_mobile", "phone_home") VALUES (?, ?)  [["phone_mobile", "61450764000"], ["phone_home", "19785550000"]]
   (2.0ms)  commit transaction
=> true
irb(main):003:0> p.phone_work = '0200 777 000'
=> "0200 777 000"
irb(main):004:0> p
=> #<Person id: 1, phone_home: "19785550000", phone_mobile: "61450764000", phone_work: "0200 777 000">
irb(main):005:0> p.save
   (0.1ms)  begin transaction
  SQL (0.5ms)  UPDATE "people" SET "phone_work" = ?, "phone_home" = ? WHERE "people"."id" = ?  [["phone_work", "61200777000"], ["phone_home", "6119785550000"], ["id", 1]]
   (1.1ms)  commit transaction
=> true

Phony 2.1 incompatibility related to country codes/numbers

In phony_validator, in the common case, a country code is passed to the Phony.plausible? method:

@record.errors.add(attribute, error_message) if not Phony.plausible?(value, cc: country_code_or_country_number)

While Phony expects cc to be specifically a country number, otherwise the phone number will not be plausible.

Phony.plausible?('+1 555 1234 123', cc: 'US')
=> false

Phony.plausible?('+1 555 1234 123', cc: '1')
=> true

The solution is to do the ISO3166::Country::Data conversion from country code to country number.

I'll try to create a PR for that this week.

problem with v 0.2.1

thank you for this nice gem,
just updated to v 0.2.1 and I'm having the following issue

screenshot_199

validator insists my field doesn't exist , it worked well with 0.2.0

Error when formatting invalid numbers

"+479090909".phony_formatted(:normalize => :NO, :format => :international)
NoMethodError: undefined method split' for 1:Fixnum from /phony-2.0.1/lib/phony/country_codes.rb:70:insplit'

+479090909 is missing a digit and is thus invalid. From Phony:

Phony.plausible?('+479090909', cc: '47')
=> false

Using a number different from the country

Hi,
thanks for this great gem! I'm not sure if this is is a phony or phony_rails issue:

I have a validation in the model that goes like this:

phony_normalize :phone
  validates :phone, phony_plausible: true, presence: true

This works fine when the user wants to add a number that has the same country code/prefix than the country_code from the address. If the user types a number from another country, prefixed by + so that it's clear that there already is a country code the country prefix from the record's country code is added.

Is that a bug or a feature? In this case I want that the user can specify a number from another country, but the number is prefixed by default with the country prefix from the record's country_code. Is that possible? I saw that there is an undocumented ignore_record_country_code option but that seems to ignore the country code at all.

"translation missing" when using validator on non-activerecord backed models

I have a model that's not an ActiveRecord subclass:

class Demo
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end

  attr_accessor :phone
  validates_plausible_phone :phone
end

It has this validator:

validates :phone, :phony_plausible => true

But I've also tried:

validates_plausible_phone :phone

Either way, when I attempt to save with an invalid phone number, the validation message displayed to the user is:

Phone translation missing: en.activemodel.errors.models.demo.attributes.phone.improbable_phone

If I use the validators on an ActiveRecord-backed model:

class User < ActiveRecord::Base
  attr_accessible :phone 
  validates_plausible_phone :phone
end

I get the correct validation message:

Phone is an invalid number

I'm happy to manually add the translation but I was just wondering if this is expected?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.