Posts Tagged ‘rails’
search plugin for rails
July 10th, 2008 •
tags: rails, rails plugins, search
# USAGE EXAMPLE
# -----------------------------------------------------------
# class PostsController < ApplicationController
# restful_search do |s|
# s.model = :foo
# s.search_param_name = "search" # defaults to 'match'
# s.columns = [ 'foo.name', 'bar.state', 'baz.comment' ],
# s.joins = [ :foo => { :bar => :baz } ],
# end
#
# def index
# @posts = restful_search_results
# end
# end
# -----------------------------------------------------------
integer range collection_select form helper
July 9th, 2008 •
tags: rails, rails views
<%= f.collection_select :priority, (1..5), :to_i, :to_i %>
calling named_scope in a loop doesn’t seem to work in rails 2.1.0 ?
June 20th, 2008 •
tags: rails, rails models
# # Raises NoMethodError: undefined method `processing' # %(pending processing complete error).each do |s| # named_scope s.to_sym, # :conditions => ["state = ?", s], # :order => "priority, created_at" # end named_scope :pending, :conditions => "state = 'pending'", :order => "priority, created_at" named_scope :processing, :conditions => "state = 'processing'", :order => "priority, created_at" named_scope :complete, :conditions => "state = 'complete'", :order => "priority, created_at" named_scope :errorneous, :conditions => "state = 'error'", :order => "priority, created_at"
capistrano, thin, remote_cache, safe credentials and symlinked vendor/rails
June 12th, 2008 •
tags: capistrano, rails
set :application, "coolapp"
set :repository, "http://snusnu.info/svn/#{coolapp}/trunk/coolapp"
set :deploy_via, :remote_cache
set :deploy_to, "/u/apps/coolapp"
role :app, "snusnu.info", :primary => true
# rely on ssh-agent or the likes to serve our private key on authentication
ssh_options[:port] = 22
ssh_options[:username] = 'coolio'
ssh_options[:host_key] = "ssh-rsa"
ssh_options[:auth_methods] = %w(publickey)
# workaround for capistrano-2.3 bug
ssh_options[:keys] = %w(~/.ssh/id_dsa.snusnu.info ~/.ssh/id_rsa.snusnu.info)
# taken from Advanced Rails Recipes
desc "Watch multiple log files at the same time"
task :tail_log, :roles => :app do
stream "tail -f #{shared_path}/log/production.log"
end
# call this if 'deploy_via :remote_cache' is set
# and you want to deploy a different tag or branch
# inspired from Jonathan Weiss' explanation of the issue
# http://blog.innerewut.de/2008/3/12/remote-cache-pitfalls
task :delete_remote_cache, :roles => :app do
run "rm -rf #{shared_path}/cached-copy"
end
namespace :symlink do
task :vendor_rails, :roles => :app do
run "ln -s #{shared_path}/rails #{release_path}/vendor/rails"
end
end
after "deploy:update_code", "symlink:vendor_rails"
namespace :thin do
%w(start stop restart).each do |action|
desc "#{action.to_s.capitalize} the application's thin server(s)"
task action.to_sym, :roles => :app do
run "thin #{action} -C #{deploy_to}/current/config/thin.yml"
end
end
end
namespace :deploy do
# we don't need sudo for cleanup
before("deploy:cleanup") do
set :use_sudo, false
end
# taken from Advanced Rails Recipes
desc "Runs after every successful deployment"
task :after_default do
cleanup
end
# taken from Advanced Rails Recipes
task :copy_database_configuration do
production_db_config = "#{deploy_to}/shared/production.database.yml"
run "cp #{production_db_config} #{release_path}/config/database.yml"
end
after "deploy:update_code", "deploy:copy_database_configuration"
%w(start stop restart).each do |action|
desc "#{action.to_s.capitalize} the thin server(s)"
task action.to_sym do
find_and_execute_task("thin:#{action}")
end
end
end
aligned numbers aka zerofill
May 6th, 2008 •
tags: rails, rails helper, ruby
# zerofill(7,3) => "007"
def zerofill(value, digits = 9)
"%0#{digits}d" % value.to_i
end
google analytics for rails production environment
April 25th, 2008 •
tags: rails, rails helper
# assuming a partial located in views/shared # that contains the google analytics script body def render_google_analytics_script render :partial => "/shared/google_analytics" if Rails.env == "production" end # render from layouts <%= render_google_analytics_script %>
paginated record numbers
April 23rd, 2008 •
tags: rails, rails helper
# application_helper.rb # record numbering inside paginated admin index views def paginated_record_number(offset) # TODO find out will_paginate page_count query page = params[:page] ? params[:page].to_i : nil (page ? page - 1 : 0) * ( params[:per_page] || 30) + offset + 1 end # use in views like so <%= paginated_record_number(idx) %>
link_to_has_one
April 16th, 2008 •
tags: rails, rails helper
# Creates 'Show AssociatedResource' or 'New AssociatedResource' links
# based on wether the specified has_one association exists or not.
# The optional options parameter is passed through to link_to as html_options.
# Since this helper relies on record identification, there is no way to pass
# all the other url_for options, as far as I can see
# ---------------------------------------------------------------------------
# Use in your views like so:
# <%= link_to_has_one @post, :comment %>
# <%= link_to_has_one @post, :comment, "What say you?" %>
# <%= link_to_has_one @post, :comment, "What say you?", :class => "oldskool" %>
def link_to_has_one(parent, has_one_association_name, options = {})
has_one_association_name = has_one_association_name.to_s.underscore
child = has_one_association_name.camelize
child_path = "#{parent.class.to_s.underscore}_#{has_one_association_name}_path"
if parent.send(has_one_association_name)
name = options[:new_name] ? options[:new_name] : "Show #{child}"
link_to name, self.send(child_path, parent), options
else
name = options[:existing_name] ? options[:existing_name] : "New #{child}"
link_to name, self.send("new_#{child_path}", parent), options
end
end
named_scope features and gotchas
April 16th, 2008 •
tags: rails, rails models
# Examples mostly taken from Ryan Daigle's blog.
# http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality
# this shall serve as a reminder for me!
# WORKS but actually breaks coding conventions
# well, at least in most cases if you respect print margins ;)
# (multiline blocks/lambdas(?) are supposed to be enclosed in do/end
named_scope :created_by_account, lambda { |account|
{ :conditions => [ "created_by = ?", account.id ] }
}
# DOES NOT WORK
# ArgumentError: tried to create Proc object without a block
# Most probably this is due to the way that named_scope extensions can be defined
named_scope :created_by_account, lambda do |account|
{ :conditions => [ "created_by = ?", account.id ] }
end
# named_scope extensions
# I guess because of the way do/end is used here,
# it is not possible to use do/end with lambda
named_scope :inactive, :conditions => {:active => false} do
def activate
each { |i| i.update_attribute(:active, true) }
end
end
# original comment by Pratik Naik on March 27, 2008 @ 08:56 PM
named_scope :recent, :conditions => ['created_at > ?', 1.week.ago]
# That is really a bad example. As the conditions gets evaluated at load time,
# it’ll end up giving you inaccurate results in production
# where models get loaded only once.
# "Correct" way would be :
named_scope :recent, lambda {
{ :conditions => ['created_at > ?', 1.minute.ago] }
}
# Store named scopes
active = User.scoped(:conditions => {:active => true})
recent = User.scoped(lambda { { :conditions => ['created_at > ?', 1.minute.ago] } })
recent_active = recent.active
recent_active.each { |u| ... }
# count and statistic methods
user.active.recent.count #=> 23
user.active.recent.sum(:age) #=> 391
watching activerecord
April 15th, 2008 •
tags: rails, rails helper
# This greatly helps learning what ActiveRecord does! # All credits go to Jamis Buck at # http://weblog.jamisbuck.org/2007/1/31/more-on-watching-activerecord # environment.rb def log_to(stream) ActiveRecord::Base.logger = Logger.new(stream) ActiveRecord::Base.clear_active_connections! end # in irb or script/console or environment.rb log_to(STDOUT) # or create new streams buffer = StringIO.new log_to(buffer) puts buffer.string