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 31-40 of 463 total

record grouping

   1  
   2  @users = User.find(
   3    :all, 
   4    :select => "MONTH(created_at) as month, YEAR(created_at) as year, COUNT(*) AS records",
   5    :conditions => ["admin = 0'"], 
   6    :group => "year, month")
   7  
   8  <% for @user in @users %>
   9    <%=@user.month%>
  10    <%=@user.year%>
  11    <%=@user.records%>
  12  <% end %>

date_select conversion

function to convert a value from a date_select into a more sql-friendly value

   1  
   2  <%=date_select(:date,'',:start_year => 1950,:include_blank => false, :default => { :year => '1970' })%>
   3  
   4  def convert_date(obj) 
   5    return “#{obj[(1i)]}-#{obj[(2i)]}-#{obj[(3i)]}
   6  end

ISO 8601 date format for microformats

Strftime to get the ISO 8601 (see RFC 3339) full date format for an hEvent Microformat. Doubtless usable in other situations.

   1  
   2  strftime('%Y-%m-%dT%H:%M:%S%z');


If you're in Ruby, you can access this the quick way with:

   1  
   2  $ irb
   3  >> require 'time'
   4  => true
   5  >> Time.now.iso8601
   6  => "2008-07-09T16:13:30+12:00"


Rails example:

   1  
   2  <abbr class="dtstart" title="<%= event.start_date.iso8601"><%= event.start_date.to_s(:long) %></abbr>

Finding recent data in database

This shows how to find recent data from last hour, day, week, month, whatever

   1  
   2  class Post < ActiveRecord::Base
   3    def self.find_latest(time = nil)
   4      r = %w( hour day week month year )
   5      if r.include?(time)
   6        self.find :all, :conditions => ['created_at > ?', 1.send(time).ago]
   7      else
   8        self.find :all
   9      end
  10    end
  11  end
  12  
  13  Post.find_latest('day')
  14  Post.find_latest('week')
  15  Post.find_latest('year')

Simple cacher module for Rails

Illustration of a simple cacher module for Rails.

   1  
   2  # lib/cacher.rb
   3  module Cacher
   4    STORE = {}
   5    
   6    def cache(*args)
   7      STORE[args.inspect] ||= yield
   8    end
   9  
  10    def flush!
  11      STORE.clear
  12    end
  13    module_function :flush!
  14  end
  15  
  16  # app/models/person.rb
  17  class Person < AR::Base
  18    include Cacher
  19  
  20    def finger
  21      cache(:finger, email) do
  22        `finger #{email}`
  23      end
  24    end
  25  end
  26  
  27  # app/controller/application.rb
  28  class ApplicationController < AC::Base
  29    after_filter { Cacher.flush! }
  30  end

Default Values for Blank Values OO-style

In Ruby the idiom || can be used to provide a default value if something is nil. This can't be done with blank since an empty string is not nil and will short-circuit the || operator, leaving most of us to to do something like "name.blank? ? 'John Doe' : name". Here's a way to do this OO-style:

   1  
   2  class Object  
   3    def or_if_blank(value)  
   4      self.respond_to?(:blank) && self.blank? ? value : self  
   5    end  
   6  end
   7  
   8  name.or_if_blank("John Doe")

Rails Notice/Warning Flash Message

Somewhat lame, but handy nonetheless.

   1  
   2  <% if flash[:warning] or flash[:notice] %>
   3    <div id="notice" <% if flash[:warning] %>class="warning"<% end %>>
   4      <%= flash[:warning] || flash[:notice] %>
   5    </div>
   6    <script type="text/javascript">
   7      setTimeout("new Effect.Fade('notice');", 15000)
   8    </script>
   9  <% end %>

Custom validation with rails: words with more than 26 characters

This goes in whatever model you're validating. "Subject" can be any of the symbols in your model and doesn't need the : in front of it.
   1  
   2  def validate
   3  	if subject.split.any?{|w| w.length > 26}
   4  		errors.add(:subject, "cannot have words more than 26 consecutive characters")
   5  	end
   6  end

rake task to rename views to rails 2.0 format

// This task will rename your files to the rails 2.0 format, using git mv. Add it to /lib/tasks/rails.rake

   1  
   2  namespace 'views' do
   3    desc 'Renames all .rhtml views to .html.erb, .rjs to .js.rjs, .rxml to .xml.builder, and .haml to .html.haml'
   4    task 'rename' do
   5      Dir.glob('app/views/**/[^_]*.rhtml').each do |file|
   6        puts `git mv #{file} #{file.gsub(/\.rhtml$/, '.html.erb')}`
   7      end
   8  
   9      Dir.glob('app/views/**/[^_]*.rxml').each do |file|
  10        puts `git mv #{file} #{file.gsub(/\.rxml$/, '.xml.builder')}`
  11      end
  12  
  13      Dir.glob('app/views/**/[^_]*.rjs').each do |file|
  14        puts `git mv #{file} #{file.gsub(/\.rjs$/, '.js.rjs')}`
  15      end
  16      Dir.glob('app/views/**/[^_]*.haml').each do |file|
  17        puts `git mv #{file} #{file.gsub(/\.haml$/, '.html.haml')}`
  18      end
  19    end
  20  end

Rails Date Formats

// cribbed from http://wiki.rubyonrails.org/rails/pages/HowToDefineYourOwnDateFormat

   1  
   2  my_formats = {
   3    :my_format_1 => '%l %p, %b %d, %Y',
   4    :my_format_2  => '%l:%M %p, %B %d, %Y'
   5  }
   6  
   7  ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(my_formats)
   8  ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(my_formats)
« Newer Snippets
Older Snippets »
Showing 31-40 of 463 total