From f1ad8922467e6c915fbb23d48369d79ae886bcbf Mon Sep 17 00:00:00 2001 From: joshua stein Date: Tue, 10 Oct 2017 16:28:05 -0500 Subject: [PATCH] add /messages.json and /messages/sent.json interfaces --- app/controllers/messages_controller.rb | 42 ++++++++++++++++++-------- app/models/message.rb | 19 ++++++++++++ config/routes.rb | 3 +- 3 files changed, 50 insertions(+), 14 deletions(-) diff --git a/app/controllers/messages_controller.rb b/app/controllers/messages_controller.rb index b493a5a5a3..bf93f78737 100644 --- a/app/controllers/messages_controller.rb +++ b/app/controllers/messages_controller.rb @@ -3,29 +3,45 @@ class MessagesController < ApplicationController before_action :find_message, :only => [ :show, :destroy, :keep_as_new ] def index - @cur_url = "/messages" - @title = "Messages" + @messages = @user.undeleted_received_messages - @new_message = Message.new + respond_to do |format| + format.html { + @cur_url = "/messages" + @title = "Messages" - @direction = :in - @messages = @user.undeleted_received_messages + @new_message = Message.new + + @direction = :in - if params[:to] - @new_message.recipient_username = params[:to] + if params[:to] + @new_message.recipient_username = params[:to] + end + } + format.json { + render :json => @messages + } end end def sent - @cur_url = "/messages" - @title = "Messages Sent" - - @direction = :out @messages = @user.undeleted_sent_messages - @new_message = Message.new + respond_to do |format| + format.html { + @cur_url = "/messages" + @title = "Messages Sent" - render :action => "index" + @direction = :out + + @new_message = Message.new + + render :action => "index" + } + format.json { + render :json => @messages + } + end end def create diff --git a/app/models/message.rb b/app/models/message.rb index bcb64fc588..63789fc1f9 100644 --- a/app/models/message.rb +++ b/app/models/message.rb @@ -22,6 +22,25 @@ class Message < ActiveRecord::Base after_save :update_unread_counts after_save :check_for_both_deleted + def as_json(options = {}) + attrs = [ + :short_id, + :created_at, + :has_been_read, + :subject, + :body, + :deleted_by_author, + :deleted_by_recipient, + ] + + h = super(:only => attrs) + + h[:author_username] = self.author.try(:username) + h[:recipient_username] = self.recipient.try(:username) + + h + end + def assign_short_id self.short_id = ShortId.new(self.class).generate end diff --git a/config/routes.rb b/config/routes.rb index f4bb940139..1fa049c219 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -89,7 +89,8 @@ get "/comments/page/:page" => "comments#index" get "/comments" => "comments#index", :format => /html|rss/ - get "/messages/sent" => "messages#sent" + get "/messages/sent" => "messages#sent", :format => /html|json/ + get "/messages" => "messages#index", :format => /html|json/ post "/messages/batch_delete" => "messages#batch_delete", :as => "batch_delete_messages" resources :messages do