├── .gitignore ├── .rspec ├── Gemfile ├── LICENSE.txt ├── README.md ├── Rakefile ├── lib ├── rut_validation.rb ├── rut_validation │ └── version.rb ├── string_validator.rb └── validator.rb ├── rut_validation.gemspec └── spec ├── dummy ├── Rakefile ├── app │ └── models │ │ ├── .gitkeep │ │ └── user.rb ├── config.ru ├── config │ ├── application.rb │ ├── boot.rb │ ├── database.yml │ ├── environment.rb │ ├── initializers │ │ ├── backtrace_silencers.rb │ │ ├── inflections.rb │ │ ├── mime_types.rb │ │ ├── secret_token.rb │ │ ├── session_store.rb │ │ └── wrap_parameters.rb │ ├── locales │ │ └── en.yml │ └── routes.rb └── db │ ├── development.sqlite3 │ ├── migrate │ └── 20130813013807_create_users.rb │ ├── schema.rb │ ├── seeds.rb │ └── test.sqlite3 ├── lib └── rut_validator_spec.rb └── spec_helper.rb /.gitignore: -------------------------------------------------------------------------------- 1 | *.gem 2 | *.rbc 3 | .bundle 4 | .config 5 | .yardoc 6 | Gemfile.lock 7 | InstalledFiles 8 | _yardoc 9 | coverage 10 | doc/ 11 | lib/bundler/man 12 | pkg 13 | rdoc 14 | spec/reports 15 | test/tmp 16 | test/version_tmp 17 | tmp 18 | spec/dummy/log 19 | spec/dummy/tmp -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --color 2 | --format progress 3 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | # Specify your gem's dependencies in rut_validation.gemspec 4 | gemspec 5 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013 Christopher Fernández 2 | 3 | MIT License 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the 7 | "Software"), to deal in the Software without restriction, including 8 | without limitation the rights to use, copy, modify, merge, publish, 9 | distribute, sublicense, and/or sell copies of the Software, and to 10 | permit persons to whom the Software is furnished to do so, subject to 11 | the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 20 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 22 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rut Validation 2 | 3 | Rut Validation provides a run/rut chilean validator for your model attributes or a single string. 4 | 5 | [![Gem Version](https://badge.fury.io/rb/rut_validation.png)](http://badge.fury.io/rb/rut_validation) 6 | [![Build Status](https://travis-ci.org/Phifo/rut_validation.png?branch=master)](https://travis-ci.org/Phifo/rut_validation) 7 | 8 | ## Installation 9 | 10 | Add this line to your application's Gemfile: 11 | 12 | gem 'rut_validation' 13 | 14 | And then execute: 15 | 16 | $ bundle 17 | 18 | Or install it yourself as: 19 | 20 | $ gem install rut_validation 21 | 22 | ## Usage 23 | 24 | If you want to validate a model attribute you just need to set `rut: true` (like any model validation in Rails): 25 | 26 | ```ruby 27 | class User < ActiveRecord::Base 28 | attr_accessible :rut 29 | 30 | validates :rut, rut: true 31 | end 32 | ``` 33 | 34 | If you want to validate a single string: 35 | 36 | "16329351-K".rut_valid? 37 | => true 38 | "7654764-8".rut_valid? 39 | => false 40 | 41 | ## Contributing 42 | 43 | 1. Fork it 44 | 2. Create your feature branch (`git checkout -b my-new-feature`) 45 | 3. Commit your changes (`git commit -am 'Add some feature'`) 46 | 4. Push to the branch (`git push origin my-new-feature`) 47 | 5. Create new Pull Request 48 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require "bundler/gem_tasks" 2 | require "rspec/core/rake_task" 3 | 4 | RSpec::Core::RakeTask.new 5 | 6 | task :default => :spec -------------------------------------------------------------------------------- /lib/rut_validation.rb: -------------------------------------------------------------------------------- 1 | require "rut_validation/version" 2 | require "string_validator" 3 | require "validator" -------------------------------------------------------------------------------- /lib/rut_validation/version.rb: -------------------------------------------------------------------------------- 1 | # Gem version 2 | 3 | module RutValidation 4 | VERSION = "1.1.0" 5 | end 6 | -------------------------------------------------------------------------------- /lib/string_validator.rb: -------------------------------------------------------------------------------- 1 | # Add a rut_valid? method to the String class. 2 | 3 | class String 4 | ## 5 | # Validates if the string has the rut/run syntax and 6 | # calculates/validate the digit 7 | # @return [true, false] 8 | def rut_valid? 9 | if not(self =~ /\A(\d{7,8})\-(\d{1}|k|K)\Z/i) and not(self =~ /\A(\d{1,3})\.(\d{1,3})\.(\d{1,3})\-(k|K|\d{1})\Z/) 10 | return false 11 | end 12 | 13 | results = Array.new 14 | rut = self.strip.split("-").first.delete(".").to_i 15 | numerical_serie = 2 16 | 17 | while rut > 0 18 | results.push (rut % 10) * numerical_serie 19 | rut = rut / 10 20 | numerical_serie += 1 21 | numerical_serie = 2 if numerical_serie > 7 22 | end 23 | 24 | digit = 11 - (results.inject(:+) % 11) 25 | 26 | if digit == 10 27 | digit = "k" 28 | elsif digit == 11 29 | digit = "0" 30 | else 31 | digit = digit.to_s 32 | end 33 | 34 | if digit == self.strip.split("-").last.downcase 35 | return true 36 | else 37 | return false 38 | end 39 | end 40 | end -------------------------------------------------------------------------------- /lib/validator.rb: -------------------------------------------------------------------------------- 1 | ## 2 | # Validates if the given string has the correct rut/run syntax 3 | # and if the rut/run has the correct digit. 4 | 5 | class RutValidator < ActiveModel::EachValidator 6 | ## 7 | # @param value [String] the string to be validated 8 | def validate_each(record, attribute, value) 9 | if value.nil? or not value.is_a?(String) 10 | record.errors[attribute] << (options[:message] || "is not a valid rut") 11 | elsif not value.rut_valid? 12 | record.errors[attribute] << (options[:message] || "is not a valid rut") 13 | end 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /rut_validation.gemspec: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | lib = File.expand_path('../lib', __FILE__) 3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 4 | require 'rut_validation/version' 5 | 6 | Gem::Specification.new do |spec| 7 | spec.name = "rut_validation" 8 | spec.version = RutValidation::VERSION 9 | spec.authors = ["Christopher Fernández"] 10 | spec.email = ["fernandez.chl@gmail.com"] 11 | spec.description = %q{RUT/RUN Chilean validator for Rails models} 12 | spec.summary = %q{RUT/RUN Chilean validator for Rails models} 13 | spec.homepage = "" 14 | spec.license = "MIT" 15 | 16 | spec.files = `git ls-files`.split($/) 17 | spec.require_paths = ["lib"] 18 | 19 | spec.add_dependency "railties", ">= 4.1" 20 | 21 | spec.add_development_dependency "rspec", "~> 2.14" 22 | spec.add_development_dependency "activerecord", "~> 4.1" 23 | spec.add_development_dependency "sqlite3", "~> 1.3.9" 24 | end 25 | -------------------------------------------------------------------------------- /spec/dummy/Rakefile: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env rake 2 | # Add your own tasks in files placed in lib/tasks ending in .rake, 3 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 4 | 5 | require File.expand_path('../config/application', __FILE__) 6 | 7 | Dummy::Application.load_tasks 8 | -------------------------------------------------------------------------------- /spec/dummy/app/models/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Phifo/rut_validation/8b2b8bc30dbcf39709b1cf7c20c3e8adffad5892/spec/dummy/app/models/.gitkeep -------------------------------------------------------------------------------- /spec/dummy/app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ActiveRecord::Base 2 | validates :rut, rut: true 3 | end -------------------------------------------------------------------------------- /spec/dummy/config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require ::File.expand_path('../config/environment', __FILE__) 4 | run Dummy::Application 5 | -------------------------------------------------------------------------------- /spec/dummy/config/application.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path('../boot', __FILE__) 2 | 3 | require 'rails/all' 4 | 5 | if defined?(Bundler) 6 | # If you precompile assets before deploying to production, use this line 7 | Bundler.require(*Rails.groups(:assets => %w(development test))) 8 | # If you want your assets lazily compiled in production, use this line 9 | # Bundler.require(:default, :assets, Rails.env) 10 | end 11 | 12 | module Dummy 13 | class Application < Rails::Application 14 | config.encoding = "utf-8" 15 | config.active_support.deprecation = :stderr 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /spec/dummy/config/boot.rb: -------------------------------------------------------------------------------- 1 | require 'rubygems' 2 | 3 | # Set up gems listed in the Gemfile. 4 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 5 | 6 | require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) 7 | -------------------------------------------------------------------------------- /spec/dummy/config/database.yml: -------------------------------------------------------------------------------- 1 | # SQLite version 3.x 2 | # gem install sqlite3 3 | # 4 | # Ensure the SQLite 3 gem is defined in your Gemfile 5 | # gem 'sqlite3' 6 | development: 7 | adapter: sqlite3 8 | database: db/development.sqlite3 9 | pool: 5 10 | timeout: 5000 11 | 12 | # Warning: The database defined as "test" will be erased and 13 | # re-generated from your development database when you run "rake". 14 | # Do not set this db to the same as development or production. 15 | test: 16 | adapter: sqlite3 17 | database: db/test.sqlite3 18 | pool: 5 19 | timeout: 5000 20 | 21 | production: 22 | adapter: sqlite3 23 | database: db/production.sqlite3 24 | pool: 5 25 | timeout: 5000 26 | -------------------------------------------------------------------------------- /spec/dummy/config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the rails application 2 | require File.expand_path('../application', __FILE__) 3 | 4 | # Initialize the rails application 5 | Dummy::Application.initialize! 6 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format 4 | # (all these examples are active by default): 5 | # ActiveSupport::Inflector.inflections do |inflect| 6 | # inflect.plural /^(ox)$/i, '\1en' 7 | # inflect.singular /^(ox)en/i, '\1' 8 | # inflect.irregular 'person', 'people' 9 | # inflect.uncountable %w( fish sheep ) 10 | # end 11 | # 12 | # These inflection rules are supported but not enabled by default: 13 | # ActiveSupport::Inflector.inflections do |inflect| 14 | # inflect.acronym 'RESTful' 15 | # end 16 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | # Mime::Type.register_alias "text/html", :iphone 6 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/secret_token.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | # Make sure the secret is at least 30 characters and all random, 6 | # no regular words or you'll be exposed to dictionary attacks. 7 | Dummy::Application.config.secret_token = '466413fb3b0e35e50ebbcf019eb7b35e0b1f3334a89a9e6ffefea9be70e394751d83563bd5d2447dc947bee33f882efd1e23682c507b2bca82d2735ddafbf554' 8 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/session_store.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | Dummy::Application.config.session_store :cookie_store, key: '_dummy_session' 4 | 5 | # Use the database for sessions instead of the cookie-based default, 6 | # which shouldn't be used to store highly confidential information 7 | # (create the session table with "rails generate session_migration") 8 | # Dummy::Application.config.session_store :active_record_store 9 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | # 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] 9 | end 10 | 11 | # Disable root element in JSON by default. 12 | ActiveSupport.on_load(:active_record) do 13 | self.include_root_in_json = false 14 | end 15 | -------------------------------------------------------------------------------- /spec/dummy/config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Sample localization file for English. Add more files in this directory for other locales. 2 | # See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points. 3 | 4 | en: 5 | hello: "Hello world" 6 | -------------------------------------------------------------------------------- /spec/dummy/config/routes.rb: -------------------------------------------------------------------------------- 1 | Dummy::Application.routes.draw do 2 | # The priority is based upon order of creation: 3 | # first created -> highest priority. 4 | 5 | # Sample of regular route: 6 | # match 'products/:id' => 'catalog#view' 7 | # Keep in mind you can assign values other than :controller and :action 8 | 9 | # Sample of named route: 10 | # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase 11 | # This route can be invoked with purchase_url(:id => product.id) 12 | 13 | # Sample resource route (maps HTTP verbs to controller actions automatically): 14 | # resources :products 15 | 16 | # Sample resource route with options: 17 | # resources :products do 18 | # member do 19 | # get 'short' 20 | # post 'toggle' 21 | # end 22 | # 23 | # collection do 24 | # get 'sold' 25 | # end 26 | # end 27 | 28 | # Sample resource route with sub-resources: 29 | # resources :products do 30 | # resources :comments, :sales 31 | # resource :seller 32 | # end 33 | 34 | # Sample resource route with more complex sub-resources 35 | # resources :products do 36 | # resources :comments 37 | # resources :sales do 38 | # get 'recent', :on => :collection 39 | # end 40 | # end 41 | 42 | # Sample resource route within a namespace: 43 | # namespace :admin do 44 | # # Directs /admin/products/* to Admin::ProductsController 45 | # # (app/controllers/admin/products_controller.rb) 46 | # resources :products 47 | # end 48 | 49 | # You can have the root of your site routed with "root" 50 | # just remember to delete public/index.html. 51 | # root :to => 'welcome#index' 52 | 53 | # See how all your routes lay out with "rake routes" 54 | 55 | # This is a legacy wild controller route that's not recommended for RESTful applications. 56 | # Note: This route will make all actions in every controller accessible via GET requests. 57 | # match ':controller(/:action(/:id))(.:format)' 58 | end 59 | -------------------------------------------------------------------------------- /spec/dummy/db/development.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Phifo/rut_validation/8b2b8bc30dbcf39709b1cf7c20c3e8adffad5892/spec/dummy/db/development.sqlite3 -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20130813013807_create_users.rb: -------------------------------------------------------------------------------- 1 | class CreateUsers < ActiveRecord::Migration 2 | def change 3 | create_table :users do |t| 4 | t.string :rut 5 | 6 | t.timestamps 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /spec/dummy/db/schema.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # This file is auto-generated from the current state of the database. Instead 3 | # of editing this file, please use the migrations feature of Active Record to 4 | # incrementally modify your database, and then regenerate this schema definition. 5 | # 6 | # Note that this schema.rb definition is the authoritative source for your 7 | # database schema. If you need to create the application database on another 8 | # system, you should be using db:schema:load, not running all the migrations 9 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 10 | # you'll amass, the slower it'll run and the greater likelihood for issues). 11 | # 12 | # It's strongly recommended to check this file into your version control system. 13 | 14 | ActiveRecord::Schema.define(:version => 20130813013807) do 15 | 16 | create_table "users", :force => true do |t| 17 | t.string "rut" 18 | t.datetime "created_at", :null => false 19 | t.datetime "updated_at", :null => false 20 | end 21 | 22 | end 23 | -------------------------------------------------------------------------------- /spec/dummy/db/seeds.rb: -------------------------------------------------------------------------------- 1 | # This file should contain all the record creation needed to seed the database with its default values. 2 | # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). 3 | # 4 | # Examples: 5 | # 6 | # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) 7 | # Mayor.create(name: 'Emanuel', city: cities.first) 8 | -------------------------------------------------------------------------------- /spec/dummy/db/test.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Phifo/rut_validation/8b2b8bc30dbcf39709b1cf7c20c3e8adffad5892/spec/dummy/db/test.sqlite3 -------------------------------------------------------------------------------- /spec/lib/rut_validator_spec.rb: -------------------------------------------------------------------------------- 1 | require "spec_helper" 2 | 3 | describe User do 4 | user = User.new 5 | it "should have a valid rut" do 6 | user.rut = "16329351-K" 7 | user.should be_valid 8 | user.rut = "6354455-8" 9 | user.should be_valid 10 | user.rut = "10.137.341-k" 11 | user.should be_valid 12 | end 13 | 14 | it "should detect invalid rut" do 15 | user.rut = "7654764-8" 16 | user.should_not be_valid 17 | user.rut = "67.124.556-8" 18 | user.should_not be_valid 19 | user.rut = "16329351.-K" 20 | user.should_not be_valid 21 | user.rut = nil 22 | user.should_not be_valid 23 | user.rut = 63544558 24 | user.should_not be_valid 25 | end 26 | end -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | ENV["RAILS_ENV"] = "test" 2 | 3 | require File.expand_path("../dummy/config/environment.rb", __FILE__) 4 | require "rut_validation" 5 | 6 | Rails.backtrace_cleaner.remove_silencers! --------------------------------------------------------------------------------