Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS 

Custom SQL query without find_by_sql

What if you need to call a custom query in Rails? In most cases you'll be content with ditching ActiveRecord::Base.find and going with .find_by_sql. But instantiating an Active Record per row is expensive. What if you want something faster, but you still want an OO feel? Pop this in your environment.rb (or a separate file) and give this a whirl:

   1  
   2  # OO-ified connection.select_all
   3  require 'ostruct'
   4  module ActiveRecord
   5    class Base
   6      class << self
   7        def select_all(query)
   8          rows = connection.select_all(query)
   9          rows.map! do |row|
  10            row = OpenStruct.new(row)
  11            table = row.send(:table)
  12            table.each {|k, v| table[k] = select_type_cast(v) }
  13            row
  14          end
  15          rows
  16        end
  17        def select_one(query)
  18          select_all(query).first
  19        end
  20        def select_value(query)
  21          select_type_cast(connection.select_value(query))
  22        end
  23        def select_type_cast(v)
  24          return unless v
  25          if md = v.match(/^(\d{4})-(\d{2})-(\d{2})$/)
  26            Date.new(*md.captures.map(&:to_i)) rescue v
  27          elsif md = v.match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/)
  28            Time.local(*md.captures.map(&:to_i)) rescue v
  29          elsif v =~ /^\d+$/
  30            v.to_i
  31          elsif v =~ /^\d+(?:\.\d+)+$/
  32            v.to_f
  33          else
  34            v
  35          end
  36        end
  37      end
  38    end
  39  end

Configuring Asterisk as a Jabber client

Here's my working instructions to connect my Asterisk box as a client to my Jabber server. When a call comes in on extension 10 a message is sent to me.


file: jabber.conf
   1  
   2  [general]
   3  debug=yes                               ;;Turn on debugging by default.
   4  autoprune=no                            ;;Auto remove users from buddy list.
   5  autoregister=yes                        ;;Auto register users from buddy list. 
   6  
   7  [asterisk]                              ;;label
   8  type=client                             ;;Client or Component connection
   9  serverhost=jamesrobertson.eu
  10                                          ;;      talk.google.com
  11  username=asterisk@jamesrobertson.eu/Home        ;;Username with optional roster.
  12  
  13  secret=XXXXXXXX                         ;;Password
  14  port=5222                               ;;Port to use defaults to 5222
  15  usetls=no                               ;;Use tls or not
  16  ;usesasl=yes                            ;;Use sasl or not
  17  buddy=james@jamesrobertson.eu
  18  statusmessage="I am available"          ;;Have custom status message for
  19                                          ;;Asterisk.
  20  timeout=100                             ;;Timeout on the message stack.
  21  

file: extensions.conf
   1  
   2  exten => 10,1,JABBERSend(asterisk,james@jamesrobertson.eu, Call from ${CALLERID(name)} at number <${CALLERID(num)}> on ${STRFTIME(,GMT-1,%A %B %d %G at %l:%M:%S %p)} )
   3  exten => 10,n,Macro(stdexten,100,100)
   4  


output (observed in my chat window from user Asterisk)
Call from Line 1 - Home at number <6200> on Sunday May 18 2008 at 8:53:24 PM

scala extensions for emacs

// description of your code here

   1  
   2  (require 'scala-mode)
   3  (require 'compile)
   4  (require 'flymake)
   5  (require 'font-lock)
   6  
   7  (defvar scala-build-commad nil)
   8  (make-variable-buffer-local 'scala-build-command)
   9  
  10  (add-hook 'scala-mode-hook
  11            (lambda ()
  12  	    (flymake-mode-on)
  13  	    ))
  14  
  15  (defun flymake-scala-init ()
  16    (let* ((text-of-first-line (buffer-substring-no-properties (point-min) (min 20 (point-max)))))
  17      (progn
  18        (remove-hook 'after-save-hook 'flymake-after-save-hook t)
  19        (save-buffer)
  20        (add-hook 'after-save-hook 'flymake-after-save-hook nil t)
  21        (if (string-match "^//script" text-of-first-line)
  22  	  (list "fsc" (list "-Xscript" "MainScript" "-d" "c:/tmp" buffer-file-name))
  23  	(or scala-build-command (list "fsc" (list "-d" "c:/tmp" buffer-file-name))))
  24        )))
  25  
  26  (push '(".+\\.scala$" flymake-scala-init) flymake-allowed-file-name-masks)
  27  (push '("^\\(.*\\):\\([0-9]+\\): error: \\(.*\\)$" 1 2 nil 3) flymake-err-line-patterns)
  28  
  29  (set (make-local-variable 'indent-line-function) 'scala-indent-line)
  30  
  31  (defun scala-indent-line ()
  32    "Indent current line of Scala code."
  33    (interactive)
  34    (indent-line-to (max 0 (scala-calculate-indentation))))
  35  
  36  (defun scala-calculate-indentation ()
  37    "Return the column to which the current line should be indented."
  38    (save-excursion
  39      (scala-maybe-skip-leading-close-delim)
  40      (let ((pos (point)))
  41        (beginning-of-line)
  42        (if (not (search-backward-regexp "[^\n\t\r ]" 1 0))
  43  	  0
  44  	(progn
  45  	  (scala-maybe-skip-leading-close-delim)
  46  	  (+ (current-indentation) (* 2 (scala-count-scope-depth (point) pos))))))))
  47  
  48  (defun scala-maybe-skip-leading-close-delim ()
  49    (beginning-of-line)
  50    (forward-to-indentation 0)
  51    (if (looking-at "\\s)")
  52        (forward-char)
  53      (beginning-of-line)))
  54  
  55  (defun scala-face-at-point (pos)
  56    "Return face descriptor for char at point."
  57    (plist-get (text-properties-at pos) 'face))
  58  
  59  (defun scala-count-scope-depth (rstart rend)
  60    "Return difference between open and close scope delimeters."
  61    (save-excursion
  62      (goto-char rstart)
  63      (let ((open-count 0)
  64  	  (close-count 0)
  65  	  opoint)
  66        (while (and (< (point) rend)
  67  		  (progn (setq opoint (point))
  68  			 (re-search-forward "\\s)\\|\\s(" rend t)))
  69  	(if (= opoint (point))
  70  	    (forward-char 1)
  71  	  (cond
  72  
  73              ;; Use font-lock-mode to ignore strings and comments
  74  	   ((scala-face-at-point (- (point) 1))) 
  75  
  76  	   ((looking-back "\\s)")
  77  	    (incf close-count))
  78  	   ((looking-back "\\s(")
  79  	    (incf open-count))
  80  	   )))
  81        (- open-count close-count))))
  82  
  83  
  84  (provide 'scala-extensions)
  85  

Helpful extensions to core Ruby classes

If you find yourself doing this a lot:

   1  
   2  <% if @collection.any? -%>
   3  <ol>
   4    <% for item in @collection %>
   5      <li><%= item %></li>
   6    <% end -%>
   7  </ol>
   8  <% end -%>


...you might want to extend two Ruby core classes to automagically print out HTML-lists. Extend Array with:

   1  
   2  def to_html_list(type = :ol)
   3    self.inject("<#{type}>\n") { |output, item| output << "\t<li>#{item}</li>\n" } << "</#{type}>\n" if self.any?
   4  end


Now you can produce both OL (default) and UL lists. You can easily convert a Hash into a DL-list by extending it like so:

   1  
   2  def to_html_list
   3    self.inject("<dl>\n") { |o, p| o << "\t<dt>#{p[0]}</dt>\n\t<dd>#{p[1]}</dd>\n" } << "</dl>\n" if self.any?
   4  end


Extending core classes is a bit dangerous but I use these in almost every Rails project.

Recursively add file extensions in OSX using Magic and your own filetypes

ExtensionAdder v.1

ExtensionAdder is an OSX ruby script that recursively traverses a folder, adding extensions to approprate files. The script uses the Magic file, but you can extend the behavior by adding your own shell scripts (see the "includes" folder) to grep into files that Magic only classifies as "data".

At this time you have to explicitly state which file types you want to add extensions to.

Download it here

-Sandon Jurowski
jurowski@wisc.edu
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS