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

Matt Scilipoti

« Newer Snippets
Older Snippets »
Showing 21-30 of 46 total

RoR Date Formats

From http://hittingthebuffers.com/2006/08/11/date-formats/:
August 11, 2006
Date formats

Here's a handy date related tip I just read when I was looking around for ways to make an RSS feed valid.

If you go to a command line and run script/console, then type ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS it displays a hash containing default date formatting which can be used with to_s() like this:
      xml.pubDate(article.created_at.to_s(:rfc822))


It's also possible to add additional formats to the end of application.rb:
      ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
        :default => "%m/%d/%Y",
        :date_time12 => "%m/%d/%Y %I:%M%p",
        :date_time24 => "%m/%d/%Y %H:%M"
      )


From Comments (as of 2006.08.14):
2.
My personal faves:
      :iso_8601_date_only => ‘%Y-%m-%d’,
      :iso_8601_time_only => ‘%H:%M:%S%z’

Comment by Todd Sayre — August 12, 2006 @ 3:19 pm

Rake Freezes Rails

Stolen from: ZenSpider: http://blog.zenspider.com/archives/2006/08/upgrade_rails_n.html

If you prefer to freeze your rails checkout. I recommend stealing this rule:
namespace :rails do
  namespace :freeze do
    desc "Lock to a specific rails version. Defaults to 1.1.5 or specify with RELEASE=x.y.z"
    task :version do
      rel = ENV['RELEASE'] || '1.1.5'
      tag = 'rel_' + rel.split(/[.-]/).join('-')
      rails_svn = "http://dev.rubyonrails.org/svn/rails/tags/#{tag}"

      puts "Freezing to #{tag} using #{rails_svn}"
      sh "type svn"
      
      dir = 'vendor/rails'
      rm_rf dir
      mkdir_p dir
      for framework in %w( railties actionpack activerecord actionmailer activesupport actionwebservice )
        checkout = "#{dir}/#{framework}"
        sh "svn export #{rails_svn}/#{framework} #{checkout}"
        unless test ?d, checkout then
          puts "ERROR: checkout missing: #{checkout}"
          exit 1
        end
      end
    end
  end
end

and running:
rake rails:freeze:version

It'll default to 1.1.5 or you can specify the tagged version you want using RELEASE=x.y.z.

Rake's missing_method found!

From http://newbieonrails.topfunky.com/articles/2006/07/28/foscon-and-living-dangerously-with-rake:
Updated from : http://mentalized.net/journal/2006/07/28/run_specific_tests_via_rake/

If you define a rule with an empty string, you can catch any task that hasn’t been defined elsewhere. This makes it easy to dynamically create rake tasks. Essentially, this is method_missing for rake!
rule "" do |t|
  t.name 
  # ... do something with the name of the task  
end

I experimented by writing a rule that will take a task with the format of controllername_testname and automatically run a single test from the relevant functional or unit test.
##
# Run a single test in Rails.
#
#   rake blogs_list
#   => Runs test_list for BlogsController (functional test)
#
#   rake blog_create
#   => Runs test_create for BlogTest (unit test)

rule "" do |t|
  if /(.*)_([^.]+)$/.match(t.name)
    file_name = $1
    test_name = $2
    if File.exist?("test/unit/#{file_name}_test.rb")
      file_name = "unit/#{file_name}_test.rb" 
    elsif File.exist?("test/functional/#{file_name}_controller_test.rb")
      file_name = "functional/#{file_name}_controller_test.rb" 
    else
      raise "No file found for #{file_name}" 
    end
    sh "ruby -Ilib:test test/#{file_name} -n /^test_#{test_name}/" 
  end
end


Update from : http://mentalized.net/journal/2006/07/28/run_specific_tests_via_rake/
This modified version uses a different syntax (rake test:foo:bar instead rake foo_bar) and regex matching for test names.

Usage
$ rake test:blog
=> Runs the full BlogTest unit test

$ rake test:blog:create
=> Runs the tests matching /create/ in the BlogTest unit test

$ rake test:blog_controller
=> Runs all tests in the BlogControllerTest functional test

$ rake test:blog_controller:create
=> Runs the tests matching /create/ in the BlogControllerTest functional test	


Code
# Run specific tests or test files
# 
# rake test:blog
# => Runs the full BlogTest unit test
# 
# rake test:blog:create
# => Runs the tests matching /create/ in the BlogTest unit test
# 
# rake test:blog_controller
# => Runs all tests in the BlogControllerTest functional test
# 
# rake test:blog_controller
# => Runs the tests matching /create/ in the BlogControllerTest functional test	
rule "" do |t|
  # test:file:method
  if /test:(.*)(:([^.]+))?$/.match(t.name)
    arguments = t.name.split(":")[1..-1]
    file_name = arguments.first
    test_name = arguments[1..-1] 
    
    if File.exist?("test/unit/#{file_name}_test.rb")
      run_file_name = "unit/#{file_name}_test.rb" 
    elsif File.exist?("test/functional/#{file_name}_test.rb")
      run_file_name = "functional/#{file_name}_test.rb" 
    end
    
    sh "ruby -Ilib:test test/#{run_file_name} -n /#{test_name}/" 
  end
end

Do whatever you want with the above code, it’s yours now.

ClassLibrary Projects and App.config

This snippet comes from Jamie Cansdale at TestDriven.net (http://weblogs.asp.net/nunitaddin/archive/2006/06/07/ClassLibrary-Projects-and-App.config.aspx)

In Visual Studio .NET 2003 if you want you unit tests to use an app config file you need to ensure a config file exists with the same path as your test assembly but ending with '.config'. Life has improved a bit with Visual Studio 2005 as it will automatically copy any 'App.config' file to the correct place even for ClassLibrary projects. You can achieve the same affect in VS2003 by using the following post-build event:
copy "$(ProjectDir)App.config" "$(TargetPath).config"

DRY RAILS database.yml config file

From http://blog.bleything.net/articles/2006/06/27/dry-out-your-database-yml:



login: &login
  adapter: mysql
  username: username
  password: password
  host: mysql.example.com

development:
  <<: *login
  database: app_dev

test:
  <<: *login
  database: app_test

production:
  <<: *login
  database: app_prod

ActiveRecord and SQL Server

From http://www.softiesonrails.com/articles/2006/06/28/activerecord-with-sqlserver-without-rails:

Ensure you done the initial setup for SQL Server and ActiveRecord (ADO.rb).

require 'rubygems'
require_gem 'activerecord'

ActiveRecord::Base.establish_connection(
  :adapter  => "sqlserver",
  :dsn => "instance_name_goes_here",
  :host => "machine_name\\instance_name",
  :database =>  "db_name",
  :username =>  "my_username",
  :password =>  "my_password"
)

class MsSqlTable < ActiveRecord::Base
  def method_missing(method, *args)
    respond_to?(method) ? super : send(method.to_s.camelize, *args)
  end
end

class Item < MsSqlTable
  set_primary_key "sku"
  set_table_name "item"
end


I'll walk through it real quick:

1. The :dsn needs to be your SQL Server instance name
2. The :host needs to a path like "myserver\myinstance", even though you've already specified the instance name in the :dsn parameter
3. The rest of the settings should be obvious. If your password is blank, don't specify :password at all.
4. Our legacy column names are things like OldDescription. So I created an intermediate base class that would provide ruby-like aliases. Now I can use item.old_description instead if I want to.
5. Finally, I declare one class for each table I want to access. I have to set the primary key and table name manually, since our tables don't correspond to any Rails conventions.

I saved this script as legacy.rb, and then fired up irb from that directory:
irb> load 'legacy.rb'
=> true
irb> Item.find("191191").old_description
=> "Table In A Bag"
irb>

Hash Tricks

From: http://blog.caboo.se/articles/2006/06/11/stupid-hash-tricks

class Hash

  # lets through the keys in the argument
  # >> {:one => 1, :two => 2, :three => 3}.pass(:one)
  # => {:one=>1}
  def pass(*keys)
    tmp = self.clone
    tmp.delete_if {|k,v| ! keys.include?(k) }
    tmp
  end

  # blocks the keys in the arguments
  # >> {:one => 1, :two => 2, :three => 3}.block(:one)
  # => {:two=>2, :three=>3}
  def block(*keys)
    tmp = self.clone
    tmp.delete_if {|k,v| keys.include?(k) }
    tmp
  end

end


In case you don’t already see the utility of this:
def some_action
    # some script kiddie also passed in :bee, which we don't want tampered with _here_.
    @model = Model.create(params.pass(:foo, :bar))
  end

or those cases where you don’t want to let everything through and don’t want to resort to attr_protected or attr_accessible

pretty tables for rails models

From http://www.rubyinside.com/columnized-text-datasets-in-rails-71.html:
Inspired by: http://blog.caboo.se/articles/2006/06/10/pretty-tables-for-ruby-objects

It gives a MySQL-command-line-client style textual view of data stored in your Rails database. The syntax worked like this:
Something.find(:all, :conditions => ‘whatever‘).pretty_print


class Array

  protected

    def columnized_row(fields, sized)
      r = []
      fields.each_with_index do |f, i|
        r << sprintf(�%0-#{sized[i]}s“, f.to_s.gsub(/\n|\r/, ‘’).slice(0, sized[i]))
      end
      r.join(’ | ‘)
    end

  public

  def columnized(options = {})
    sized = {}
    self.each do |row|
      row.attributes.values.each_with_index do |value, i|
        sized[i] = [sized[i].to_i, row.attributes.keys[i].length, value.to_s.length].max
        sized[i] = [options[:max_width], sized[i].to_i].min if options[:max_width]
      end
    end

    table = []
    table << header = columnized_row(self.first.attributes.keys, sized)
    table << header.gsub(/./, ‘-‘)
    self.each { |row| table << columnized_row(row.attributes.values, sized) }
    table.join(�\n“)
  end
end

class ActiveRecord::Base
  def columnized(options = {})
    [*self].columnized(options)
  end
end



To use:
>> puts Post.find(:all).columnized(:max_width => 10)
updated_at | title      | private | url | thumb      | metadata | movie      | id  | views | content    | user_id | created_at
——————————————————————————————————————————
Wed May 31 | tetwer     | 0       |     |            |          |            | 909 | 0     | video:xyzz | 1       | Wed May 31
Wed May 31 | bbbb       | 0       |     |            |          |            | 1   | 15    | // descrip | 1       | Tue May 23
Wed May 31 | cxzcxzx    | 0       |     |            |          |            | 906 | 19    | // descrip | 1       | Tue May 23
Wed May 31 | jklklkl;   | 0       |     |            |          |            | 907 | 35    | // descrip | 1       | Tue May 23


If you want to use it with your project, put the code into lib/columnized.rb, use require ‘columnized’, and you’re ready to roll. Unlike courtenay’s version, mine only supports max_width, but I didn’t consider changing the column separator too important.

Adding Comments to the IIS Log

Adding Comments to the IIS Log

A simple way to provide more information to the IIS log files is to append it yourself with the Response.AppendToLog method. By using Session and Application events you can place keywords that you can later use when search the files. You might even be able to train some of the analysis programs to understand you keywords and hopefully provide more meaningful stats.

    Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires at the beginning of each request
        Response.AppendToLog("test")
    End Sub

There are some restrictions, however. Since the data you provide is appended to the URI Query portion of the log file, you are limited to 80 characters. In addition, you cannot use commas since they are a delimiter for some of the log file formats. Also, if you anticipate that there will be other querystring elements you may want to prepend your string with an ampersand.

----

From http://psacake.com/web/ht.asp:
While trying to come up with new ways to record things that are happening on my Web server, I came across the Response Objects AppendToLog Method. This method allows you to write directly to the IIS Log File using only one line of code. This has come in handy for error trapping and troubleshooting. The following is a piece of sample code that writes a single entry to the log file:

     Response.AppendToLog "Database Being Accessed"


The above line would write the following to your IIS log file:

127.0.0.1, -, 01/01/00, 12:00:34, W3SVC1,WEBSERVER,
127.0.0.1, 161342, 485, 228, 200, 0, get, /somefile.asp, Database Being Accessed

Remember that the IIS log file is a comma-delimited file, and you should try to avoid using commas in the data string you pass to the log file.

----

Rant From http://sqljunkies.com/WebLog/ktegels/archive/2004/01/21/795.aspx:
Since we already have IIS logging turned on, it just made sense to log to that. When we needed to harvest the data for making test case, we could just parse the logs. So, I turned a hopeful eye towards HttpResponse.AppendToLog (which is available to us in ASP.NET as Response.AppendToLog) thinking it might at least be a Copper Bullet. It works, but, where it decides to put your entry in the log could be a problem. Data written to these logs using this method is inserted where the cs-uri-query field would be rather than at the end of the record.

I suppose that this behavior makes sense if you stop to consider that the cs-uri-query field should be blank, null or otherwise meaningless for POSTs (normally). Of course, the de facto RFC doesn't say that, so IIS can get by with it.

Unless of course, you're GETting, not POSTing. But in those cases, you really don't need this trick anyway.

My whole problem with this that the "Extended Log File Format" does offer a more proper place to put this data: x-Comment. If X-Comment appeared at the end of a line, it likely wouldn't break most log parsers, and we'd have a sensible place to look for this.

Force recompile of Sql Server stored procs

This force a recompile of all stored procs, views, tables, triggers, and functions in the current database.
CHECKPOINT 
GO

DBCC DROPCLEANBUFFERS
GO

DBCC FREEPROCCACHE
GO

DECLARE @intDBID INTEGER 
SET @intDBID = DB_ID()

DBCC FLUSHPROCINDB (@intDBID)
GO


declare @procNames Table (procName varchar(255))
insert into @procNames
select name from sysObjects where xtype in ('V','P','U','FN','TF','TR' ) and status > 0

--select * from @procNames

set nocount off
--3. Run each command
-- =============================================
-- Declare and using a READ_ONLY cursor
-- =============================================
DECLARE RecompilableItemsCursor CURSOR
READ_ONLY
FOR select procName from @procNames

DECLARE @RecompilableItem varchar(255)
OPEN RecompilableItemsCursor


FETCH NEXT FROM RecompilableItemsCursor INTO @RecompilableItem
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN
		DECLARE @sql varchar(300)
		select @sql = 'Exec sp_recompile ' + @RecompilableItem
		print @sql
		exec (@sql)
	END
	FETCH NEXT FROM RecompilableItemsCursor INTO @RecompilableItem
END

CLOSE RecompilableItemsCursor
DEALLOCATE RecompilableItemsCursor


GO

« Newer Snippets
Older Snippets »
Showing 21-30 of 46 total