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

Remco van 't Veer http://blog.remvee.net

« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS 

Simple cacher module for Rails

Illustration of a simple cacher module for Rails.

# lib/cacher.rb
module Cacher
  STORE = {}
  
  def cache(*args)
    STORE[args.inspect] ||= yield
  end

  def flush!
    STORE.clear
  end
  module_function :flush!
end

# app/models/person.rb
class Person < AR::Base
  include Cacher

  def finger
    cache(:finger, email) do
      `finger #{email}`
    end
  end
end

# app/controller/application.rb
class ApplicationController < AC::Base
  after_filter { Cacher.flush! }
end

Persistent Rails cookie session

Session cookies, the Rails-2 kind, are transient because that's safer. In some applications safety isn't important. The following makes the session cookies persist for a year.

class ApplicationController < ActionController::Base
  before_filter :update_session_expiration_date

private
  def update_session_expiration_date
    unless ActionController::Base.session_options[:session_expires]
      ActionController::Base.session_options[:session_expires] = 1.year.from_now
    end
  end
end

load all fixtures

In some test cases I need all my fixtures to be loaded. To make this easier, add the following to test/test_helper.rb:

class Test::Unit::TestCase
  def self.all_fixtures
    Dir[File.dirname(__FILE__) + "/fixtures/*.yml"].each do |f|
      fixtures File.basename(f, '.yml')
    end
  end

  ..
end


and in your tests use it as follows:

class FooTest < Test::Unit::TestCase
  all_fixtures

  ..
end


Happy testing!

Disable protected attributes in ActiveRecordHelper forms

To make the form method in ActiveRecordHelper disable protected attribute, place the following in your application_help.rb:

def attr_protected?(record, column)
  o = instance_variable_get("@#{record}")
  o && o.class.protected_attributes &&
      o.class.protected_attributes.include?(column.name.to_sym)
end

def default_input_block
  Proc.new { |record, column|
    options = attr_protected?(record, column) ? {:disabled => true} : {}
    <<-"end_html" 
      <p>
        <label for="#{record}_#{column.name}">#{column.human_name}</label>
        <br />
        #{input(record, column.name, options)}
      </p>
    end_html
  }
end


And mark some attributes protected, for example:

class Item < ActiveRecord::Base
  attr_protected :created_at
end


The created_at attribute will be rendered but won't be editable. This will work for "dynamic scaffolds" too!

give focus to first input field or textarea on page

Place the following in your application.js file and make sure your layout includes "javascript_include_tag :defaults".
Event.observe(window, 'load', function() {
  var e = $A(document.getElementsByTagName('*')).find(function(e) {
    return (e.tagName.toUpperCase() == 'INPUT' && (e.type == 'text' || e.type == 'password'))
        || e.tagName.toUpperCase() == 'TEXTAREA' || e.tagName.toUpperCase() == 'SELECT';
  });
  if (e) e.focus();
});

non persistent ActiveRecord

# = ActiveForm - non persistent ActiveRecord
#
# Simple base class to make AR objects without a corresponding database
# table.  These objects can still use AR validations but can't be saved
# to the database.  Use the +valid?+ method to validate.
#
# == Example
#
#   class FeedbackForm < ActiveForm
#     column :email
#     column :message
#     validates_presence_of :email, :message
#   end
#
class ActiveForm < ActiveRecord::Base
  def self.columns() @columns ||= []; end # :nodoc:
  
  # Define an attribute, takes the same arguments as
  # ActiveRecord::ConnectionAdapters::Column.new only in a
  # slightly different order.
  def self.column(name, sql_type = nil, default = nil, null = true)
    columns << ActiveRecord::ConnectionAdapters::Column.new(
        name.to_s, default, sql_type.to_s, null)
  end
end

url and xml encode to fool naive web spiders

Encode all characters to XML entities:

  def xml_encode(text)
    text.unpack('c*').map{|c|"&\##{c};"}.join
  end


Encode all characters to %00%00.. url ecoding:

  def url_encode(text)
    text.split('').map{|c|"%#{c.unpack('H2')}"}.join
  end


The following:

  <a href="<%= xml_encode("mailto:" + url_encode("somebody@somewhere.net")) %>">mail somebody</a>


yields:

  <a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;&#37;&#55;&#51;&#37;&#54;&#102;&#37;&#54;&#100;&#37;&#54;&#53;&#37;&#54;&#50;&#37;&#54;&#102;&#37;&#54;&#52;&#37;&#55;&#57;&#37;&#52;&#48;&#37;&#55;&#51;&#37;&#54;&#102;&#37;&#54;&#100;&#37;&#54;&#53;&#37;&#55;&#55;&#37;&#54;&#56;&#37;&#54;&#53;&#37;&#55;&#50;&#37;&#54;&#53;&#37;&#50;&#101;&#37;&#54;&#101;&#37;&#54;&#53;&#37;&#55;&#52;">mail somebody</a>


which works fine in a browser.
« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS