Commit bfb43459 by Rocky Duan

parameters to retrieve comments up to a certain depth; untested

parent 259f6f93
...@@ -19,7 +19,11 @@ ActiveRecord::Base.establish_connection(databases[env]) ...@@ -19,7 +19,11 @@ ActiveRecord::Base.establish_connection(databases[env])
# retrive all comments of a commentable object # retrive all comments of a commentable object
get '/api/v1/commentables/:commentable_type/:commentable_id/comments' do |commentable_type, commentable_id| get '/api/v1/commentables/:commentable_type/:commentable_id/comments' do |commentable_type, commentable_id|
comment_thread = CommentThread.find_or_create_by_commentable_type_and_commentable_id(commentable_type, commentable_id) comment_thread = CommentThread.find_or_create_by_commentable_type_and_commentable_id(commentable_type, commentable_id)
comment_thread.json_comments if params["to_depth"]
comment_thread.json_comments(to_depth: params["to_depth"].to_i)
else
comment_thread.json_comments
end
end end
# create a new top-level comment # create a new top-level comment
...@@ -65,11 +69,20 @@ end ...@@ -65,11 +69,20 @@ end
# get the information of a single comment # get the information of a single comment
get '/api/v1/comments/:comment_id' do |comment_id| get '/api/v1/comments/:comment_id' do |comment_id|
puts params
comment = Comment.find_by_id(comment_id) comment = Comment.find_by_id(comment_id)
if comment.nil? or comment.is_root? if comment.nil? or comment.is_root?
error 400, {:error => "invalid comment id"}.to_json error 400, {:error => "invalid comment id"}.to_json
else else
comment.to_json if params["recursive"] == "true"
if params["to_depth"]
comment.to_hash_tree(to_depth: params["to_depth"].to_i).to_json
else
comment.to_hash_tree.to_json
end
else
comment.to_json
end
end end
end end
......
...@@ -21,8 +21,12 @@ class Comment < ActiveRecord::Base ...@@ -21,8 +21,12 @@ class Comment < ActiveRecord::Base
nodes.map {|node, sub_nodes| node.to_hash.merge(:children => hash_tree(sub_nodes).compact)} nodes.map {|node, sub_nodes| node.to_hash.merge(:children => hash_tree(sub_nodes).compact)}
end end
def to_hash_tree def to_hash_tree(args=nil)
self.class.hash_tree(self.subtree.arrange(:order => "updated_at DESC")) if args and args[:to_depth]
self.class.hash_tree(self.subtree(to_depth: args[:to_depth]).arrange(:order => "updated_at DESC"))
else
self.class.hash_tree(self.subtree.arrange(:order => "updated_at DESC"))
end
end end
def to_hash def to_hash
......
...@@ -29,8 +29,8 @@ class CommentThread < ActiveRecord::Base ...@@ -29,8 +29,8 @@ class CommentThread < ActiveRecord::Base
super_comment.descendants super_comment.descendants
end end
def json_comments def json_comments(args=nil)
super_comment.to_hash_tree.first[:children].to_json super_comment.to_hash_tree(args).first[:children].to_json
end end
end end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment