A More Useful login_as Test Helper

I just got upset that i could not do login_as User.first or User.first.id, so i fixed that…

Usage

#in your tests...
login_as :quentin
login_as false
login_as User.first
login_as User.first.id + 1

Install

#authenticated_test_helper
  def login_as(user)
    id = case user
      when false,nil then nil
      when Symbol,String then users(user).id
      when Fixnum then user
      else user.id
    end
    @request.session[:user_id] = id
  end

Grabbing Zen and the Art of Motorcycle Maintenance

I just found “Zen and the Art of Motorcycle Maintenance” for free online, a book that was on my wish list for quiet some time (recommended by a good number of programmers…).

And since i like a printed version here is a small script to get it in a printable format.
(which i post here for educational purpose only)

require 'rubygems'
require 'open-uri'
require 'hpricot'

book = 'zen_and_the_art/zen_and_the_art'
pages = 32
text = ''
1.upto(pages) { |i|
  doc = Hpricot(open("http://www.esolibris.com/ebooks/#{book}_#{i.to_s.rjust(2,'0')}.php").read)
  doc.search('table.body tr td[@height=40] div').remove
  doc.search('table.body tr td[@height=40] img').remove
  doc.search('table.body tr td[@height=40] p.body').remove
  doc.search('table.body tr td[@height=40] p a').remove
  part = doc.search('table.body tr td[@height=40]')
  text += part.inner_html
}

File.open('out.html','w') {|f|f.puts text}

No More Crontab Madness with a single Night Rake-Task

Crontab grows larger and larger with every new cleanup/maintence task…

...
0 0 1 * * cd ~/apps/my_app/current && RAILS_ENV=production rake summary:weekly_update >> ~/apps/my_app/current/log/summary_weekly_update.log
0 0 7 * * cd ~/apps/my_app/current && RAILS_ENV=production rake summary:weekly_update >> ~/apps/my_app/current/log/summary_weekly_update.log
0 0 14 * * cd ~/apps/my_app/current && RAILS_ENV=production rake summary:weekly_update >> ~/apps/my_app/current/log/summary_weekly_update.log
0 0 21 * * cd ~/apps/my_app/current && RAILS_ENV=production rake summary:weekly_update >> ~/apps/my_app/current/log/summary_weekly_update.log
...
echo 'crontab sucks...'

This is not DRY, so we fix it…

Cron calls “rake night” every night and night takes care of the rest…

#redirect and append puts to the logfile
def logging_to(path)
  FileUtils.touch([path])
  $stdout = File.new(path,'a+')
  yield
  $stdout = STDOUT
end

#use DRY to simulate a dry run
#uses hoptoad for error recording(better than exception notifier...), get it @ hoptoad.com
def invoke_and_log_task(name)
  begin
    logging_to "log/#{name.gsub(':','_')}.log" do
      if ENV['DRY']
        puts "dry-running #{name}"
      else
        Rake::Task[name].invoke
      end
    end
  rescue Exception => e
    HoptoadNotifier.notify(
      :error_class => "Nightly #{name} Error #{e.class}",
      :error_message => "#{e.message}"
    )
  end
end

desc "Runs maintains tasks at night"
task :night do
  invoke_and_log_task 'feed:update'
  invoke_and_log_task 'summary:weekly_update' if [1,7,14,21].include? Time.now.day
  ENV['greeting'] = 'Hello again...'
  invoke_and_log_task 'spam_users' if Time.now.day == 5
end

Switching User Agents while Grabbing with Mechanize

When grabbing pages, your user-agent could compromise your efforts of ‘not getting sued‘, its easy to see that the so called
‘WWW-Mechanize/0.8.5 (http://rubyforge.org/projects/mechanize/)’ browser (mechanize default user agent) may not be ‘browsing’…

So in order to stay undetected, we change our user_agent…

require 'activesupport' #for the rand part...

class MyGrabber
  def grab
    doc = Hpricot(agent.get('www.lawyer-rich-company.com').body)
    puts doc.search('#secret_info span').inner_html
  end

  def agent
    return @agent if @agent
    @agent = WWW::Mechanize.new
    @agent.user_agent_alias = WWW::Mechanize::AGENT_ALIASES.keys.rand
    #login or what not...
    @agent
  end
end