I wanted to keep my API request logic separate form the controller logic. I therefore make use of a separate model (EmailCheckerEmailChecker) that creates an instance of this class via EmailChecker.new(params)EmailChecker.new(params).
Then I can check the new instance with valid?valid?.
When it returns false I grepgrep the errors and return it. This example only checks email but of course you can use any Rails validations on multiple parameters.
Problem is that I have to create a class for every api-requestAPI request you want to validate. Actually I don't mind because it makes the code easy to understand but it's not very DRY.
Any suggestions to improve this code?
class EmailChecker
include ActiveModel::Validations
include ActiveModel::Conversion
include ActiveModel::Naming
attr_accessor :email
validates_format_of :email, :with => /\A[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}\z/i
# validates :email, presence: true
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=",value)
end
end
def persisted?
false
end
end #emailchecker