Created
April 30, 2012 00:24
-
-
Save ms-ati/2554355 to your computer and use it in GitHub Desktop.
Multiple blog comment validations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pp' | |
require 'rumonade' | |
User = Struct.new(:user_id, :name) | |
Post = Struct.new(:post_id, :text, :comments) | |
Comment = Struct.new(:user, :post, :text) | |
Users = [User.new(101, "Dave")] | |
Posts = [Post.new(201, "Welcome to my blog", [])] | |
def validate_not_nil(arg, nil_error_msg) | |
if arg.nil? then Left(nil_error_msg) else Right(arg) end | |
end | |
def validate_user(user_id) | |
validate_not_nil(user_id, "Missing user id").right.flat_map do |id| | |
validate_not_nil(Users.find {|u| u.user_id == id}, "Unknown user id") | |
end | |
end | |
def validate_post(post_id) | |
validate_not_nil(post_id, "Missing post id").right.flat_map do |id| | |
validate_not_nil(Posts.find {|u| u.post_id == id}, "Unknown post id") | |
end | |
end | |
Policy = { /\bdisagree\b/i => "disagreement", /\bjerk\b/i => "name calling" } | |
def validate_text(text) | |
validate_not_nil(text, "Missing comment text").lift_to_a.right.flat_map do |txt, d| | |
Policy.map { |rex, msg| if rex =~ txt then Left("No #{msg} allowed!") else Right(txt) end.lift_to_a }. | |
inject(:+).right.map { |*txts| txts[0, 1] } | |
end | |
end | |
def add_comment(user_id, post_id, text) | |
[validate_user(user_id).lift_to_a, validate_post(post_id).lift_to_a, validate_text(text)]. | |
inject(:+).right.map { |u, p, t| p.comments << Comment.new(u, p, t.first); p } | |
end | |
pp add_comment(nil, nil, nil) | |
# Left(["Missing user id", "Missing post id", "Missing comment text"]) | |
pp add_comment(42, 16, "I totally disagree with this jerk...") | |
# Left(["Unknown user id", "Unknown post id", "No disagreement allowed!", "No name calling allowed!"]) | |
pp add_comment(101, 201, "I agree!") | |
# Right(#<struct Post post_id=201, text="Welcome to my blog", comments=[#<struct Comment user=#<struct User user_id=101, name="Dave">, post=#<struct Post:...>, text="I agree!">]>) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment