I am providing a web service to be called by external companies. The required data covers several models including person, address etc. I want to validate the received data conditionally based upon some fields within the request. I will eventually have many differing sets of validation data, although currently I only have one and I am about to add the second.
My current model looks something like this
class Person < ActiveRecord::Base
validates_length_of :first_name, :within => 1..32, :allow_blank => true
...
...
end
Conceptually my model now needs to do something like this.
class Person < ActiveRecord::Base
validate :first_name?
def first_name?
if country == 'UK'
if company_name == 'ABC'
validates_length_of :first_name, :within => 1..32
else if company_name == 'DEF'
validates_length_of :first_name, :within => 2..20
end
else if country == 'DE'
if company_name == 'ABC'
validates_length_of :first_name, :within => 1..32
else if company_name == 'DEF'
validates_length_of :first_name, :within => 2..20
end
end
end
This would obviously work fine for 2 companies/countries but will not work well as the number of companies and/or countries increases. I am now considering keeping the validation data either in the database or in a YAML file and then performing the validations manually for each field based upon the minimum, maximum, format values stored externally from the model.
I am thinking that I could store the validation data in a structure similar to the following
country: UK companyname: ABC field: first_name minimum_length: 2 maximum_length: 20 required: true field: middle_name minimum_length: 1 maximum_length: 10 field: email_address minimum_length: 10 format: /someregexforemail addresses/ companyname: DEF field ... country: DE companyname: XYZ field: ....
and so on.
I could then load this validation data and use this within my own hand-rolled validator.
Has anyone done similar things in the past and what methods did you use? I am particularly interested to know how you approached the following.
- Where did you store your configuration data i.e. DB or YAML?
- Did you load and parse the configuration data for each request or once as the server loaded?
- How did you structure the actual method that did validation?