Never been to TextSnippets 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 (or not, you can keep them private!)

About this user

Kjell (misterk @forum.textdrive) http://station11.net

« Newer Snippets
Older Snippets »
7 total  XML / RSS feed 

Dynamic time based finder for ActiveRecord

I think it's pretty nice. Get all records within a railsified period of time (7.days.ago, 12.months.ago). I can do cool things like Workout.within_12_days or Workout.within_12_hours. Further conditions can be given as a hash, and will be transposed onto the end of the :conditions.

Workout.within_n_units(:user_id => 12) #-> Workout.find(:all, :conditions => 'created_at > n.units.ago and user_id = 12')


class Workout < ActiveRecord::Base
  class << self
    def within_n_temporal_units(number, units, further_conds={})
      conds = "created_at > '#{eval("#{number}.#{units}.ago").to_s(:db)}'"
      further_conds.each {|key, val| conds << " and #{key} = #{val}"}
      Workout.find(:all, :conditions => conds)
    end
    
    def method_missing(name, *args)
      return within_n_temporal_units($~[1], $~[2], args[0] || {}) if name.to_s =~ /within_(\d+)_(\w+)/
      raise NoMethodError, "undefined method `#{name}' for #{self}:Class"
    end
  end
end

JS translation bookmarklet

I got this mostly working - the only thing that sucks is encoding of non-ascii characters like �, �, etc... I've tried escape(), but it's just stripped the offending character. Anyone know js and feel like fixing this?

javascript:langpair="fr|en";
  text=""+(window.getSelection?window.getSelection()
           :document.getselection?document.getSelection()
           :document.selection.createRange().text);
  if(!text)text=prompt("enter%20text%20to%20translate","");
  if(text!=null)void(window.open(
      "http://google.com/translate_t?langpair="+langpair+"&text="+text,
     "translate","scrollbars=1,resizablel=1,width=500,height=500"))

Development Actionmailer setup problems

Has anyone been able to do this? My ActionMailer works fine when it's on barclay, but for developing locally I can't make a connection. I get:

Errno::ECONNREFUSED in Contact#index

Connection refused - connect(2)

/app/controllers/contact_controller.rb:6:in `index'


My isp doesn't block port 25:

[] % telnet barclay.textdrive.com 25
Trying 207.7.108.37...
Connected to barclay.textdrive.com.
Escape character is '^]'.
220 barclay.textdrive.com ESMTP Postfix
^]


And my ActionMailer config in config/environments/development.rb is this:

ActionMailer::Base.server_settings = {
  :address  => "barclay.textdrive.com",
  :port  => 25, 
  :domain  => 'http://station11.net/',
  :user_name  => "#{username}", # without @domain
  :password  => "#{password}",
  :authentication  => :plain
}

Rails new/add/delete helper

Call: @registered_user_functions( @photo )@, get ( new | edit | delete ) links.
  def registered_user_functions( item = nil, show_new = true )
    # abstract name of html#id to update with javascript
    update_name = item.class.to_s.downcase
    if @session[:user]
      a = "( "
      a << link_to( 'new', :action => 'new' ) + " | " if show_new
      if item # is given to edit or destroy...
        a << link_to_remote( "edit",
              {:url => { :action => "edit", :id => item },
              {:href => url_for( :action => "edit", :id => item ) },
              :update => "#{update_name}-#{item.id}" } )
        a << " | "
        a << link_to_remote( "delete",
              {:url => { :action => "destroy", :id => item },
              {:href => url_for( :action => "destroy", :id => item ) },
              :update => "#{update_name}-#{item.id}",
              :confirm => "really delete this #{update_name}?" } )
      end
      a << " )"
    end
  end

Real good Granola

- Ingredients:

3 cups rolled oats
1 1/4 cups bran flakes
3/4 cup shredded coconut
1/2 cup walnuts
1 cup sliced almonds
3/4 cup salted sunflower seeds
2 teaspoons cinnamon
2 1/2 teaspoons pure maple syrup
honey (1/3-1/2 cup depending on taste)
canola oil (1/3-1/2 cup)

Preheat oven to 350 degrees. Cover baking sheets with wax paper and grease with cooking spray. Combine oats, bran flakes, coconut, walnuts, almonds, sunflower seeds, and cinnamon in a large bowl. Mix maple syrup, honey and oil in small bowl; add to dry mixture and stir until well mixed. Spread on cookie sheet(s) and bake for 20-25 minutes until golden brown, tossing granola halfway through baking time to keep edges from burning. Cool completely before storing.

Make your shell beep at you

My computer is real slow, and when I want to do things like rake a rails app or compile something, it takes awhile, and I always forget what was doing. But not if I can have some sort of alarm go off whenever the terminal finishes it's current task:

alias beep="echo -en \"\\007\""


Bingo! Then just clip it onto the end of a command, and when that command finishes, the terminal should beep (\007 is a character code that should make a sound when it's echoed).

rake;beep


And rake can run all the tests I've written for a rails app, and give me a yell when it finishes.

lighttpd as a startup item on os x

Create the /Library/StartupItems/Lighttpd directory, put both the Lighttpd (chmod +x) and the StartupParameters.plist (I don't really know what this does at all) files into the directory. (this is on jaguar, before the new launchd came out in tiger).

Then add the following line to /etc/hostconfig:

LIGHTTPD=-YES-


You can start, stop and restart lighttpd using /Library/StartupItems/Lighttpd (start|stop|restart) now, and it will startup when OS X boots.

-------- Lighttpd
#!/bin/sh
#
# /Library/StartupItems/Lighttpd/Lighttpd
#
# Script to startup lighttpd with OS X booting.
# OS X 10.3 Jaguar
# modified by kjell olsen
#
# adapted from the startup mysql
# (c) 2003 MySQL AB
# Written by Lenz Grimmer 
#

# Suppress the annoying "$1: unbound variable" error when no option
# was given
if [ -z $1 ] ; then
        echo "Usage: $0 [start|stop|restart] "
        exit 1
fi

# Source the common setup functions for startup scripts
test -r /etc/rc.common || exit 1
. /etc/rc.common

# change config and script to match your machine's lighttpd config and lighttpd
CONFIG="/etc/lighttpd/lighttpd.conf"
SCRIPT="/usr/local/sbin/lighttpd"

StartService () 
{
  if [ "${LIGHTTPD:=-NO-}" = "-YES-" ] ; then
    ConsoleMessage "Starting Lighttpd Server"
    $SCRIPT -f $CONFIG
  fi
}

StopService ()
{
  ConsoleMessage "Killing Lighttpd Server"
  kill `cat /var/run/lighttpd.pid` 
}

RestartService ()
{
        ConsoleMessage "Restarting Lighttpd server"
        /Library/StartupItems/Lighttpd/Lighttpd stop
        /Library/StartupItems/Lighttpd/Lighttpd start
}

if test -x $SCRIPT ; then
        RunService "$1"
else
        ConsoleMessage "Could not find lighttpd startup script!"
fi

Be sure to change $SCRIPT + $CONFIG to work with your own lighttpd.

-------- StartupParameters.plist
<?xml version="1.0" encoding="UTF-8"?>
DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Descriptionkey>
        Lighttpd 1.13</string>
        <key>OrderPreferencekey>
        None</string>
        <key>Provideskey>
        
                Lighttpd</string>
        array>
        Uses</key>
        <array>
                <string>Networkstring>
                Resolver</string>
        array>
        </dict>
plist>


Again, I'm not exactly sure what this does. I copied it from the MYSQL one and changed the description and provider, left "uses" alone.
« Newer Snippets
Older Snippets »
7 total  XML / RSS feed