.. autores::
:autor: "Miguel Costa"
... and everywhere else
Author: Carlos Batman
Writing is nature's way of exposing how sloppy your thinking is.
- Guindon, via MPJ
Documentação em Django - #dontjustcode
fonte: https://en.wikipedia.org/wiki/Software_documentation (yeah, I know...)
Documentação em Django - #dontjustcode
Só o que é deles!
Documentação em Django - #dontjustcode
Um exemplo
Being able to write about your code shows that you really understand how it works.
- QDeltaE, via Codepen
Documentação em Django - #dontjustcode
function a(b) {
    return Math.floor(Math.random()*b)
 }
function c(d, e) {
    let f; 
      
    do {
      f = a(d);
    } while(f === e)
    return f;
}
// caso de uso
c(1000, 3)A minha biblioteca para gerar números!
Documentação em Django - #dontjustcode
// LOOK MA, I'M SELF-DOCUMENTED!
function getRandomInteger(maximumInteger) {
    return Math.floor(Math.random()*maximumInteger)
 }
function getRandomIntegerWithException(maximumInteger, exceptionInteger) {
    let outputInteger; 
    
    // run the random number function
    // as long as the output is the same
    // as the exception  
    do {
      outputInteger = getRandomInteger(maximumInteger);
    } while(exceptionInteger === outputInteger)
    return outputInteger;
}
// caso de uso
getRandomNumberExcept(1000, 3)
Há restrições?
A minha AUTODOCUMENTADA biblioteca!
'com exceção?'
Porque preciso disto?
Documentação em Django - #dontjustcode
/**
 * Returns a random INTEGER POSITIVE number that will not
 * be larger than a specific number.
 * 
 * This method is convenient for generating a random index for a list
 * given the width as parameter 
 *
 * @param  {Number} maximumInteger A positive number that sets the maximum value
 * @return {Number}                A random positive not exceeding maximumNumber
 * 
 * @todo Throw an error in case maximumInteger is NOT a positive number
 * 
 * @example
 * // get a random integer up to 10
 * getRandomInteger(10)
*/
function getRandomInteger(maximumInteger)A minha DESCRITA biblioteca para gerar números!
Documentação em Django - #dontjustcode
/**
 * Returns a random positive integer provided a maximum integer.
 * If set, the random positive number will be different from an 
 * exception set as a parameter.
 *
 * This can be used to ensure that a random number will not generate
 * a number that was generated before and/or is not a desired value.
 *
 * This function uses {@link getRandomInteger}.
 * 
 * @example
 * // generate a random number up to 10, but not including 3
 * getRandomIntegerWithException(10, 3)
 * @param  {Number} maximumInteger   A positive number that sets the maximum value
 * @param  {Number} [exceptionInteger] [description]
 * @return {Number}                  [description]
 */
function getRandomIntegerWithException(maximumInteger, exceptionInteger)A minha DESCRITA biblioteca para gerar números!
Documentação em Django - #dontjustcode
Documentação em Django - #dontjustcode
Comentário descritivo em Javascript em formato JSDocs (via DoxyDoxygen)
 
Documentação em Django - #dontjustcode
Vantagens?
No que estava eu a pensar quando fiz isto?!
Templates em Django - Django4FrontEnd
Coding explains 'how' and commenting explains you 'why' - Bisileesh P.B
fonte: Rapid Value Solutions
... and testing proves that the 'how' works! - Me
But the pre-emptively badass code you are writing with that goal is even more likely to become a thorn in someone’s side. Whose? The next unlucky person who has to comprehend your code, which may even be yourself.
- Kevin Bloch, via Toptal
Documentação em Django - #dontjustcode
Documentação em Django - #dontjustcode
Documentação técnica a partir de comentários descritivos de funções, métodos e classes.
(Ainda sobre comentários descritivos)
Documentação em Django - #dontjustcode
Documentação em Django - #dontjustcode
Porquê ter um padrão para do-comentar código?
Compilação automática da documentação em 'manuais'
def get_data_from_something(id):
    """
    This is a helper function for views.
    Gets the seo data corresponding to an instance of :class:`app.models.Something` with a specific id string
    The returned object contains:
    * title
    * description
    * a list of keywords
    
    :param      id:  A string containing the identifier value of the requested object
    :type       id:  string
    
    :returns:   A dictionary containing the a title string, a description string and a list of keyword.
    :rtype:     dictionary
    .. todo::
       Set an error in case there is no SEOPage instance requested
    .. note::
       It is not clear why this is not a manager or model method
    :Example:
    >>> # returns seo-related data for the page with 'home' urlname
    >>> get_seo_data("home")
    
    """Documentação em Django - #dontjustcode
Sumário muito resumido
Descrição mais detalhada (depois de linha de intervalo)
Diretivas (notas com formatação específica para documentação em Sphinx)
class IFrameTag(InclusionTag):
    """
    Renders an IFrame HTML element that can either be included directly or through a block component.
    
    Its options can be set via the :class:`templatetags.IFrameTagForm` form.
    
    :Example:
    
    .. code-block:: html
       {% iframe src='//slides.com/costaman/djadefdoc/embed' width=500 height=400 %}
       <!-- will output -->
       <iframe src='//slides.com/costaman/djadefdoc/embed' width='500' height='400' frameborder='0'></iframe>
    """
    # ... actual codeDocumentação em Django - #dontjustcode
"code block" dentro de exemplo
linha em branco é importante!
Documentação em Django - #dontjustcode
Templates em Django - Django4FrontEnd
fonte: http://stackoverflow.com/questions/9846242/setting-up-django-settings-for-sphinx-documentation
pip install sphinxsphinx-quickstartmake html# docs/source/conf.py
# caminho relativo desde este ficheiro
# deve apanhar apps
import os
import sys
from django.conf import settings
# caminho para o projeto
# sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('../..'))
# ou seja lá qual for o ficheiro...
# os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'só se não estiver definido em ambiente
assume 'project/_docs/source'
Templates em Django - Django4FrontEnd
fonte: http://stackoverflow.com/questions/9846242/setting-up-django-settings-for-sphinx-documentation
pip install sphinxsphinx-quickstartmake html# docs/source/conf.py
import os
import sys
import django
# caminho para o projeto
# sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('../..'))
# ou seja lá qual for o ficheiro...
# os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
django.setup()só se não estiver definido em ambiente
assume 'project/_docs/source'
IMPORTANTE (automodule)
Templates em Django - Django4FrontEnd
Sphinx RTD - tema estilo 'Read the docs'
Título 1
========
É favor respeitar o número de traços por baixo do título.
Texto *itálico* **negrito** e .
Subtítulo
---------
Não existe padrão para sublinhados para *headings*.
O primeiro é para títulos1, segundo para títulos 2
.. warning::
   Isto é um aviso
.. todo::
   Isto é um todo!
Título 1
--------
É favor respeitar o número de traços por baixo do título.
Texto *itálico* **negrito** e .
Subtítulo
=========
Não existe padrão para sublinhados para *headings*.
O primeiro é para títulos1, segundo para títulos 2
.. warning::
   Isto é um aviso
.. todo::
   Isto é um todo!
Esquerda == Direita, mesmo usando diferentes sublinados para níveis de título
Lista desordenada
=================
* Item 1
* Item 2
Lista Ordenada
==============
1. Item 1
2. Item 2
Ou...
# Item 1
# Item 2
.. _pagina1:
Página 1
--------
Podemos fazer uma referência a :ref:`pagina2`.
Aquele comentário ali em cima com o underscore? 
É uma etiqueta (para se poder referenciar a página).
.. _pagina2:
Página 2
--------
Podemos fazer uma referência a :ref:`pagina1`.
Aquele comentário ali em cima com o underscore?
É uma etiqueta (para se poder referenciar a página).
Para referenciar funções, classes ou módulos, 
pode-se usar caminhos absolutos ou relativos! 
Podes ver mais na função :func:`main_app.my_functions.function`, 
assim como a classe :class:`main_app.models.EstaClasse`.
Também existe `mod` para... módulos!
.. no proprio ficheiro, para fazer uma ref. a uma func. local
A função local :func:`do_stuff`.
referência única
vai para...
aparece...
.. links
Isto tem `um link externo <http://www.linkpersonaizado.ya>`_ com o texto "um link externo"
Documentação em Django - #dontjustcode
.. directive:: parameters
   :option1:
   :option2:
   ContentEspécie de funções para gerar conteúdo "especial", mas que suporta parâmetros e personalizações
3 espaços
(indentação)
Linha vazia antes do conteúdo
podem aparecer logo por baixo
customizações predefenidas
Documentação em Django - #dontjustcode
.. deprecated:: 1.1
   use something else. This function is old!
.. todo::
   Set a TODO here
.. note::
   Just a general note!
.. reference to another function, class or method
.. seealso:: 
   It's related to :class:`SomeClass`.
.. comentario
   ainda um comentario
   cuidado com a identação!.. directive::
   parametros
   :option1:
   :option2:
   ContentEstrutura Base
parâmetro
não tem ::
# if this were a function...
note("Just a general note!")Gerar tabela de conteúdo
------------------------
Podemos hiperligar aos índices a partir do *name*, 
tipo :ref:`indice`.
Sem subníveis e título 'Table of Content'
=========================================
.. toctree::
   :maxdepth:1
   :caption: Table of Content
   :name: indice
   pagina1
   pagina2
Documentação em Django - #dontjustcode
Gerar tabela de conteúdo
------------------------
Podemos hiperligar aos índices a partir do *name*, 
tipo :ref:`indice2`.
Até 1 subnível
==============
.. toctree::
   :maxdepth:1
   :name: indice2
   pagina1
   pagina2
   subpaginas/*
.. automodule:: app.file
   :members:
.. autoclass:: app.file.class
   :members:Documentação em Django - #dontjustcode
Documentação em Django - #dontjustcode