Skip to content

Instantly share code, notes, and snippets.

@joahking
Last active November 1, 2016 22:11
Show Gist options
  • Save joahking/a70b85020eaffcb5c17e0ae4ef326c47 to your computer and use it in GitHub Desktop.
Save joahking/a70b85020eaffcb5c17e0ae4ef326c47 to your computer and use it in GitHub Desktop.
example of usage of concerns
# app/models/concerns/phone_number.rb
# concern to validate spanish phone numbers and provide some custom formatters
module PhoneNumber
extend ActiveSupport::Concern
PHONE_REGEXP = /\+\d{2}\s\d{3}\s\d{3}\s\d{3}/.freeze # e.g. +34 900 123 123
included do
validates :phone_number, presence: true, format: { with: PHONE_REGEXP, message: "invalid phone number" }
end
def phone_format_00
phone_number.gsub(/\+/, '00')
end
end
# app/models/store.rb
class Store < ActiveRecord::Base
include PhoneNumber
end
# app/models/user.rb
class User < ActiveRecord::Base
include PhoneNumber
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment