Skip to content

Instantly share code, notes, and snippets.

@gotjosh
Created June 18, 2014 18:37
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 gotjosh/6027c43e435973668c28 to your computer and use it in GitHub Desktop.
Save gotjosh/6027c43e435973668c28 to your computer and use it in GitHub Desktop.
module ParamsValidator
def validator array_of_values = [], default _value, param
array_of_values.include? param ? param : default_value
end
end
class ParamsValidator
class << self
def validate
# properly initialize and set the hash to return
end
private
def validator array_of_values = [], default _value, param
array_of_values.include? param ? param : default_value
end
end
end
# Inheritance
class ProductValidator < ParamsValidator
class << self
def validate params
@hash ||= {
limit: validate_limit params[:limit],
sort: validate_sort params[:sort],
page: validate_limit params[:page],
category_id: params[:category_id]
}
end
private
def validate_limit limit_param
validator %w(15 30 50), 15, limit_param
end
def validate_sort sort_param
validator %w(most_recent a-z z-a), 'most_recent', sort_param
end
end
end
# as a module?
class ProductValidator
include ParamsValidator
class << self
def validate params
@hash ||= {
limit: validate_limit params[:limit],
sort: validate_sort params[:sort],
page: validate_limit params[:page],
category_id: params[:category_id]
}
end
private
def validate_limit limit_param
validator %w(15 30 50), 15, limit_param
end
def validate_sort sort_param
validator %w(most_recent a-z z-a), 'most_recent', sort_param
end
end
end
# As a DSL?
class Product
validator :limit, %w(15 30 50), 15
validator :page, %w(1..50), 15, 1
end
# controller
private
def product_param
Product.validate(params)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment