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.

   1  
   2  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.
*/
   1  
   2  function colorize(c:Number,mc:MovieClip){
   3    var tf:Transform = new Transform(mc);
   4    var color_tf:ColorTransform = new ColorTransform();
   5    color_tf.rgb = c;
   6    tf.colorTransform = color_tf;
   7  };

Application version number and cool codename based on subversion number

// description of your code here

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

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.

   1  
   2  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:

   1  
   2  if @logged_in_client
   3    page.replace_html "message", :partial => 'shared/bad_login'
   4  else
   5    page.redirect_to "whatever you want here"
   6  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

   1  
   2  render :update do |page|
   3    if @logged_in_client
   4      page.replace_html "message", :partial => 'shared/bad_login'
   5    else
   6      page.redirect_to "whatever you want here"
   7    end
   8  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:
   1  
   2  # view
   3  <%= form_tag :controller => :posts, :action => create %>
   4   <%= text_field("post", "title", "size" => 20) %>
   5   <%= text_field("user", "email", "size" => 20) %>
   6  <%= end_form_tag %>

   1  
   2  # posts_controller
   3  class PostsController < ApplicationController
   4   def create
   5     @post = Post.create(params[:post])
   6     @user = User.create(params[:user])
   7     @post.users << @user
   8   end
   9  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:

   1  
   2  def file=(new_file)
   3   new_file.rewind
   4   image = Magick::Image::from_blob(new_file.read).first
   5  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"


   1  
   2  task :start_fresh => :environment do
   3       Rake::Task[:clear_logs].invoke
   4       puts 'clearing logs                           ...done'
   5       
   6       Rake::Task[:recreate_database].invoke
   7       puts 'recreate test database                  ...done'
   8       puts 'recreate development database           ...done'
   9       
  10       ActiveRecord::Base.establish_connection(:development)
  11       Rake::Task[:migrate].invoke
  12       puts 'migrate the development database        ...done'
  13       
  14       Rake::Task[:load_fixtures_to_development].invoke
  15       puts 'load fixtures into development database ...done'
  16       
  17       ActiveRecord::Base.establish_connection(:test)
  18       Rake::Task[:prepare_test_database].invoke
  19       puts 'clone the development structure to test ...done'
  20  end
  21  
  22  desc "Load fixtures data into the test database"
  23  task :load_fixtures_to_development => :environment do
  24    require 'active_record/fixtures'
  25    ActiveRecord::Base.establish_connection(:development)
  26    Dir.glob(File.join(RAILS_ROOT, 'test', 'fixtures', '*.{yml,csv}')).each do |fixture_file|
  27      Fixtures.create_fixtures('test/fixtures', File.basename(fixture_file, '.*'))
  28    end
  29  end
  30  
  31  task :recreate_database => :environment do
  32    abcs = ActiveRecord::Base.configurations
  33  	tdb = Array.new
  34    tdb << 'test'
  35    tdb << 'development'
  36  
  37   	for db in tdb
  38  	  case abcs[db]["adapter"]
  39  	    when "mysql"
  40  	      ActiveRecord::Base.establish_connection(db.to_sym)
  41  	      ActiveRecord::Base.connection.recreate_database(abcs[db]["database"])
  42  	    when "postgresql"
  43  	      ENV['PGHOST']     = abcs[db]["host"] if abcs[db]["host"]
  44  	      ENV['PGPORT']     = abcs[db]["port"].to_s if abcs[db]["port"]
  45  	      ENV['PGPASSWORD'] = abcs[db]["password"].to_s if abcs[db]["password"]
  46  	      enc_option = "-E #{abcs[db]["encoding"]}" if abcs[db]["encoding"]
  47  	      `dropdb -U "#{abcs[db]["username"]}" #{abcs[db]["database"]}`
  48  	      `createdb #{enc_option} -U "#{abcs[db]["username"]}" #{abcs[db]["database"]}`
  49  	    when "sqlite","sqlite3"
  50  	      dbfile = abcs[db]["database"] || abcs[db]["dbfile"]
  51  	      File.delete(dbfile) if File.exist?(dbfile)
  52  	    when "sqlserver"
  53  	      dropfkscript = "#{abcs[db]["host"]}.#{abcs[db]["database"]}.DP1".gsub(/\\/,'-')
  54  	      `osql -E -S #{abcs[db]["host"]} -d #{abcs[db]["database"]} -i db\\#{dropfkscript}`
  55  	      `osql -E -S #{abcs[db]["host"]} -d #{abcs[db]["database"]} -i db\\#{RAILS_ENV}_structure.sql`
  56  	    when "oci"
  57  	      ActiveRecord::Base.establish_connection(db.to_sym)
  58  	      ActiveRecord::Base.connection.structure_drop.split(";\n\n").each do |ddl|
  59  	        ActiveRecord::Base.connection.execute(ddl)
  60  	      end
  61  	    else
  62  	      raise "Task not supported by '#{abcs[db]["adapter"]}'"
  63  	  end
  64  	end
  65  end
  66  
  67  desc "Start Application"
  68  task :start do
  69    system "ruby script/server"
  70  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.

   1  
   2  ENV["RAILS_ENV"] = "test"
   3  require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
   4  require 'test_help'
   5  class Test::Unit::TestCase
   6  
   7    def unit_create(model,options)
   8      pre_count = model.count
   9      @o = model.new(options)
  10      assert @o.save
  11      assert_equal pre_count + 1, model.count
  12      assert_kind_of model, @o
  13    end
  14    
  15    def unit_destroy(model,id)
  16      pre_count = model.count
  17      @o = model.find(id)
  18      assert @o.destroy
  19  	assert_equal pre_count - 1, model.count
  20  	
  21      assert_raise(ActiveRecord::RecordNotFound) { model.find(id) }
  22    end
  23    
  24    def unit_update(model,id,value_hash)
  25      assert @o = model.find(id), "cannot test update because record was not found"
  26      value_hash.each do |key,value|
  27        @o[key] = value
  28      end
  29      assert @o.save, "could not update object, failed to save"
  30      @o.reload
  31      value_hash.each do |key,value|
  32        assert_equal @o[key], value, "after update the database does not contain the new values."
  33      end
  34    end
  35    
  36    def unit_protect_update_against_duplicate_records(original_record,record_to_update,*attributes)
  37      attributes.each do |attribute|
  38        record_to_update[attribute] = original_record [attribute]
  39      end
  40      assert !record_to_update.save, "the application updated the group even though it contained duplicate information on unique fields"
  41      attributes.each do |attribute|
  42        assert record_to_update.errors.on( attribute), "the application should have contained an error on field '#{attribute}'"
  43      end
  44    end
  45    
  46  end
  47  
  48  
  49  
  50  ----------------------
  51  Usage
  52  
  53  require File.dirname(__FILE__) + '/../test_helper'
  54  require File.dirname(__FILE__) + '/../test_unit_helper'
  55  class AssetTest < Test::Unit::TestCase
  56    fixtures :assets,  :projects
  57  
  58    test_required_attributes Asset,'cannot be blank', :name
  59    
  60    def setup
  61      @model = Asset
  62      @asset_one = assets(:asset_2)
  63  	@asset_two = assets(:asset_3)
  64      
  65  	@new_obj = {
  66  		:status => 1,
  67    		:iteration_id => 1,
  68    		:name => 'Stella',
  69  		:description => 'shot of the amazing 6502'
  70        }
  71    end
  72    
  73    def test_create_asset
  74      unit_create @model,@new_obj 
  75    end
  76    
  77    def test_destroy_asset
  78      unit_destroy @model, @model.find(:first).id
  79    end
  80    
  81    def test_update_asset
  82      @id = @model.find(:first).id
  83      @new_values = {
  84       	:status=> 1,
  85   		:name=> 'orb.jpg'
  86      }
  87      unit_update @model, @id, @new_values
  88    end
  89   
  90  end
  91  

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.
   1  
   2  #expects a format like this:
   3  	#test_required_attributes_in_controller User,
   4    	#					{:params=>{:id=>1,:user=>{}},:session=>{:user=>{}}},
   5  	#					[:create, :update],
   6  	#					:first_name, :last_name, :username, :email_address, :password
   7  
   8      def test_required_attributes_in_controller( model, options, actions,*required_fields )
   9      	
  10  		sym = model.to_s.downcase.to_sym
  11  		for field in required_fields
  12        		options[:params][sym][field] = ''
  13      	end
  14  		
  15        	actions.each do |action|
  16          	self.class_eval do
  17            		define_method("test_#{action}_method_requires_fields") do
  18              		assert_nothing_raised do
  19  						post action, options[:params],options[:session]
  20  					end
  21              		for field in required_fields
  22        					assert !assigns(sym).errors[field].empty? unless options[:params][sym][field] == ''
  23      				end
  24      				assert !assigns.empty?,"This method requires specific parameters, yet no errors were created with them missing"
  25            		end
  26          	end
  27        	end
  28  	end
  29  	
  30  	  #Expects format like this: 
  31  	  #   test_required_unique_attributes_in_controller User,
  32  	  #							{:params=>{:id=>1,:user=>{}},:session=>{:user=>{}}},
  33  	  #							[:create, :update],
  34  	  #							:username, :email_address
  35  	  #
  36  		
  37      def test_required_unique_attributes_in_controller( model, options, actions,*required_fields )
  38      	sym = model.to_s.downcase.to_sym
  39  		for field in required_fields
  40        		options[:params][sym][field] = ''
  41      	end
  42  		
  43        	actions.each do |action|
  44          	self.class_eval do
  45            		define_method("test_#{action}_method_requires_unique_fields") do
  46              		assert_nothing_raised do
  47  						post action, options[:params],options[:session]
  48  					end
  49              		for field in required_fields
  50        					assert !assigns(sym).errors[field].empty? unless options[:params][sym][field] == ''
  51      				end
  52      				assert !assigns.empty?,"This method fails without unique parameters, yet no errors were created"
  53            		end
  54          	end
  55        	end
  56      end
  57  	
  58  	#Expects format like this:
  59  	# test_required_url_parameters_in_controller 
  60  	#                                           User,
  61  	#                                           {:params=>{},:session=>{:user=>{}}},
  62  	#                                           :edit, :destroy, :show, :update	
  63  	
  64      def test_required_url_parameters_in_controller(model, options, *actions)
  65        sym = model.to_s.downcase.to_sym
  66        actions.each do |action|
  67          self.class_eval do
  68            define_method("test_#{action}_method_requires_url_parameters") do
  69              post action, options[:params],options[:session]
  70              assert_response :redirect
  71              assert_nil assigns(sym),"This method requires a url parameter, yet the controller still created an object."
  72            end
  73          end
  74        end
  75      end
  76  	
  77    end
« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS