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-10 of 111 total  RSS 

Custom Rails Callback

// This shows you how to extend active record to allow a custom callback.

#ever needed to add your own callback into the active record callback chain?
#here's how...
module ActiveRecord
  
  #to keep things clean we'll define our own module
  module SweetCustomCallbacks
    
    #this is the ruby method that is called when you call include on a module
    #the method passed, base in our case, is the class your including yourself in
    def self.included(base)
      
      #this clas_eval method takes a block that will be added to base, which is ActiveRecord::Base
      #basically this is like writing code directly into the class ActiveRecord::Base
      base.class_eval do
        
        #alias_method_chain is very cool
        #it allows us override a method without removing the original and without the original knowing its been changed
        #here's how it works:
        # 1st argument is the name of the method you're overriding
        # 2nd argument is feature you want to add
        # so if create_or_update is called it will actually call create_or_update_with_sweet_custom_callbacks
        # the original is still avaliable at create_or_update_without_custom_callbacks
        
        alias_method_chain :create_or_update, :sweet_custom_callbacks
        #the method create_or_update is an internals method to ActiveRecord that is called whenever you call .save or .update
        
        #this is the class method that allows the cool syntax:
        # class Article < ActiveRecord::Base
        # before_before_save :add_authors_name
        #private
        #def add_authors_name
        #.....
        def self.before_before_save(*callbacks, &block)
          callbacks << block if block_given? #add the block to the array of callback functions if a block was passed
          write_inheritable_array(:before_before_save,callbacks) 
        end
      end
    end
    
    #the instance method, although not recomended is avaliable for overriding
    #also if you wanted to have a callback that always did something say add the users's id to the object 
    #you could always code that in here and remove the class above
    def before_before_save() end

    #ok this is the method that is now called instead of create_or_update
    #it calls a method callback on 
    def create_or_update_with_sweet_custom_callbacks
      return false if callback(:before_before_save) == false  #this method does all the real work and calls the callback function in callbacks.rb that gets the methods and runs them 
      create_or_update_without_sweet_custom_callbacks
    end
    
   end
 
   class Base    
     include SweetCustomCallbacks #include our module in ActiveRecord::Base
   end
end

Convert a UTF-8 string to ISO-8859-1

Convert a utf string to iso, used this when generating a pdf with pdf-writer in Rails, all my text is UTF8 but pdf-writer does not support this.

#add this to environment.rb
#call to_iso on any UTF8 string to get a ISO string back
#example : "Cédez le passage aux français".to_iso

class String
  require 'iconv' #this line is not needed in rails !
  def to_iso
    Iconv.conv('ISO-8859-1', 'utf-8', self)
  end
end

open_body_tag

  #creates a body tag uniquely indentifying this page
  #takes an options Hash with two keys:
  #
  #<tt>id</tt>::        string that will be used as the body's ID. defaults to <tt>controller.controller_name.singularize</tt>
  #<tt>classes</tt>::   an Array of class names. defaults to <tt>[params[:action]]</tt>
  #
  #Examples:
  #
  # in HomeController#index:
  #
  # <%= open_body_tag %>
  # => <body id='home' class='index'>
  #
  # <%= open_body_tag(:id => 'foo') %>
  # => <body id='foo' class='index'>
  #
  # <%= open_body_tag(:id => 'foo', :classes => %w(one two)) %>
  # => <body id='foo' class='one two'>
  def open_body_tag(options = { :id => controller.controller_name.singularize, :classes => [params[:action]] })
    "<body id='#{options[:id]}' class='#{options[:classes].join(' ')}'>"
  end

Convert .rhtml templates to .html.erb

// run this shell command from within the dir you want to change. You will need to change the hg line to use which ever version control you are using, or if you're not use version control (naughty!) then leave out the hg letters altogether.

for f in $(find . -name '*.rhtml') ; do c=$(dirname $f)/$(basename $f .rhtml).html.erb ; hg mv $f $c ; done

Rails URL Validation

No regexes, allows URLs with ports or IPs. Inspiration from here

  validates_each :href, :on => :create do |record, attr, value|
    begin
      uri = URI.parse(value)
      if uri.class != URI::HTTP
        record.errors.add(attr, 'Only HTTP protocol addresses can be used')
      end
    rescue URI::InvalidURIError
      record.errors.add(attr, 'The format of the url is not valid.')
    end
  end

Helper for testing default routes generated by a resource in Ruby on Rails

These methods test that the routes for resources defined in routes.rb are working as expected. Call them from your functional (controller) tests.

Add the following 3 methods to test/test_helper.rb (updated for Rails 1.2.5 which no longer uses semicolons as a separator for the edit action):
# Test for routes generated by map.resource (singular).
def assert_routing_for_resource(controller, skip=[], nesting=[])
  routes = [
    ["new",'/new',{},:get], ["create",'',{},:post],
    ["show",'',{},:get], ["edit",'/edit',{},:get],
    ["update",'',{},:put], ["destroy",'',{},:delete]
    ]
  check_resource_routing(controller, routes, skip, nesting)
end
# Test for routes generated by map.resources (plural).
def assert_routing_for_resources(controller, skip=[], nesting=[])
  routes = [
    ["index",'',{},:get], ["new",'/new',{},:get], ["create",'',{},:post],
    ["show",'/1',{:id=>'1'},:get], ["edit",'/1/edit',{:id=>'1'},:get],
    ["update",'/1',{:id=>'1'},:put], ["destroy",'/1',{:id=>'1'},:delete]
    ]
  check_resource_routing(controller, routes, skip, nesting)
end

# Check that the expected paths will be generated by a resource, and that
# the expected params will be generated by paths defined by a resource.
# routes is array of [action, url string after controller, extra params].
def check_resource_routing(controller, routes, skip=[], nesting=[])
  # set a prefix for nested resources
  prefix = nesting.join('s/1/')
  unless prefix.blank?
    prefix += "s/1/"
  end
  # Add params for nested resources.
  # For each 'nest', include a ":nest_id=>'1'" param.
  params = {}
  nesting.each do |param|
    params["#{param}_id".to_sym] = '1'
  end
  # Test each of the standard resource routes.
  routes.each do |pair|
    unless skip.include? pair[0]
      assert_generates("/#{prefix}#{controller}#{pair[1]}",
        {:controller=>controller,
        :action=>pair[0]}.merge(pair[2]).merge(params), {}, {},
        "Failed generation of resource route for action #{pair[0]} /#{prefix}#{controller}#{pair[1]}")
      assert_recognizes(
        {:controller=>controller,
          :action=>pair[0]}.merge(pair[2]).merge(params),
        {:path=>"/#{prefix}#{controller}#{pair[1]}", :method=>pair[3]},
        {}, "Failed to recognize resource route for path #{pair[3]}:/#{prefix}#{controller}#{pair[1]}")
    end
  end
end

EXAMPLES

You can specify actions to 'skip' (if you have a special route for that action).
If using nested resources, set the nesting array (use singular strings).

So, if you have the following in routes.rb:
map.make_thing '/make', :controller=>'things', :action=>'new'
map.resources :nests do |nest|
  nest.resources :things
end
map.resource :foo

then you can use the following in things_controller_test.rb:
def test_resource_routing
  assert_routing_for_resources 'things', ['new'], ['nest']
  assert_routing_for_resource 'foo'
end

Modified Growl support for Ruby autotest

# This code is a different approach to using Growl notifications (Mac OS X)
# with autotest for Ruby.
# The code can be added to ~/.autotest
# Be sure to comment out "require 'autotest/growl'" if you have that line
# in your .autotest file.
# Based on ZenTest-3.6.1/lib/autotest/growl.rb
# Requires the 2 rails png graphics found at:
# http://blog.internautdesign.com/2006/11/12/autotest-growl-goodness

module Autotest::Growl
  # save the name of the working directory (e.g., the app name)
  # to be used as a key to identify this particular run of autotest
  # so the same growl notification will be reused for updates,
  # instead of a new growl window for every posting.
  @@current_directory_name = Dir.pwd.match(/([^\/]+)\z/).to_s
  def self.growl title, msg, pri=0
    title += " in #{@@current_directory_name}"
    msg += " at #{Time.now}"
    # ### change the path to the directory for the png graphics:
    system "growlnotify -n autotest #{pri > 0 ? '-s ' : ''}--image /Users/grant/Pictures/rails_#{pri > 0 ? 'fail' : 'ok'}.png -p #{pri} -d '#{Dir.pwd}' -m #{msg.inspect} #{title}"
  end

  Autotest.add_hook :run do  |at|
    growl "autotest running", "Started"
  end
  Autotest.add_hook :red do |at|
    growl "Tests Failed", "#{at.files_to_test.size} tests failed", 2
  end
  Autotest.add_hook :green do |at|
    growl "Tests Passed", "Tests passed", -2 if at.tainted
  end
  Autotest.add_hook :all_good do |at|
    growl "Tests Passed", "All tests passed", -2 if at.tainted
  end
end

Using POP3 to Retrieve Email for Rails App

Put this in a file called "inbox" in the scripts/ directory of your Rails app. change the host, username, and password to match.

Set up a cron job to run this script every so often (frequency depends on your needs).

#!/usr/bin/env ruby

require 'net/pop'
require File.dirname(__FILE__) + '/../config/environment'

logger = RAILS_DEFAULT_LOGGER

logger.info "Running Mail Importer..." 
Net::POP3.start("localhost", nil, "username", "password") do |pop|
  if pop.mails.empty?
    logger.info "NO MAIL" 
  else
    pop.mails.each do |email|
      begin
        logger.info "receiving mail..." 
        Notifier.receive(email.pop)
        email.delete
      rescue Exception => e
        logger.error "Error receiving email at " + Time.now.to_s + "::: " + e.message
      end
    end
  end
end
logger.info "Finished Mail Importer." 

Setting up Ruby On Rails with PostgreSQL on Mac OS X 10.4.9

This is a modified version of the Ruby on Rails Tutorial (TutorialStepOne, TutorialStepOnePostgresql, ...).

Log in to an admin user account and, if necessary, fix your command search path in $HOME/.bash_profile, $HOME/.bash_login or $HOME/.profile to include "/usr/local" and "/usr/local/sbin" (cf. Using /usr/local > Set The Path; echo $PATH | tr ":" "\n"). If there are no such files, just create them: touch $HOME/.bash_login && touch $HOME/.bashrc (ls -a | grep \.bash).

To avoid RubyGems loading issues it's no bad idea to add export RUBYOPT=rubygems to your $HOME/.bash_login file as well.

If you want your system path changes to take effect not only for you you can modify the global system path settings in the systemwide initialization files /private/etc/profile and /private/etc/bashrc accordingly.

To fix the paths of installed manual pages add the lines "MANPATH /usr/local/share/man" and "MANPATH /usr/local/man" to sudo nano +45 /usr/share/misc/man.conf (man -w | tr ":" "\n").


(USE THE FOLLOWING AT YOUR OWN RISK!)


REQUIREMENTS:

I. Xcode


II. PostgreSQL Database Server

Install this PostgreSQL Database Server package.

# test after installation
which psql     # /usr/local/bin/psql
psql --version     # psql (PostgreSQL) 8.2.3, contains support for command-line editing


Alternative installation: Getting PostgreSQL running for Rails on a Mac


III. Ruby 1.8.6, Ruby On Rails 1.2.3 & Mongrel 1.0.1

Building Ruby, Rails, Subversion, Mongrel, and MySQL on Mac OS X

To install both Mongrel & Mongrel Cluster use: sudo gem install -y mongrel mongrel_cluster (cf. Using Mongrel Cluster).

# test after installation
ruby -v     # ruby 1.8.6
rails -v     # Rails 1.2.3
gem list     # ... mongrel (1.0.1) ...



IV. ruby-postgres 0.7.1
sudo gem install -y ruby-postgres



As an alternative you may try Ruby on rails installer script for Mac OSX or choose to install via MacPorts as described in Installing Ruby on Rails and PostgreSQL on OS X, Second Edition or Installing Rails on Mac OS X Tiger (10.4.8). However, you then may have to change your system paths mentioned above accordingly.


1. create a database server


# first create a directory called PostgreSQL-db on your Desktop
mkdir -p $HOME/Desktop/PostgreSQL-db

# create a new db server called railsdb
/usr/local/bin/initdb -E UTF8 -D $HOME/Desktop/PostgreSQL-db/railsdb

# START DB SERVER
dir="$HOME/Desktop/PostgreSQL-db"; /usr/local/bin/pg_ctl -D $dir/railsdb -l $dir/railsdb/postgres.log start

# STOP DB SERVER
#dir="$HOME/Desktop/PostgreSQL-db"; /usr/local/bin/pg_ctl -D $dir/railsdb -l $dir/railsdb/postgres.log stop -m smart

# check
cat $HOME/Desktop/PostgreSQL-db/railsdb/pg_hba.conf

   ...
   # TYPE  DATABASE    USER        CIDR-ADDRESS          METHOD

   # "local" is for Unix domain socket connections only
   local   all         all                               trust
   # IPv4 local connections:
   host    all         all         127.0.0.1/32          trust
   # IPv6 local connections:
   host    all         all         ::1/128               trust



2. create PostgreSQL database


createdb `whoami`_development
#dropdb `whoami`_development

createdb `whoami`_test
#dropdb `whoami`_test

#createdb `whoami`_production
#dropdb `whoami`_production



3. set up your Rails project


cd $HOME/Desktop/RubyOnRails-projects
rails -d postgresql `whoami`
cd `whoami`



4. edit /config/database.yml


open -e $HOME/Desktop/RubyOnRails-projects/`whoami`/config/database.yml

# just uncomment the following line
#encoding: UTF8 



5. make Rails & PostgreSQL work together


cd $HOME/Desktop/RubyOnRails-projects/`whoami`

ruby script/generate migration People

# edit /db/migrate/001_people.rb
# cf. http://wiki.rubyonrails.org/rails/pages/TutorialStepOneMigrations

open -e $HOME/Desktop/RubyOnRails-projects/`whoami`/db/migrate/001_people.rb

 class People < ActiveRecord::Migration

    def self.up
      create_table :people do |table|
      # note that "id" is added implicitly, by default
        table.column :name, :string
        table.column :street1, :string
        table.column :street2, :string
        table.column :city, :string
        table.column :state, :string
        table.column :zip, :string
     end
    end

    def self.down
      drop_table :people 
    end
  end



rake db:migrate

ruby script/generate model Person  

#open -e $HOME/Desktop/RubyOnRails-projects/`whoami`/app/models/person.rb  # file will be explained below

ruby script/console

>> ...
        entry = Person.new
        entry.name = "Name" 
        entry.street1 = "123 Somwhere" 
        entry.street2 = "" 
        entry.city = "Smallville" 
        entry.state = "KS" 
        entry.zip = "123456" 
        entry.save
        exit


# check newly created db table

psql `whoami`_development
SELECT * FROM people;
\q


# test
rake      # ... 0 failures, 0 errors

# create new controller
ruby script/generate controller People list view new edit


# edit /app/controllers/people_controller.rb
open -e $HOME/Desktop/RubyOnRails-projects/`whoami`/app/controllers/people_controller.rb

  def view
   @person = Person.find(1)
  end



# edit /app/views/people/view.rhtml
open -e $HOME/Desktop/RubyOnRails-projects/`whoami`/app/views/people/view.rhtml

# copy & paste & uncomment the following lines

#<html>
#  <body>
#    <h1>People#view</h1>
#    <p>This page will display one person.</p>
#    <p>
#    <%= @person.name %><br />
#    <%= @person.street1 %><br />
#    <%= @person.street2 %><br />
#    <%= @person.city %><br />
#    <%= @person.state %><br />
#    <%= @person.zip %><br />
#    </p>
#  </body>
#</html>


# the file /app/models/person.rb explained (see above)
# open -e $HOME/Desktop/RubyOnRails-projects/`whoami`/app/models/person.rb

# class Person < ActiveRecord::Base
# end

# How does this know to map to the people table we created? ActiveRecord pluralizes the class name and looks for that 
# table in the database. This doesn’t just mean adding an ’s’. Irregular plural forms are also handled, so Rails knows 
# that the plural of ‘person’ is ‘people’. The rules for how it does this are described in the documentation
# (see http://wiki.rubyonrails.org/rails/pages/TutorialStepSix).

# test
rake

# start your Rails app
cd $HOME/Desktop/RubyOnRails-projects/`whoami`

ruby script/server
#ruby script/server --environment=development

# open a second shell window and go to ...  
open -a Safari http://localhost:3000/people/view


Print and preselect checkboxes

Create a selection box list and preselect with previously assigned Roles

def createCheckBoxList(user)
    
    userRolesID = Hash.new
    user.roles.each do | ur |
      userRolesID[ur.name] = ur.id   
    end
 
    @roles = Role.find(:all)
    
    html_output = String.new
    # first create the checkbox
      for role in @roles
        if userRolesID.has_key?(role.name)
          html_output << check_box("roles_user", role.id, :checked => 'checked')
        else
          html_output << check_box("roles_user", role.id)
        end
        # then print the role name
        html_output << " " + role.name + "<br />"
      end
      
      return html_output
    
  end
« Newer Snippets
Older Snippets »
Showing 1-10 of 111 total  RSS