Rails: transform Path to Url

Almost 1 hour of digging before i gave up and built this…
Update: thanks for the improvement @ Will Sulzer

  # abs or /abs -> http://myx.com/abs
  # https://grosser.it/2008/11/24/rails-transform-path-to-url
  def path_to_url(path)
    "#{request.protocol}#{request.host_with_port.sub(/:80$/,"")}/#{path.sub(/^\//,"")}"
  end

Invoke Any Rake Task via Capistrano

Just run a rake task without having to setup a special capistrano task.

Usage

cap rake_task:invoke COMMAND="db:migrate" #yes, its a silly example...

Setup

namespace :rake_task do
  task :invoke do
    if ENV['COMMAND'].to_s.strip == ''
      puts "USAGE:   cap rake:invoke COMMAND='db:migrate'"
    else
      run "cd #{current_path} && RAILS_ENV=production sudo rake #{ENV['COMMAND']}"
    end
  end
end

All Your Records As CSV, fast and generic

Our admins are always data-greedy, so i provided a method that lets them get detailed data on any search result they like. Be careful to not let normal users access this (hide email addresses etc).

Installation

  • Provide a current_model method that returns which model the controller is working on.
  • Store the objects you want to render in @current_objects.
  • add this block to every index action response (in a DRY way…)

Usage

  • Visit /xxx/anything.csv to get all data in csv
format.csv do
  #collect data
  keys = current_model.new.attributes.keys.sort
  csv_string = FasterCSV.generate do |csv|
    csv << keys
    @current_objects.each do |record|
      csv << record.attributes.sort_by{|k,v|k}.map{|arr|arr[1]}
    end
  end

  #send data
  filename = current_model.to_s.downcase.gsub(/[^0-9a-z]/, "_") + ".csv"
  send_data(csv_string,
    :type => 'text/csv; charset=utf-8; header=present',
    :filename => filename
  )
end

has_a_location – the Latitude Longitude – Rails Plugin

Easy handling of latitude/longitude information, build on top of acts_as_mappable (aka geokit).

has_a_location Installation instructions

Usage

class User < ActiveRecord::Base
  has_a_location
end

@user.location = [11.101,22.121]# latitude , longitude
@user.in_radius(100) #find in 100 miles radius

#this location will not be stored since it is the "default location"
@user.location = [0,0] 

show_map if @user.location

All options and Readme