green_light 0.0.2

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,5 @@
1
+ *.gem
2
+ .bundle
3
+ Gemfile.lock
4
+ pkg/*
5
+ **/**/.*.swp
data/Gemfile ADDED
@@ -0,0 +1,5 @@
1
+ source 'http://rubygems.org'
2
+ gem 'rails'
3
+ gem "activerecord", :require => "active_record"
4
+ gem 'rspec'
5
+ gem 'supermodel'
data/README.rdoc ADDED
@@ -0,0 +1,52 @@
1
+ = green_light
2
+
3
+ Provides client side validation (with the help of the jquery validation plugin) while keeping validation in the model, where it belongs.
4
+
5
+
6
+ == Installation
7
+
8
+ Add green_light to your Gemfile and run the bundle install command.
9
+
10
+ gem 'green_light'
11
+ bundle install
12
+
13
+
14
+ == Usage
15
+
16
+ Run this generator to copy the required assets to your public folder:-
17
+
18
+ rails g green_light_assets
19
+
20
+ Download jQuery and the {jQuery Validation Plugin}[http://bassistance.de/jquery-plugins/jquery-plugin-validation/] and include them in your layout header.
21
+
22
+ Also, insert the following javascript include tag in your layout html header:-
23
+
24
+ <%= javascript_include_tag 'jquery.validate_regex', 'green_light' %>
25
+
26
+ Note, the green_light file specified above is generated dynamically, so it wont appear in your public javascripts folder.
27
+
28
+ Add the <tt>green_light</tt> class to the forms that you wish to have client side validation:-
29
+
30
+ <%= form_for(@model, :html => { :class => 'green_light' }) do |f| %>
31
+
32
+ And finally, add some validations to your models!
33
+
34
+
35
+ == Currently Supports these validations
36
+
37
+ validates_presence_of
38
+ validates_length_of
39
+ validates_format_of
40
+ validates_uniqueness_of
41
+ validates_numericality_of
42
+
43
+
44
+ == Requirements
45
+
46
+ jQuery versions 1.3.2, 1.4.2, 1.4.4, 1.5.0, 1.5.1
47
+
48
+
49
+ == Running the Tests
50
+
51
+ bundle install
52
+ bundle exec rspec spec
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require 'bundler'
2
+ Bundler::GemHelper.install_tasks
@@ -0,0 +1,24 @@
1
+ class JavascriptsController < ApplicationController
2
+ respond_to :js, :text
3
+
4
+ def green_light
5
+ @rules = GreenLight::Rules.generate(all_models)
6
+ respond_with(@rules)
7
+ end
8
+
9
+ def check_for_uniqueness
10
+ record = params[:model].constantize.where("#{params[:field]} = ?", params[params[:model].downcase.underscore][params[:field]])
11
+ if record.count > 0
12
+ render :text => "\"#{params[params[:model].downcase.underscore][params[:field]]} is already taken.\""
13
+ else
14
+ render :text => true
15
+ end
16
+ end
17
+
18
+ private
19
+ def all_models
20
+ tables = ActiveRecord::Base.connection.tables
21
+ tables.delete("schema_migrations")
22
+ tables.map { |table| table.camelize.singularize.constantize }
23
+ end
24
+ end
@@ -0,0 +1,3 @@
1
+ $().ready(function() {
2
+ $(".green_light").validate(<%= @rules.html_safe %>);
3
+ });
data/config/routes.rb ADDED
@@ -0,0 +1,4 @@
1
+ Rails.application.routes.draw do
2
+ match "/javascripts/green_light" => "javascripts#green_light"
3
+ match "/javascripts/check_for_uniqueness" => "javascripts#check_for_uniqueness"
4
+ end
@@ -0,0 +1,21 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+ require "green_light/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "green_light"
7
+ s.version = GreenLight::VERSION
8
+ s.platform = Gem::Platform::RUBY
9
+ s.authors = ["Phil McClure"]
10
+ s.email = ["pmcclure@rumblelabs.com"]
11
+ s.homepage = "http://www.rumblelabs.com"
12
+ s.summary = %q{Simple client side validation that keeps validation in the models}
13
+ s.description = %q{Simple client side validation that keeps validation in the models}
14
+
15
+ s.rubyforge_project = "green_light"
16
+
17
+ s.files = `git ls-files`.split("\n")
18
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
19
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
20
+ s.require_paths = ["lib"]
21
+ end
@@ -0,0 +1,14 @@
1
+ require 'active_support/all'
2
+ require File.join(File.dirname(__FILE__), 'green_light/engine')
3
+
4
+ module GreenLight
5
+ autoload :Rules, 'green_light/rules'
6
+
7
+ module Validations
8
+ autoload :ValidatesFormatOf, 'green_light/validations/validates_format_of'
9
+ autoload :ValidatesLengthOf, 'green_light/validations/validates_length_of'
10
+ autoload :ValidatesNumericalityOf, 'green_light/validations/validates_numericality_of'
11
+ autoload :ValidatesPresenceOf, 'green_light/validations/validates_presence_of'
12
+ autoload :ValidatesUniquenessOf, 'green_light/validations/validates_uniqueness_of'
13
+ end
14
+ end
@@ -0,0 +1,4 @@
1
+ module GreenLight #:nodoc:
2
+ class Engine < ::Rails::Engine #:nodoc:
3
+ end
4
+ end
@@ -0,0 +1,34 @@
1
+ module GreenLight
2
+ class Rules
3
+ include Validations::ValidatesFormatOf
4
+ include Validations::ValidatesLengthOf
5
+ include Validations::ValidatesNumericalityOf
6
+ include Validations::ValidatesPresenceOf
7
+ include Validations::ValidatesUniquenessOf
8
+
9
+ def self.generate(models)
10
+ data, rules = {}, {}
11
+ models.each do |model|
12
+ model._validators.each do |field_name, validations|
13
+ rules["#{model.to_s.underscore.downcase}[#{field_name}]"] = parse_each_validation(model, field_name, validations)
14
+ data[:rules] = rules
15
+ end
16
+ end
17
+ data.merge!({:errorElement => "span"})
18
+ data.to_json
19
+ end
20
+
21
+ private
22
+ def self.parse_each_validation(model, field_name, validation_objs)
23
+ data, params = {}, {}
24
+ params[:model], params[:field_name] = model, field_name
25
+ validation_objs.each do |val_obj|
26
+ params[:val_obj] = val_obj
27
+ # Call each validation method
28
+ result = send(val_obj.class.name.split('::').last.underscore, params)
29
+ data.merge!(result) unless result.nil?
30
+ end
31
+ data
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,14 @@
1
+ module GreenLight
2
+ module Validations
3
+ module ValidatesFormatOf
4
+ extend ActiveSupport::Concern
5
+
6
+ module ClassMethods
7
+ def format_validator(params = {})
8
+ {:regex => "#{params[:val_obj].options[:with]}".gsub('?-mix:', '')}
9
+ end
10
+ end
11
+ end
12
+ end
13
+ end
14
+
@@ -0,0 +1,16 @@
1
+ module GreenLight
2
+ module Validations
3
+ module ValidatesLengthOf
4
+ extend ActiveSupport::Concern
5
+
6
+ module ClassMethods
7
+ def length_validator(params = {})
8
+ min, max = {}, {}
9
+ min = {:minlength => params[:val_obj].options[:minimum]} if params[:val_obj].options[:minimum]
10
+ max = {:maxlength => params[:val_obj].options[:maximum]} if params[:val_obj].options[:maximum]
11
+ min.merge!(max)
12
+ end
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,14 @@
1
+ module GreenLight
2
+ module Validations
3
+ module ValidatesNumericalityOf
4
+ extend ActiveSupport::Concern
5
+
6
+ module ClassMethods
7
+ def numericality_validator(params = {})
8
+ {:regex => "^[0-9]*$"}
9
+ end
10
+ end
11
+ end
12
+ end
13
+ end
14
+
@@ -0,0 +1,14 @@
1
+ module GreenLight
2
+ module Validations
3
+ module ValidatesPresenceOf
4
+ extend ActiveSupport::Concern
5
+
6
+ module ClassMethods
7
+ def presence_validator(params = {})
8
+ {:required => true}
9
+ end
10
+ end
11
+ end
12
+ end
13
+ end
14
+
@@ -0,0 +1,13 @@
1
+ module GreenLight
2
+ module Validations
3
+ module ValidatesUniquenessOf
4
+ extend ActiveSupport::Concern
5
+
6
+ module ClassMethods
7
+ def uniqueness_validator(params = {})
8
+ { :remote => "/javascripts/check_for_uniqueness?model=#{params[:model].to_s}&field=#{params[:field_name]}" }
9
+ end
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,3 @@
1
+ module GreenLight
2
+ VERSION = "0.0.2"
3
+ end
@@ -0,0 +1,8 @@
1
+ Description:
2
+ Explain the generator
3
+
4
+ Example:
5
+ rails generate green_light_assets
6
+
7
+ This will create:
8
+ what/will/it/create
@@ -0,0 +1,23 @@
1
+ require 'rails/generators'
2
+
3
+ class GreenLightAssetsGenerator < Rails::Generators::Base
4
+ source_root File.expand_path('../templates', __FILE__)
5
+
6
+ def generate_assets
7
+ unless File.exists?("public/javascripts/jquery.validate_regex.js")
8
+ copy_file "jquery.validate_regex.js", "public/javascripts/jquery.validate_regex.js"
9
+ else
10
+ puts "public/javascripts/jquery.validate_regex.js already exists."
11
+ end
12
+
13
+ puts "Nearly there! Just download the jQuery Validate plugin (http://jquery.bassistance.de/validate/jquery-validation-1.8.0.zip)"
14
+ puts "and jQuery 1.3.2, 1.4.2, 1.4.4, 1.5.0, 1.5.1."
15
+ puts ""
16
+ puts "Include the above in your layout header."
17
+ puts ""
18
+ puts "Also, insert the following code in your layout header"
19
+ puts ""
20
+ puts "<%= javascript_include_tag 'jquery.validate_regex', 'green_light' %>"
21
+ puts ""
22
+ end
23
+ end
@@ -0,0 +1,9 @@
1
+ $.validator.addMethod(
2
+ "regex",
3
+ function(value, element, regexp) {
4
+ var check = false;
5
+ var re = new RegExp(regexp);
6
+ return this.optional(element) || re.test(value);
7
+ },
8
+ "You have entered an invalid value for this field"
9
+ );
@@ -0,0 +1,51 @@
1
+ require File.dirname(__FILE__) + '/spec_helper'
2
+
3
+ describe GreenLight do
4
+ before(:all) do
5
+ end
6
+
7
+ it "should return a valid json string when validating the format of a field" do
8
+ rules = GreenLight::Rules.generate([FormatOfModel])
9
+ rules.should == "{\"errorElement\":\"span\",\"rules\":{\"format_of_model[title]\":{\"regex\":\"(^[A-Za-z]$)\"}}}"
10
+ end
11
+
12
+ it "should return a json string when validating the presence of a field" do
13
+ rules = GreenLight::Rules.generate([PresenceOfModel])
14
+ rules.should == "{\"errorElement\":\"span\",\"rules\":{\"presence_of_model[title]\":{\"required\":true}}}"
15
+ end
16
+
17
+ it "should return a json string when validating the length of a field" do
18
+ rules = GreenLight::Rules.generate([LengthOfModel])
19
+ rules.should == "{\"errorElement\":\"span\",\"rules\":{\"length_of_model[title]\":{\"maxlength\":10,\"minlength\":5}}}"
20
+ end
21
+
22
+ it "should return a json string when validating the numericality of a field" do
23
+ rules = GreenLight::Rules.generate([NumericalityOfModel])
24
+ rules.should == "{\"errorElement\":\"span\",\"rules\":{\"numericality_of_model[age]\":{\"regex\":\"^[0-9]*$\"}}}"
25
+ end
26
+
27
+ it "should return a json string when validating the uniqueness of a field" do
28
+ rules = GreenLight::Rules.generate([UniquenessOfModel])
29
+ rules.should == "{\"errorElement\":\"span\",\"rules\":{\"uniqueness_of_model[title]\":{\"remote\":\"/javascripts/check_for_uniqueness?model=UniquenessOfModel&field=title\"}}}"
30
+ end
31
+ end
32
+
33
+ class FormatOfModel < SuperModel::Base
34
+ validates_format_of :title, :with => /^[A-Za-z]$/
35
+ end
36
+
37
+ class PresenceOfModel < SuperModel::Base
38
+ validates_presence_of :title
39
+ end
40
+
41
+ class LengthOfModel < SuperModel::Base
42
+ validates_length_of :title, :within => 5..10
43
+ end
44
+
45
+ class NumericalityOfModel < SuperModel::Base
46
+ validates_numericality_of :age
47
+ end
48
+
49
+ class UniquenessOfModel < SuperModel::Base
50
+ validates_uniqueness_of :title
51
+ end
@@ -0,0 +1,6 @@
1
+ require 'rubygems'
2
+ require 'rspec'
3
+ require 'rails'
4
+ require 'active_record'
5
+ require 'supermodel'
6
+ require File.dirname(__FILE__) + '/../lib/green_light'
metadata ADDED
@@ -0,0 +1,89 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: green_light
3
+ version: !ruby/object:Gem::Version
4
+ hash: 27
5
+ prerelease:
6
+ segments:
7
+ - 0
8
+ - 0
9
+ - 2
10
+ version: 0.0.2
11
+ platform: ruby
12
+ authors:
13
+ - Phil McClure
14
+ autorequire:
15
+ bindir: bin
16
+ cert_chain: []
17
+
18
+ date: 2011-04-04 00:00:00 +01:00
19
+ default_executable:
20
+ dependencies: []
21
+
22
+ description: Simple client side validation that keeps validation in the models
23
+ email:
24
+ - pmcclure@rumblelabs.com
25
+ executables: []
26
+
27
+ extensions: []
28
+
29
+ extra_rdoc_files: []
30
+
31
+ files:
32
+ - .gitignore
33
+ - Gemfile
34
+ - README.rdoc
35
+ - Rakefile
36
+ - app/controllers/javascripts_controller.rb
37
+ - app/views/javascripts/green_light.js.erb
38
+ - config/routes.rb
39
+ - green_light.gemspec
40
+ - lib/green_light.rb
41
+ - lib/green_light/engine.rb
42
+ - lib/green_light/rules.rb
43
+ - lib/green_light/validations/validates_format_of.rb
44
+ - lib/green_light/validations/validates_length_of.rb
45
+ - lib/green_light/validations/validates_numericality_of.rb
46
+ - lib/green_light/validations/validates_presence_of.rb
47
+ - lib/green_light/validations/validates_uniqueness_of.rb
48
+ - lib/green_light/version.rb
49
+ - lib/rails/generators/green_light_assets/USAGE
50
+ - lib/rails/generators/green_light_assets/green_light_assets_generator.rb
51
+ - lib/rails/generators/green_light_assets/templates/jquery.validate_regex.js
52
+ - spec/green_light_spec.rb
53
+ - spec/spec_helper.rb
54
+ has_rdoc: true
55
+ homepage: http://www.rumblelabs.com
56
+ licenses: []
57
+
58
+ post_install_message:
59
+ rdoc_options: []
60
+
61
+ require_paths:
62
+ - lib
63
+ required_ruby_version: !ruby/object:Gem::Requirement
64
+ none: false
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ hash: 3
69
+ segments:
70
+ - 0
71
+ version: "0"
72
+ required_rubygems_version: !ruby/object:Gem::Requirement
73
+ none: false
74
+ requirements:
75
+ - - ">="
76
+ - !ruby/object:Gem::Version
77
+ hash: 3
78
+ segments:
79
+ - 0
80
+ version: "0"
81
+ requirements: []
82
+
83
+ rubyforge_project: green_light
84
+ rubygems_version: 1.5.2
85
+ signing_key:
86
+ specification_version: 3
87
+ summary: Simple client side validation that keeps validation in the models
88
+ test_files: []
89
+