example snippets

Valid RSS 2.0 Feed Template for Rails

Tagged ruby, rails, rss2.0, feed, rss, template, example, atom  Languages ruby

If you like Atom more than RSS use the atom_feed_helper.

Here's the template, modify it to fit your needs. I know there are plugins and other ways of doing this, but I hate code that gets too abstract:

<?xml version="1.0"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <atom:link href="http://xxxxxxx" rel="self" type="application/rss+xml" />
    <title>Code Snippets - Aktagon</title>
    <link>http://snippets.aktagon.com/</link>
    <description>Share your code with the world. Allow others to review and comment.</description>
    <language>en-us</language>
    <pubDate><%= @snippets[0].created_at.rfc822 %></pubDate>
    <lastBuildDate><%= @snippets[0].created_at.rfc822 %></lastBuildDate>
    <docs>http://blogs.law.harvard.edu/tech/rss</docs>
    <generator>Aktagon Snippets</generator>
 <% for snippet in @snippets %>
    <item>
      <title><![CDATA[<%= snippet.title %>]]></title>
      <link><%= snippet_url(snippet) %></link>
      <description><![CDATA[<%= snippet.rendered_body %>]]></description>
      <pubDate><%= @snippets[0].created_at.rfc822 %></pubDate>
      <guid><%= snippet_url(snippet) %></guid>
      <% for tag in snippet.tags%>
        <category domain="http://snippets.aktagon.com/snippets"><![CDATA[<%= tag.name %>]]></category>
      <% end%>
    </item>
<% end %>
  </channel>
</rss>

Remember to serve the feed with the correct HTTP headers.

It also helps to have an auto-discovery tag inside the head tag:

<link rel="alternate" type="application/rss+xml" title="RSS feed" href="http://<%= request.host %>/rss/" />

Example of how to fetch a URL with Net:HTTP and Ruby

Tagged net, http, ruby, example, headers  Languages ruby
require 'net/http'
require 'net/https'

url = URI.parse('http://www.google.com/yo?query=yahoo')

http = Net::HTTP.new(url.host, url.port)

http.open_timeout = http.read_timeout = 10  # Set open and read timeout to 10 seconds
http.use_ssl = (url.scheme == "https")
       
headers = {
  'User-Agent'          => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12',
  'If-Modified-Since'   => '',
  'If-None-Match'       => ''
}

# Note to self, use request_uri not path: http://www.ruby-doc.org/core/classes/URI/HTTP.html#M004934
response, body = http.get(url.request_uri, headers)

puts response.code
puts response.message

response.each {|key, val| puts key + ' = ' + val}

Ruby Regular expression examples

Tagged regular expression, ruby, example, regex  Languages ruby
# extract xxx
text = "{{xxx}}"
if text[/\{\{(.*)?\}\}/]
  xxx = $1
end

# extract all headers from a raw Wikipedia article
# example:
# ==Banks==
# ===Fraud===
# ===Corruption===
# \1 = back reference
headers = text.scan(/^(={1,5})(.+?)\1$/m).inject([]) do |result, m|
  header = OpenStruct.new(:depth => m[0].length, :title => m[1])
  result << header
  print ("    "*header.depth) + header.title + "\n"
  result
end

Example of how to use Ruby's NET::HTTP

Tagged http, net::http, ruby, example, debug, https, timeout, proxy  Languages ruby

I always forget how to use NET:HTTP and examples online are of little help, so I use this code as a starting point when I work with NET:HTTP.

The code supports: * HTTP redirects * POST/GET * Headers * SSL/HTTPs * Proxies * Debugging HTTP traffic * HTTP connection and read timeout

require 'net/http'
require 'net/https'
require 'uri'

class HTTP
  class << self
    def get(url, options = {})
      execute(url, options)
    end

    def post(url, options = { :method => :post })
      execute(url, options)
    end

    protected
      def proxy
        http_proxy = ENV["http_proxy"]
        URI.parse(http_proxy) rescue nil
      end

      def to_uri(url)
        begin
          if !url.kind_of?(URI) 

            url = URI.parse(url)
          end
        rescue
          raise URI::InvalidURIError, "Invalid url '#{url}'"
        end

        if (url.class != URI::HTTP && url.class != URI::HTTPS)
          raise URI::InvalidURIError, "Invalid url '#{url}'"
        end

        url
      end

      def execute(url, options = {})
        options = { :parameters => {}, :debug => false, 
                    :http_timeout => 60, :method => :get, 
                    :headers => {}, :redirect_count => 0, 
                    :max_redirects => 10 }.merge(options)

        url = to_uri(url)
        
        if proxy
          http = Net::HTTP::Proxy(proxy.host, proxy.port).new(url.host, url.port)
        else
          http = Net::HTTP.new(url.host, url.port)
        end
        
        if url.scheme == 'https'
          http.use_ssl = true
          http.verify_mode = OpenSSL::SSL::VERIFY_NONE
        end
        
        http.open_timeout = http.read_timeout = options[:http_timeout]
        
        http.set_debug_output $stderr if options[:debug]
        
        request = case options[:method]
          when :post
            request = Net::HTTP::Post.new(url.request_uri)
            request.set_form_data(options[:parameters])
            request
          else
            Net::HTTP::Get.new(url.request_uri)
        end

        options[:headers].each { |key, value| request[key] = value }
        response = http.request(request)

        if response.kind_of?(Net::HTTPRedirection)      
          options[:redirect_count] += 1

          if options[:redirect_count] > options[:max_redirects]
            raise "Too many redirects (#{options[:redirect_count]}): #{url}" 
          end

          redirect_url = redirect_url(response)

          if redirect_url.start_with?('/')
            url = to_uri("#{url.scheme}://#{url.host}#{redirect_url}")
          end

          response = execute(url, options)
        end

        response
      end

      # From http://railstips.org/blog/archives/2009/03/04/following-redirects-with-nethttp/
      def redirect_url(response)
        if response['location'].nil?
          response.body.match(/<a href=\"([^>]+)\">/i)[1]
        else
          response['location']
        end
      end
  end
end

You can also find my Net:HTTP example on Github

How to use the Perl DBI module

Tagged example, perl, dbi, mysql  Languages perl

Basic usage

use strict;
use DBI;
use DBD::mysql;

my $host = 'localhost';
my $database = 'xxx';
my $user = 'xxx';
my $password = '';

my $dsn = "dbi:mysql:$database:$host:3306";
my $db = DBI->connect($dsn, $user, $password);
 
my $sql = q(
  INSERT INTO 
    what (name, instructions) 
  VALUES (?, ?)
);

my $p = $db->prepare($sql);

my $result = $p->execute($name, $instructions);

print $result;

my $id = $dbh->{'mysql_insertid'};

One-liner for selecting one row

my $c = 'Horse';
my ($id, $instructions) = $db->selectrow_array("select id, instructions from categories where name = ?", undef, $c);

Go and Postgres Example

Tagged polling, example, golang, postgres  Languages go, bash
package main

import (
    "database/sql"
    _ "github.com/lib/pq"
    "log"
    "time"
)

func pollChanges() {
    var id int
    var name string
    rows, err := db.Query("SELECT id, name FROM people")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()
    for rows.Next() {
        err := rows.Scan(&id, &name)
        if err != nil {
            log.Fatal(err)
        }
        log.Println(id, name)
    }
    err = rows.Err()
    if err != nil {
        log.Fatal(err)
    }
}

var db *sql.DB

func main() {
    var err error
    db, err = sql.Open("postgres", "")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()
    for {
        time.Sleep(1000 * time.Millisecond)
        log.Println("Polling for changes...")
        pollChanges()
    }
}

Run:

PGUSER= PGPASSWORD= PGDATABASE=db_xyz PGSSLMODE=disable ./go-app

Notes

Using question marks instead of, e.g., $1 will result in the following error:

syntax error at or near ","
  • Scan requires a pointer. Forgetting to add an ampersand (Scan(id) vs Scan(&id)) will result in the following error:
Scan error on column index 0: destination not a pointer

Nim web application example

Tagged nim, jester, example  Languages bash, nim
brew install nimlang
nimble install jester
vim hello.nim
nim compile --run hello.nim
import jester, asyncdispatch, strutils, asyncnet, htmlgen, logging
#
# * CLI *
#
# brew install nimlang
# nimble install jester
# vim hello.nim
# nim compile --run hello.nim
#
# * DOCS *
#
# https://nim-lang.org/docs/htmlgen.html
# https://learnxinyminutes.com/docs/nim/
#
var L = newConsoleLogger()
addHandler(L)

settings:
  port = Port(3000)
  appName = "/"
  bindAddr = "127.0.0.1"

proc layout(content: string): string =
  htmlgen.html(htmlgen.body(content))

routes:
  get "/":
    logging.debug("render form $1 $2" % [$status, $headers])
    var content = `div`(
        h1(a(href="http://nim-lang.org", title="Hello", "Hello Nim")),
        """
        <form name="input" action="$1" method="post">
          <input type="text" name="first_name" value="" placeholder="First name" />
          <input type="text" name="last_name" value="" placeholder="Last name" />
          <input type="submit" value="Submit" />
        </form>
        """ % [uri("/", absolute = false)]
        )
    body.add(layout(content))
    status = Http200

  post "/":
    logging.debug("process form $1 $2" % [$status, $headers])
    # TODO: How can we sanitize submitted form data?
    var content = `div`(
        h1(
          a(href="http://nim-lang.org", title="Hello", "Hello $1 $2" % [$request.params["first_name"], $request.params["last_name"]])
        ),
        h4("Form data"),
        p($request.params),
    )
    body.add(layout(content))
    status = Http200

runForever()