Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added original value to uniqueness validations #48

Merged
merged 3 commits into from
Jan 12, 2015
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions app/assets/javascripts/judge.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,11 @@
return $1.toUpperCase().replace('_','');
});
};
originalValue = function(el) {
var validations = JSON.parse(el.getAttribute('data-validate'));
var validation = _.filter(validations, function (validation) { return validation.kind == "uniqueness"})[0];
return validation.original_value;
};

// Build the URL necessary to send a GET request to the mounted validations
// controller to check the validity of the given form element.
Expand All @@ -147,6 +152,9 @@
'value' : el.value,
'kind' : kind
};
if (kind == 'uniqueness') {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only a tiny thing but I'd like to maintain the style of using === in JS when testing for equality, and using == only when you need/want the ambiguity. It doesn't affect things at all in this case but it's a good habit to develop.

params['original_value'] = originalValue(el);
}
return path + queryString(params);
};

Expand Down Expand Up @@ -265,7 +273,7 @@
presence: function(options, messages) {
return closed(this.value.length ? [] : [messages.blank]);
},

// ActiveModel::Validations::LengthValidator
length: function(options, messages) {
var msgs = [],
Expand All @@ -282,7 +290,7 @@
}, this);
return closed(msgs);
},

// ActiveModel::Validations::ExclusionValidator
exclusion: function(options, messages) {
var stringIn = _(options['in']).map(function(o) {
Expand All @@ -292,7 +300,7 @@
_.include(stringIn, this.value) ? [messages.exclusion] : []
);
},

// ActiveModel::Validations::InclusionValidator
inclusion: function(options, messages) {
var stringIn = _(options['in']).map(function(o) {
Expand All @@ -302,7 +310,7 @@
!_.include(stringIn, this.value) ? [messages.inclusion] : []
);
},

// ActiveModel::Validations::NumericalityValidator
numericality: function(options, messages) {
var operators = {
Expand All @@ -313,7 +321,7 @@
less_than_or_equal_to: '<='
},
msgs = [],
parsedValue = parseFloat(this.value, 10);
parsedValue = parseFloat(this.value, 10);

if (isNaN(Number(this.value))) {
msgs.push(messages.not_a_number);
Expand All @@ -330,7 +338,7 @@
}
return closed(msgs);
},

// ActiveModel::Validations::FormatValidator
format: function(options, messages) {
var msgs = [];
Expand All @@ -348,12 +356,12 @@
}
return closed(msgs);
},

// ActiveModel::Validations::AcceptanceValidator
acceptance: function(options, messages) {
return closed(this.checked === true ? [] : [messages.accepted]);
},

// ActiveModel::Validations::ConfirmationValidator
confirmation: function(options, messages) {
var id = this.getAttribute('id'),
Expand All @@ -366,7 +374,7 @@

// ActiveModel::Validations::UniquenessValidator
uniqueness: function(options, messages) {
var validation = pending();
var validation = pending();
get(urlFor(this, 'uniqueness'), {
success: function(status, headers, text) {
validation.close(text);
Expand Down
5 changes: 3 additions & 2 deletions lib/judge/controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def validation(params)

private

REQUIRED_PARAMS = %w{klass attribute value kind}
REQUIRED_PARAMS = %w{klass attribute value kind original_value}

def params_exposed?(params)
Judge.config.exposed?(params[:klass], params[:attribute])
Expand All @@ -25,11 +25,12 @@ def params_present?(params)
end

def normalized_params(params)
params = params.dup.keep_if { |k| REQUIRED_PARAMS.include?(k) }
params = params.dup.keep_if {|k| REQUIRED_PARAMS.include?(k) || (k == :original_value && params[:kind] == :uniqueness)}
params[:klass] = find_klass(params[:klass]) if params[:klass]
params[:attribute] = params[:attribute].to_sym if params[:attribute]
params[:value] = URI.decode(params[:value]) if params[:value]
params[:kind] = params[:kind].to_sym if params[:kind]
params[:original_value] = URI.decode(params[:original_value]) if params[:original_value]
params
end

Expand Down
3 changes: 2 additions & 1 deletion lib/judge/validation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ def initialize(params)
@attribute = params[:attribute]
@value = params[:value]
@kind = params[:kind]
@original_value = params[:original_value]
validate!
end

Expand All @@ -27,7 +28,7 @@ def record

def validate!
record.errors.delete(@attribute)
amv.validate_each(record, @attribute, @value)
amv.validate_each(record, @attribute, @value) unless amv.kind == :uniqueness && @value == @original_value && @original_value != ""
self
end

Expand Down
7 changes: 5 additions & 2 deletions lib/judge/validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module Judge

class Validator

attr_reader :active_model_validator, :kind, :options, :method, :messages
attr_reader :active_model_validator, :kind, :options, :method, :messages, :original_value

REJECTED_OPTIONS = [:if, :on, :unless, :tokenizer, :scope, :case_sensitive, :judge]

Expand All @@ -11,14 +11,17 @@ def initialize(object, method, amv)
@options = amv.options.reject { |key| REJECTED_OPTIONS.include?(key) }
@method = method
@messages = Judge::MessageCollection.new(object, method, amv)
@original_value = object.send(method)
end

def to_hash
{
params = {
:kind => kind,
:options => options,
:messages => messages.to_hash
}
params[:original_value] = original_value if kind == :uniqueness
params
end

end
Expand Down
16 changes: 12 additions & 4 deletions spec/controllers/judge/validations_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@
let(:headers) do
{ :accept => "application/json" }
end

let(:valid_params) do
{
:use_route => :judge,
:format => :json,
:klass => "User",
:attribute => "username",
:value => "invisibleman",
:kind => "uniqueness"
:value => "tinbucktwo",
:kind => "uniqueness",
:original_value => "tinbucktwo"
}
end

Expand All @@ -24,7 +25,8 @@
:klass => "User",
:attribute => "city",
:value => "",
:kind => "city"
:kind => "city",
:original_value => "nil"
}
end

Expand All @@ -36,6 +38,12 @@
response.should be_success
response.body.should eql "[]"
end
it "responds with empty JSON array if original_value equals the value" do
FactoryGirl.create(:user, username: 'tinbucktwo')
get :build, valid_params, headers
response.should be_success
response.body.should eql "[]"
end
it "responds with JSON array of error messages if invalid" do
get :build, invalid_params, headers
response.should be_success
Expand Down
7 changes: 4 additions & 3 deletions spec/javascripts/judge-spec.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
describe('judge', function() {
var server,
uniquenessAttr = '[{"kind":"uniqueness","options":{},"messages":{}}]',
uniquenessAttr = '[{"kind":"uniqueness","options":{},"messages":{},"original_value":"leader"}]',
presenceAttr = '[{"kind":"presence","options":{},"messages":{"blank":"must not be blank"}}]',
uniqPresenceAttr = '[{"kind":"uniqueness","options":{},"messages":{}},{"kind":"presence","options":{},"messages":{"blank":"must not be blank"}}]',
uniqPresenceAttr = '[{"kind":"uniqueness","options":{},"messages":{},"original_value":"leader"},{"kind":"presence","options":{},"messages":{"blank":"must not be blank"}}]',
mixedAttr = '[{"kind":"presence","options":{},"messages":{"blank":"must not be blank"}},{"kind":"inclusion","options":{"in":["a","b"]},"messages":{"inclusion":"must be a or b"}}]',
uniqAndIncAttr = '[{"kind":"uniqueness","options":{},"messages":{}},{"kind":"inclusion","options":{"in":["a","b"]},"messages":{"inclusion":"must be a or b"}}]';

Expand Down Expand Up @@ -446,6 +446,7 @@ describe('judge', function() {
validator = _.bind(judge.eachValidators.uniqueness, el);
el.value = '[email protected]';
el.name = 'team[leader][email]';
el.setAttribute('data-validate', uniquenessAttr)
});
it('returns a pending Validation', function() {
validation = validator({}, {});
Expand All @@ -460,7 +461,7 @@ describe('judge', function() {
server.respond();
});
runs(function() {
expect(server.requests[0].url).toBe('/judge?klass=Leader&attribute=email&value=leader%40team.com&kind=uniqueness');
expect(server.requests[0].url).toBe('/judge?klass=Leader&attribute=email&value=leader%40team.com&kind=uniqueness&original_value=leader');
});
});
it('closes Validation as valid if the server responds with an empty JSON array', function() {
Expand Down