module ResponseMethods
  extend ActiveSupport::Concern

  EVENTS = { create: 'created', update: 'updated', destroy: 'deleted' }

  def render_success(status, options={})
    data = { message: default_message(options) }
    data[:body] = options[:json] if options[:json]

    render status: status, json: defaults.merge(data)
  end

  def render_error(status, options={})
    if (object = options[:errors]) && object.is_a?(ActiveRecord::Base)
      options[:errors] = object.errors
    elsif object && !object.is_a?(Enumerable)
      options[:errors] = [object]
    end

    render status: status, json: defaults(false).merge(options)
  end

  private
    def defaults(success=true)
      { success: success }
    end

    def default_message(options={})
      object = options[:object] || controller_name.singularize
      event = options[:event] || EVENTS[action_name.to_sym]
      options[:message] || "#{object} #{event}.".humanize
    end
end
