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 21-30 of 64 total

Update selected attributes from a list

This transfers a list of selected attributes from a list (typically inside params[]) to an AR model object. More useful than attr_accessible, attr_protected et al.

class ActiveRecord::Base
  def transfer_attributes(source, *keys)
    keys.each do |key|
      self.send("#{key}=", source[key])
    end
  end
end

ActiveRecord: cache column information

// Cache the column information so that no more query will be
// sent to the server thereafter

class ActiveRecord::Base
	
	@@_cached_columns = {}
	class << self
		
		alias :old_columns :columns
		
		def columns
			return @@_cached_columns[table_name] if @@_cached_columns[table_name]
			@@_cached_columns[table_name] = old_columns
		end
		
	end
	
end

Compress your ActiveRecord sessions

Using ActiveRecordStore and your sessions are getting too big? Try this!

# in environment.rb or some file you require
require 'zlib'
CGI::Session::ActiveRecordStore::Session.class_eval {
  class << self
    def marshal_with_compression(data)
      Zlib::Deflate.deflate(marshal_without_compression(data))
    end
    def unmarshal_with_compression(data)
      unmarshal_without_compression(Zlib::Inflate.inflate(data))
    end
    alias_method_chain :marshal, :compression
    alias_method_chain :unmarshal, :compression
  end
}

# in migration
def self.up
  change_column :sessions, :data, :binary
end

def self.down
  change_column :sessions, :data, :text
end

ActiveRecord: Find blog links with futures too distant

badbloglinks = BlogLink.find(:all, :conditions => ["status='reserved' AND expires > ?", Time.now + 2.weeks])

Apply conditions to count in ActiveRecord

blog.posts.count(:conditions => "status = 'active'")

Active Record: Select specific column data

ActiveRecord works at the row (aka record) level, not the column level. That's not to say that you can't just get a single column of data back from the database, you can, but you won't have all the attributes if you do this so just keep that in mind. you'll probably want to map them to an array..
class User < ActiveRecord::Base
  def self.names
    # find all records, then map name attributes to an array
    find(:all, :select => "name").map(&:name)
  end
end

# btw..
.map(&:name)

# is shorthand for
.map { |x| x.name }

User model basics: age calculations

class User < ActiveRecord::Base
  # ...
  
  def age
    (Time.now.year - birthday.year) - (turned_older? ? 0 : 1) rescue 0
  end
 
  def next_birthday
    birthday.to_time.change(:year => (turned_older? ? 1.year.from_now : Time.now).year)
  end
 
  def turned_older?
    (birthday.to_time.change(:year => Time.now.year) <= Time.now)
  end
end

User model basics: SHA256 passwords

class User < ActiveRecord::Base
  # ...

  def password ; @password ; end
  def password=(value)
    self.password_salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
    self.password_sha  = self.encrypt_password(value)
    @password = value
  end
  
  def encrypt_password(cleartext)
    Digest::SHA256.hexdigest(cleartext + self.password_salt)
  end
  
  def self.authenticate(nickname, password)
    user = self.find_active_by_nickname(nickname)
    raise "Username or Password invalid" if user.blank? || user.encrypt_password(password) != user.password_sha
    return user
  end
end

Add a to_conditions method to ActiveRecord::Base for converting models to finder :conditions hash.

// Mixes in a to_conditions method to ActiveRecord::Base. Converts the attributes of an AR object to a
// ActiveRecord::Base#find :conditions hash. Useful for comparing AR objects, especially when looking for
// duplicates.
// E.g.
//
// if not Post.find(:all, :conditions => my_post.conditions).empty?
// puts "Duplicate found"
// end

module Bezurk #:nodoc:
  module ActiveRecord #:nodoc:
    module Extensions
      def to_conditions
        attributes.inject({}) do |hash, (name, value)|
          hash.merge(name.intern => value)
        end
      end
      alias :to_conditions_hash :to_conditions
    end
  end
end

ActiveRecord::Base.send(:include, Bezurk::ActiveRecord::Extensions)

RSS Twitter Bot

Republish an RSS feed on a twitter account. This was the source I used to run the Woot Twitter Bot before they took it over.

require 'rubygems'
require 'active_record'
require 'simple-rss'
require 'open-uri'
require 'twitter'

#twitter account to post to
twitter_email = "yourtwitteremail@bla.com"
twitter_password = "secret"

#rss feed to post
rss_url = "http://yoursite.com/index.xml"
rss_user_agent = "http://twitter.com/yourbot"

#sqlite db
path_to_sqlite_db = "/PATH/TO/db.sqlite"


ActiveRecord::Base.logger = Logger.new(STDERR)
ActiveRecord::Base.colorize_logging = false

ActiveRecord::Base.establish_connection(
    :adapter => "sqlite3",
    :dbfile  => path_to_sqlite_db
)

#uncomment this section the first time to create the table
#
#ActiveRecord::Schema.define do
#    create_table :item do |table|
#        table.column :title, :string
#        table.column :link, :string
#    end
#end

class Item < ActiveRecord::Base
  def to_s
    "#{self.title[0..(130-self.link.length)]} - #{self.link}"
  end
end

#run the beast
rss_items = SimpleRSS.parse open(rss_url ,"User-Agent" => rss_user_agent)

for item in rss_items.items
  Item.transaction do
    unless existing_item = Item.find(:all, :conditions => ["link=?", item.link]).first
      twitter ||= Twitter::Base.new(twitter_email, twitter_password)
      new_item = Item.create(:title => item.title, :link => item.link) 
      twitter.post(new_item.to_s)
    end
  end
end


Run this once with the lines uncommented to create the DB, then slap it in your crontab.
« Newer Snippets
Older Snippets »
Showing 21-30 of 64 total