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

About this user

« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS 

Ruby Speaks

// if you are using a mac this will allow your Ruby script to speak using the macs native text to speech functionality.

system "osascript -e 'say \"the rain in Spain falls mainly on the planes\"'"

Colorize Function

/*
I don't use the flash colorize function much so this is an example of how to colorize a movieclip with a supplied hexnumber

colorize(0xff0000,my_movieClip);

//will turn my_movieClip bright red.
*/
function colorize(c:Number,mc:MovieClip){
  var tf:Transform = new Transform(mc);
  var color_tf:ColorTransform = new ColorTransform();
  color_tf.rgb = c;
  tf.colorTransform = color_tf;
};

Application version number and cool codename based on subversion number

// description of your code here

#codename generated from the dictionary
REVISION_NUMBER = `svn info`.split("\n")[4][/\d+/].to_i
APP_CODENAME  = IO.readlines("/usr/share/dict/words")[REVISION_NUMBER]

Add Subversion Revsions Number to Rails Application.

// description of your code here
Add this to your environment.rb file for a dead easy way to get your subversion revision into your application.

APP_VERSION  = IO.popen("svn info").readlines[4]

how to escape from AJAX URL

From Dylan Stamat's post on the Ruby on Rails list


Within my "login.rjs" template that get's invoked after my login process, it returns to the same page with an error message on error, or... if the login was successful, it needs to "redirect" to another controller... which is pretty much impossible to do otherwise. so, my " login.rjs" looks like:

if @logged_in_client
  page.replace_html "message", :partial => 'shared/bad_login'
else
  page.redirect_to "whatever you want here"
end

------ End Message--------
Here is my two cents:
Technically, you can do this without a RJS template at all, because it is such a simple example. Use this in your controller

render :update do |page|
  if @logged_in_client
    page.replace_html "message", :partial => 'shared/bad_login'
  else
    page.redirect_to "whatever you want here"
  end
end

Submitting data to two different tables with two different models (or how to modify multiple models from one form)

Taken from Norman Timmler's example on the ruby on rails mailing list.


Take two text fields for example:
# view
<%= form_tag :controller => :posts, :action => create %>
 <%= text_field("post", "title", "size" => 20) %>
 <%= text_field("user", "email", "size" => 20) %>
<%= end_form_tag %>

# posts_controller
class PostsController < ApplicationController
 def create
   @post = Post.create(params[:post])
   @user = User.create(params[:user])
   @post.users << @user
 end
end


In the controller the params hash has one key for every object (user,
post) in your form. As a values of this key you find a hash having a
key-value pair for every object attribute (title, email).

This way you can submit multiple objects via one form.

Create a new instance of Magick::Image out of uploaded form data

Taken from Norman Timmler's example on the Ruby on Rails mailing list:

def file=(new_file)
 new_file.rewind
 image = Magick::Image::from_blob(new_file.read).first
end

rake start_fresh

Sometimes you don't want to fool with migrating up or down a version of your development server and you just want to start fresh. This task will

clear the logs
recreate the test and development databases
migrate to the most recent schema
load all your test fixtures into your development database
clone your development structure to the test database

to use it call "rake start_fresh"


there is also a short "rake start" command, which I tossed in as a little something something, you can use it instead of typing "ruby script/server"


task :start_fresh => :environment do
     Rake::Task[:clear_logs].invoke
     puts 'clearing logs                           ...done'
     
     Rake::Task[:recreate_database].invoke
     puts 'recreate test database                  ...done'
     puts 'recreate development database           ...done'
     
     ActiveRecord::Base.establish_connection(:development)
     Rake::Task[:migrate].invoke
     puts 'migrate the development database        ...done'
     
     Rake::Task[:load_fixtures_to_development].invoke
     puts 'load fixtures into development database ...done'
     
     ActiveRecord::Base.establish_connection(:test)
     Rake::Task[:prepare_test_database].invoke
     puts 'clone the development structure to test ...done'
end

desc "Load fixtures data into the test database"
task :load_fixtures_to_development => :environment do
  require 'active_record/fixtures'
  ActiveRecord::Base.establish_connection(:development)
  Dir.glob(File.join(RAILS_ROOT, 'test', 'fixtures', '*.{yml,csv}')).each do |fixture_file|
    Fixtures.create_fixtures('test/fixtures', File.basename(fixture_file, '.*'))
  end
end

task :recreate_database => :environment do
  abcs = ActiveRecord::Base.configurations
	tdb = Array.new
  tdb << 'test'
  tdb << 'development'

 	for db in tdb
	  case abcs[db]["adapter"]
	    when "mysql"
	      ActiveRecord::Base.establish_connection(db.to_sym)
	      ActiveRecord::Base.connection.recreate_database(abcs[db]["database"])
	    when "postgresql"
	      ENV['PGHOST']     = abcs[db]["host"] if abcs[db]["host"]
	      ENV['PGPORT']     = abcs[db]["port"].to_s if abcs[db]["port"]
	      ENV['PGPASSWORD'] = abcs[db]["password"].to_s if abcs[db]["password"]
	      enc_option = "-E #{abcs[db]["encoding"]}" if abcs[db]["encoding"]
	      `dropdb -U "#{abcs[db]["username"]}" #{abcs[db]["database"]}`
	      `createdb #{enc_option} -U "#{abcs[db]["username"]}" #{abcs[db]["database"]}`
	    when "sqlite","sqlite3"
	      dbfile = abcs[db]["database"] || abcs[db]["dbfile"]
	      File.delete(dbfile) if File.exist?(dbfile)
	    when "sqlserver"
	      dropfkscript = "#{abcs[db]["host"]}.#{abcs[db]["database"]}.DP1".gsub(/\\/,'-')
	      `osql -E -S #{abcs[db]["host"]} -d #{abcs[db]["database"]} -i db\\#{dropfkscript}`
	      `osql -E -S #{abcs[db]["host"]} -d #{abcs[db]["database"]} -i db\\#{RAILS_ENV}_structure.sql`
	    when "oci"
	      ActiveRecord::Base.establish_connection(db.to_sym)
	      ActiveRecord::Base.connection.structure_drop.split(";\n\n").each do |ddl|
	        ActiveRecord::Base.connection.execute(ddl)
	      end
	    else
	      raise "Task not supported by '#{abcs[db]["adapter"]}'"
	  end
	end
end

desc "Start Application"
task :start do
  system "ruby script/server"
end

Unit Test Helper for Ruby on Rails

This is a helpful file to include along with the standard test_helper.rb file to allow you to test the most basic functionality typically employed by the basic ActiveRecord Model.

ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
class Test::Unit::TestCase

  def unit_create(model,options)
    pre_count = model.count
    @o = model.new(options)
    assert @o.save
    assert_equal pre_count + 1, model.count
    assert_kind_of model, @o
  end
  
  def unit_destroy(model,id)
    pre_count = model.count
    @o = model.find(id)
    assert @o.destroy
	assert_equal pre_count - 1, model.count
	
    assert_raise(ActiveRecord::RecordNotFound) { model.find(id) }
  end
  
  def unit_update(model,id,value_hash)
    assert @o = model.find(id), "cannot test update because record was not found"
    value_hash.each do |key,value|
      @o[key] = value
    end
    assert @o.save, "could not update object, failed to save"
    @o.reload
    value_hash.each do |key,value|
      assert_equal @o[key], value, "after update the database does not contain the new values."
    end
  end
  
  def unit_protect_update_against_duplicate_records(original_record,record_to_update,*attributes)
    attributes.each do |attribute|
      record_to_update[attribute] = original_record [attribute]
    end
    assert !record_to_update.save, "the application updated the group even though it contained duplicate information on unique fields"
    attributes.each do |attribute|
      assert record_to_update.errors.on( attribute), "the application should have contained an error on field '#{attribute}'"
    end
  end
  
end



----------------------
Usage

require File.dirname(__FILE__) + '/../test_helper'
require File.dirname(__FILE__) + '/../test_unit_helper'
class AssetTest < Test::Unit::TestCase
  fixtures :assets,  :projects

  test_required_attributes Asset,'cannot be blank', :name
  
  def setup
    @model = Asset
    @asset_one = assets(:asset_2)
	@asset_two = assets(:asset_3)
    
	@new_obj = {
		:status => 1,
  		:iteration_id => 1,
  		:name => 'Stella',
		:description => 'shot of the amazing 6502'
      }
  end
  
  def test_create_asset
    unit_create @model,@new_obj 
  end
  
  def test_destroy_asset
    unit_destroy @model, @model.find(:first).id
  end
  
  def test_update_asset
    @id = @model.find(:first).id
    @new_values = {
     	:status=> 1,
 		:name=> 'orb.jpg'
    }
    unit_update @model, @id, @new_values
  end
 
end

functional test helper to automate basic CRUD functions

This is a funcitonal test helper, which can be used to create methods on the fly to iterate through your controller methods and test for validations, url parameters and expected responses. It keeps the tests from getting as cluttered.
#expects a format like this:
	#test_required_attributes_in_controller User,
  	#					{:params=>{:id=>1,:user=>{}},:session=>{:user=>{}}},
	#					[:create, :update],
	#					:first_name, :last_name, :username, :email_address, :password

    def test_required_attributes_in_controller( model, options, actions,*required_fields )
    	
		sym = model.to_s.downcase.to_sym
		for field in required_fields
      		options[:params][sym][field] = ''
    	end
		
      	actions.each do |action|
        	self.class_eval do
          		define_method("test_#{action}_method_requires_fields") do
            		assert_nothing_raised do
						post action, options[:params],options[:session]
					end
            		for field in required_fields
      					assert !assigns(sym).errors[field].empty? unless options[:params][sym][field] == ''
    				end
    				assert !assigns.empty?,"This method requires specific parameters, yet no errors were created with them missing"
          		end
        	end
      	end
	end
	
	  #Expects format like this: 
	  #   test_required_unique_attributes_in_controller User,
	  #							{:params=>{:id=>1,:user=>{}},:session=>{:user=>{}}},
	  #							[:create, :update],
	  #							:username, :email_address
	  #
		
    def test_required_unique_attributes_in_controller( model, options, actions,*required_fields )
    	sym = model.to_s.downcase.to_sym
		for field in required_fields
      		options[:params][sym][field] = ''
    	end
		
      	actions.each do |action|
        	self.class_eval do
          		define_method("test_#{action}_method_requires_unique_fields") do
            		assert_nothing_raised do
						post action, options[:params],options[:session]
					end
            		for field in required_fields
      					assert !assigns(sym).errors[field].empty? unless options[:params][sym][field] == ''
    				end
    				assert !assigns.empty?,"This method fails without unique parameters, yet no errors were created"
          		end
        	end
      	end
    end
	
	#Expects format like this:
	# test_required_url_parameters_in_controller 
	#                                           User,
	#                                           {:params=>{},:session=>{:user=>{}}},
	#                                           :edit, :destroy, :show, :update	
	
    def test_required_url_parameters_in_controller(model, options, *actions)
      sym = model.to_s.downcase.to_sym
      actions.each do |action|
        self.class_eval do
          define_method("test_#{action}_method_requires_url_parameters") do
            post action, options[:params],options[:session]
            assert_response :redirect
            assert_nil assigns(sym),"This method requires a url parameter, yet the controller still created an object."
          end
        end
      end
    end
	
  end
« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS