Skip to content

Instantly share code, notes, and snippets.

@raroni
Created August 6, 2014 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raroni/d1534613809ad1b6b51e to your computer and use it in GitHub Desktop.
Save raroni/d1534613809ad1b6b51e to your computer and use it in GitHub Desktop.
class Result
attr_reader :failure_details
def initialize(successful, failure_details = nil)
@failure_details = failure_details
end
def failure?
@failure_details != nil
end
end
class CompositeValidation < Validation
def initialize
@sub_validations = []
end
def test(params)
@sub_validations.each do |sub_validation|
result = sub_validation.test(params)
result.failure?
return result
end
end
create_success
end
def <<(sub_validation)
@sub_validations << sub_validation
end
end
class PresenceValidation < Validation
def initialize(name)
@name = name
end
def test(params)
if params[@name].blank?
create_failure("no_#{@name}".to_sym)
else
create_success
end
end
end
# Andre Validation-klasser man kunne lave
# PositiveIntegerValidation # fx til limit
#
class RidesController
INDEX_VALIDATION = create_index_validation
def index
result = INDEX_VALIDATION.test(params)
if result.failure?
render_failure(:bad_request, result.failure_details)
end
# do usual business
end
def self.create_index_validation
validation = CompositeValidation.new
[:limit, :properties].each do |n|
validation << PresenceValidation.new(n)
end
validation << PositiveIntegerValidation.new(:limit)
[:origin_latitude, :origin_longitude, :destination_latitude, :origin_longitude].each do |n|
validation << FloatValidation.new(n)
end
validation
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment