Marc-Alexandre Chan avatar Marc-Alexandre Chan committed 4ba60c8

Move formatting methods in ListPromptsCommand to a mixin; update db __repr__

TODO: fix the prompt output reply in Add/Update events in the reply (make a
PromptUpdateReplyCommand that does the work).

TODO: grab and commit the right util.py file and merge changes in

Comments (0)

Files changed (4)

minibot/DailyPrompt-minibot.psproj

 ClassName=TProjectFileNode
 FileName=$[Project-Path]minibot.py
 
-[Project\ChildNodes\Node0\ChildNodes\Node8]
-ClassName=TProjectFileNode
-FileName=D:\Projects\Software\ScrivBot\pyGBot\pyGBot\util.py
-
 [Project\ChildNodes\Node0\ChildNodes]
-Count=9
+Count=8
 
 [Project\ChildNodes\Node1]
 ClassName=TProjectRunConfiguationsNode
         if email:
             self.email = email
 
-    def __repr__(self):
-        return "<User({r_id}, '{uname}')>".format(r_id=self.r_id,\
-                                                  uname=self.uname)
-
     def setPassword(self, password, salt=''):
         self.password = hashlib.sha256(salt + password).hexdigest()
 
+    def __repr__(self):
+        """ Return a human-readable representation of the User row. """
+        return "<User({r_id}, '{uname}', 'email', {reg})>".format(
+                r_id=self.r_id, uname=self.uname, email=self.email,
+                reg='registered' if self.registered else 'unregistered')
+
+    def __str__(self):
+        """ Return a friendly string representing a User row. """
+        return unicode(self).encode('ascii', 'replace')
+
+    def __unicode__(self):
+        """ Return a friendly string representing a User row. """
+        return "/u/{uname}{email}{reg}".format(
+            uname=self.uname,
+            email=''.join([' <', self.email, '>']) if self.email else '',
+            reg=' (unregistered)' if not self.registered else '')
+
 
 class Prompt(Base):
     """ A prompt and its related posting data (suggester, approver, status,
         return self.STATUS_TEXT[self.status]
 
     def __repr__(self):
-        return "<Prompt({id_:d}, {status}, {tpost}, '{user}', '{approver}',"\
-               "'{title}', '{excerpt}')>".format(id_=self.id,
-                              status=STATUS_TEXT[self.status],
-                              tpost=self.post_time.__str__(),
+        """ Return a human-readable representation of the Prompt row. """
+        return "<Prompt(id={id_:d}, status={status}, post_time={tpost}, "\
+               "r_post_id={post_id}, submit_time={tsubmit}, "\
+               "user='{user}', approver='{approver}',"\
+               "title='{title}', text='{excerpt}')>".format(
+                              id_=str(self.id),
+                              status=self.get_status_string(),
+                              tpost=str(self.post_time),
+                              r_post_id=str(self.post_id),
+                              tsubmit=str(self.submit_time),
                               user=self.user,
                               approver=self.approver.c.uname,
                               title=self.title,

minibot/events.py

         else:
             query = query.order_by(Prompt.id)
 
-        prompt_list = [self._format_entry(short=self.short_entry)]
+        prompt_list = [self._header_prompt(self.short_entry)]
         has_prompt = False
 
         for prompt in query[0:self.limit]:
             has_prompt = True
-            prompt_list.append(self._format_entry(prompt, self.short_entry))
+            prompt_list.append(self._format_prompt(prompt, self.short_entry))
 
         if not has_prompt:
             prompt_list = ["No results found."]
     def end(self):
         pass
 
-    def _format_entry(self, prompt=None, short=True)
-        """ Format an entry for listing. If ``short`` is true, the tabular
-        format is returned; if ``short`` is false, a full listing is returned.
-        The returned string is ended by a single newline. If ``short`` is True
-        and ``prompt`` is None, returns the table header line; if ``short`` is
-        false and ``prompt`` is None, outputs a heading delimeter. """
-        if prompt is not None:
-            if short:
-                return self._format_entry_short(prompt)
-            else:
-                return self._format_entry_long(prompt)
-        else:
-            if short:
-                return self._format_entry_short()
-            else:
-                return self._format_entry_long()
-
-    def _format_entry_short(self, prompt=None):
-        """ Format an entry for listing in short (tabular) format. If
-        ``prompt`` is ``None``, returns the table header lines. """
-        if prompt is not None:
-            str_data = []
-            # ID
-            str_data.append(unicode(prompt.id))
-            # Post time
-            str_data.append(
-                            self._localtime(prompt.post_time).\
-                            strftime('%Y-%m-%d %H:%M:%S'))
-            # status
-            if prompt.status == prompt.STATUS_POSTED:
-                str_data.append(self.md_link(
-                    prompt.get_status_string(),
-                    self._format_url(prompt.r_post_id)))
-            else:
-                str_data.append(prompt.get_status_string())
-            # title
-            str_data.append(prompt.title)
-            # submit time
-            str_data.append(
-                            self._localtime(prompt.submit_time).\
-                            strftime('%Y-%m-%d %H:%M:%S'))
-            # submitter
-            if prompt.r_source_url:
-                str_data.append(self.md_link(
-                    prompt.user, prompt.r_source_url))
-            else:
-                str_data.append(prompt.user)
-            # approver
-            str_data.append(prompt.approver.c.uname)
-            # text
-            if len(prompt.text) > self.SHORT_TEXT_LENGTH:
-                str_data.append(prompt.text[0:self.SHORT_TEXT_LENGTH-3] + '...')
-            else:
-                str_data.append(prompt.text)
-            # final newline
-            str_data.append(u'\n')
-
-            return u'|'.join(str_data)
-        else:
-            # list of tuples, just to make it easier to read/edit this
-            fields = [(u"ID",          u'-:'),
-                      (u"Post Time",   u':-'),
-                      (u"Status",      u':-:'),
-                      (u"Title",       u':-'),
-                      (u"Submit Time", u':-'),
-                      (u"Submitter",   u':-'),
-                      (u"Approver",    u':-'),
-                      (u"Text",        u':-')]
-            header = zip(*fields)
-            return u''.join(['|', '|'.join(header[0]), '|\n',
-                            '|'.join(header[1]), '|\n'])
-
-    def _format_entry_long(self, prompt=None):
-        """ Format an entry for listing in full-length format. If
-        ``prompt`` is ``None``, returns the header line. """
-        if prompt is not None:
-            str_data = []
-            # ID
-            str_data.append(u' '.join(
-                [u'#', unicode(prompt.id), prompt.title]))
-            str_data.append('\n')
-            # status
-            str_data.append(u'Status: ')
-            if prompt.status == prompt.STATUS_POSTED:
-                str_data.append(self.md_link(
-                    prompt.get_status_string(),
-                    self._format_url(prompt.r_post_id)))
-            else:
-                str_data.append(prompt.get_status_string())
-            str_data.append(u'\n')
-            # Post time
-            str_data.append(u''.join([u'Post time: ',
-                            self._localtime(prompt.post_time).\
-                            strftime('%Y-%m-%d %H:%M:%S'), u'\n']))
-            # submit time
-            str_data.append(u''.join([u'Submit time: ',
-                            self._localtime(prompt.submit_time).\
-                            strftime('%Y-%m-%d %H:%M:%S'), u'\n']))
-            # submitter
-            str_data.append(u'Submitter: ')
-            if prompt.r_source_url:
-                str_data.append(self.md_link(
-                    prompt.user, prompt.r_source_url))
-            else:
-                str_data.append(prompt.user)
-            str_data.append(u'\n')
-            # approver
-            str_data.append(
-                ''.join(['Approver: ', prompt.approver.c.uname, u'\n']))
-            # text
-            str_data.append(u'\n')
-            str_data.append(prompt.text)
-            # final newline
-            str_data.append(u'\n')
-
-            return u''.join(str_data)
-        else:
-            return "# PROMPT LISTING\n___\n"
-
     def _format_url(self, post_id):
+        """ Overrides ``DataFormatMixin._format_url()``. """
         reddit = self.res['reddit']
         return ''.join(['http://', reddit.config.domain, '/', post_id])
 
                 "out creative, thought-provoking or challenging prompts "
                 "and queue them up for next week or beyond.\n\n"
                 "Please try to avoid repeating suggestions that were already "
-                "posted in the last few weekswe probably already read it "
+                "posted in the last few weeks—we probably already read it "
                 "and either didn't find it interesting enough or liked it "
                 "enough to queue it up later on!").format(date_=self._str_date)
         # text += '\n___\n' + _BOT_MSG
+# TODO: get the rest of the file here - left it uncommited on the other computer
+
+class DataFormatMixin(object, MarkdownMixin):
+    """ Mixin for formatting database data in human-readable format. """
+    def _format_prompt(self, prompt, short=None):
+        """ Format a prompt for listing. If ``short`` is true, the tabular
+        format is returned; if ``short`` is false, a full listing is returned.
+        The returned string is ended by a single newline. If ``short`` is True
+        and ``prompt`` is None, returns the table header line; if ``short`` is
+        false and ``prompt`` is None, outputs a heading delimeter. """
+        if prompt is None:
+            return ''
+
+        if short:
+            return self.__format_prompt_short(prompt)
+        else:
+            return self.__format_prompt_long(prompt)
+
+    def _header_prompt(self, short=None):
+        """ Return a prompt listing header. If ``short`` is True, returns the
+        table header lines; if ``short`` is False, outputs a heading. Override
+        the _format_url() method to use a specific Reddit domain for URLs
+        (this class has no awareness of the Reddit object). """
+        if short:
+            # list of tuples, just to make it easier to read/edit this
+            fields = [(u"ID",          u'-:'),
+                      (u"Post Time",   u':-'),
+                      (u"Status",      u':-:'),
+                      (u"Title",       u':-'),
+                      (u"Submit Time", u':-'),
+                      (u"Submitter",   u':-'),
+                      (u"Approver",    u':-'),
+                      (u"Text",        u':-')]
+            header = zip(*fields)
+            return u''.join(['|', '|'.join(header[0]), '|\n',
+                            '|'.join(header[1]), '|\n'])
+        else:
+            return "# PROMPT LISTING\n___\n"
+
+    def _format_url(self, post_id):
+        """ Return a Reddit link for a given post ID.  This defaults to
+        http://reddit.com; override this method to use a config-specific
+        domain. """
+        return ''.join(['http://reddit.com/', post_id])
+
+    def __format_prompt_short(self, prompt):
+        """ Format a prompt row for listing in short (tabular) format. """
+        if prompt is not None:
+            str_data = []
+            # ID
+            str_data.append(unicode(prompt.id))
+            # Post time
+            str_data.append(
+                            self._localtime(prompt.post_time).\
+                            strftime('%Y-%m-%d %H:%M:%S'))
+            # status
+            if prompt.status == prompt.STATUS_POSTED:
+                str_data.append(self.md_link(
+                    prompt.get_status_string(),
+                    self._format_url(prompt.r_post_id)))
+            else:
+                str_data.append(prompt.get_status_string())
+            # title
+            str_data.append(prompt.title)
+            # submit time
+            str_data.append(
+                            self._localtime(prompt.submit_time).\
+                            strftime('%Y-%m-%d %H:%M:%S'))
+            # submitter
+            if prompt.r_source_url:
+                str_data.append(self.md_link(
+                    prompt.user, prompt.r_source_url))
+            else:
+                str_data.append(prompt.user)
+            # approver
+            str_data.append(prompt.approver.c.uname)
+            # text
+            if len(prompt.text) > self.SHORT_TEXT_LENGTH:
+                str_data.append(prompt.text[0:self.SHORT_TEXT_LENGTH-3] + '...')
+            else:
+                str_data.append(prompt.text)
+            # final newline
+            str_data.append(u'\n')
+
+            return u'|'.join(str_data)
+
+    def __format_prompt_long(self, prompt):
+        """ Format an entry for listing in full-length format. """
+        if prompt is not None:
+            str_data = []
+            # ID
+            str_data.append(u' '.join(
+                [u'#', unicode(prompt.id), prompt.title]))
+            str_data.append('\n')
+            # status
+            str_data.append(u'Status: ')
+            if prompt.status == prompt.STATUS_POSTED:
+                str_data.append(self.md_link(
+                    prompt.get_status_string(),
+                    self._format_url(prompt.r_post_id)))
+            else:
+                str_data.append(prompt.get_status_string())
+            str_data.append(u'\n')
+            # Post time
+            str_data.append(u''.join([u'Post time: ',
+                            self._localtime(prompt.post_time).\
+                            strftime('%Y-%m-%d %H:%M:%S'), u'\n']))
+            # submit time
+            str_data.append(u''.join([u'Submit time: ',
+                            self._localtime(prompt.submit_time).\
+                            strftime('%Y-%m-%d %H:%M:%S'), u'\n']))
+            # submitter
+            str_data.append(u'Submitter: ')
+            if prompt.r_source_url:
+                str_data.append(self.md_link(
+                    prompt.user, prompt.r_source_url))
+            else:
+                str_data.append(prompt.user)
+            str_data.append(u'\n')
+            # approver
+            str_data.append(
+                ''.join(['Approver: ', prompt.approver.c.uname, u'\n']))
+            # text
+            str_data.append(u'\n')
+            str_data.append(prompt.text)
+            # final newline
+            str_data.append(u'\n')
+
+            return u''.join(str_data)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.