/*
* metronome
*/
int stage = 600;
int mains = int(random(3,9) );
int subs = int(random(3,6) );
float moon_size = 3;
int bpm = 60;
int active_main = 0;
int active_sub = 0;
color main_color = #292B89;
color first_color = #1A1B55;
color active_color = 0x95FFFFFF;
int my_frame_rate = 12;
float bps = float(bpm) / 60 ;
void setup() {
size(stage, stage);
frameRate(my_frame_rate);
noStroke();
}
void draw() {
background(#989898);
if( frameCount % (my_frame_rate/bps) < 1 ){
active_main+=1;
if(active_main>=mains){
active_main=0;
}
}
if( frameCount % (my_frame_rate/bps/subs) < 1 ){
active_sub+=1;
if(active_sub==subs){
active_sub=0;
}
}
Circle a = new Circle(width/2, height/2, stage/2, mains);
a.make_moons( active_main );
a.moons[active_main].make_moons( active_sub );
}
void mouseMoved(){
mains = 2 + mouseX /(stage/10);
moon_size = mains/1.555;
active_main=0;
}
class Circle{
float r, x, y;
int active_moon, each_angle, sections;
Circle moons[] = new Circle[23];
Circle(float x_init,float y_init,float r_init, int divisions_init){
x = x_init;
y = y_init;
r = r_init;
sections = divisions_init;
each_angle = 360 / sections;
}
void make(){
ellipse(x, y, r, r);
}
void make_moons( int active_moon ){
int angle = each_angle;
for(int i = 0; i < sections; i+=1 ){
float moon_x = x + cos(radians(angle)) * (r/2);
float moon_y = y + sin(radians(angle)) * (r/2);
moons[i] = new Circle(moon_x, moon_y, r / 4, subs);
if(i==active_moon){fill(active_color);}else if(i==0){fill(first_color);} else{fill(main_color);} // HIGHLIGHT FIRST & ACTIVE MOON
moons[i].make();
angle = angle + each_angle;
}
}
}
Visual Metronome
Ruby Duration
[download id="1" format="1"]
Duration.new recieves a string describing a duration of time, and converts it into: seconds, and a standard readable format.
Or, you can pass Duration.new an integer representing seconds, and receive the same standard readable format.
Usage:
Passing a String
duration = Duration.new("2weeks 8 hr 30m")
duration.seconds # => 1240200
duration.readable # => "2 weeks, 8 hours and 30 mins"
Passing an Fixnum (of seconds)
duration = Duration.new(1240200) duration.readable # => "2 weeks, 8 hours and 30 mins"
Example valid input strings
“2 weeks”, “2wks”, “2w”,
“8h”, “8 hrs”,”8 hours”,
“30m”, “0:30″, “30 minutes”, “30min”,
“2 weeks, 8 hours and 30 minutes”, “2w 8h 30m”, “2w 8:30″,
“4 hours 30 minutes”, “4 hours and 30m”, “4h 30min”, “4:30″, “4.5″, “4.50″, “4h, 30 min”, “4.5 hours”, “4.50h”
http://ahabman.com added functionallity, extended and mashed-up http://stackoverflow.com/questions/657309/how-to-parse-days-hours-minutes-seconds-in-ruby and http://www.postal-code.com/binarycode/2007/04/04/english-friendly-timespan/
rails template
Usage $ rails app_name -m ./ahabman_template.rb
run "rm README"
run "rm public/index.html"
run "rm public/favicon.ico"
run "rm public/robots.txt"
run "rm -f public/javascripts/*"
gem 'ruby-openid', :lib => 'openid'
rake("gems:install", :sudo => true)
plugin "kamui_restful_authentication", :git => 'git://github.com/kamui/restful-authentication.git'
plugin 'exception_notifier', :git => 'git://github.com/rails/exception_notification.git'
plugin 'open_id_authentication', :git => 'git://github.com/rails/open_id_authentication.git'
#plugin 'asset_packager', :git => 'http://synthesis.sbecker.net/pages/asset_packager'
plugin 'role_requirement', :git => 'git://github.com/timcharper/role_requirement.git'
#plugin 'acts_as_taggable_redux', :git => 'http://github.com/geemus/acts_as_taggable_redux/tree/master'
#plugin 'restful-authentication', :git => 'git://github.com/technoweenie/restful-authentication.git'
generate("authenticated user sessions --include-activation --include-forgot-password --email-as-login")
generate("roles", "Role User")
#rake('acts_as_taggable:db:create')
rake("open_id_authentication:db:create")
rake('db:migrate')
route "map.root :controller => 'sessions', :action => 'signup' "
run "echo generated from ahabman_template > README"
run "cp config/database.yml config/example_database.yml"
#if yes?("Do you want this thing?")
# ...
#end
#my_var = ask("was up")
#generate :something, my_var
puts "SUCCESS!"
ruby on rails – has and belongs to many view plugin
So I’ll never have to write another has_and_belongs_to_many view again, here’s a plugin that dynamically makes 2 <ul> lists which you drag and drop both ways to manage the association.
http://svn.ahabman.com/public/many_to_many_view/
From the readme:
Assumming you have an @project var and you want to associate people with it.
<div id="m2m_container">
<%= render :partial => "shared/m2m", :locals => {
:thing => @project,
:association => 'people',
:association_attr => 'first_name' } %>
</div>
:thing take the current object
:association takes the pluralized association, a string.
:association_attr takes the attribute of the associated object that will be displayed.
You can’t use class variables in rails.
You can’t use class variables in rails. Unless you’d like to develop in production mode (specifically with config.cache_classes = true). In development mode all classes are reloaded on each request, which clears all class variables.
I had the perfect place to use them – while running a mass synchronization, and needing to store the timestamp (I couldn’t use the latest last_updated from each record). It worked perfect in ./script/console but failed entirely through the browser.
ruby csv to structured hash
I had a csv like this:
| object | color | flavor | shape |
|---|---|---|---|
| apple | red | sweet | round |
| banana | yellow | sweet | long |
| lemon | yellow | sour | round |
and I wanted a ruby hash structured like this:
{
'apple'=> { 'color'=>'red', 'flavor'=>'sweet', 'shape'=>'round'},
'banana'=> { 'color'=>'yellow', 'flavor'=>'sweet', 'shape'=>'long'},
'lemon'=> { 'color'=>'yellow', 'flavor'=>'sour', 'shape'=>'round'}
}
So I wrote this, which does the job:
require "faster_csv"
def csv_to_structured_hash
arr_of_arrs = FasterCSV.read( 'your.csv' )
stuff = {}
header = arr_of_arrs.shift
arr_of_arrs.each_with_index do |row, i|
thing = { row[0] => {} }
header.each_with_index do |col, header_index|
thing[ row[0] ][ header[header_index] ] = row[ header_index]
end
stuff.update( thing )
end
return stuff
end
Ruby conversion module
This is a ruby module useful for conversions dealing with length, weight, torque.
module Convert
def Convert.number_with_precision(number, precision=2)
"%01.#{precision}f" % number
rescue
number
end
def Convert.mm_to_in(mm, precision=2)
number_with_precision(mm * 0.03937, precision)
end
def Convert.in_to_mm(inches, precision=2)
number_with_precision(inches / 0.03937 , precision)
end
def Convert.feet_to_meters(f, precision=2)
number_with_precision( f * 0.3048, precision)
end
def Convert.meters_to_inches(m, precision=2)
number_with_precision( m * 39.37, precision)
end
def Convert.meters_to_feet(m, precision=2)
number_with_precision( m * 3.281, precision)
end
def Convert.kg_to_lbs(kg, precision=2)
number_with_precision( kg * 2.2 , precision)
end
def Convert.lbs_to_kg(lbs, precision=2)
number_with_precision( lbs / 2.2 , precision)
end
def Convert.nm_to_inch_pounds(nm, precision=1)
number_with_precision( nm * 8.850 , precision)
end
def Convert.inch_pounds_to_nm(inlb, precision=1)
number_with_precision( inlb / 8.850 , precision)
end
end
Rails redirect_to :back in Internet Explorer
Today I realized that the rails command redirect_to :back does not work in Internet Explorer because redirect_to :back depends on the HTTP_REFERER http header, which IE does not send. I was capturing an onclick event with jQuery and was able to sending along the current URL as a query string, which provided an easy way around this limitation.
In the view:
<script>
$jQuery('#myLink').click(function(){
window.location.href = 'theDestinationPage/?current_url=' + document.location ;
})
</script>
In the controller:
def myAction
.....
redirect_to params[:current_url]
end
Rails background process – simple, fast, easy.
My situation was this -
- Rails 2.0 app running on slicehost (ubuntu 8.04) in passenger mod_rails
- The goal was Dynamic PDF generation for a product catalog ( > 100 pages)
- This event had to be triggered from within the rails request / response cycle, but run outside of it
- I needed the simplest, fastest, more reliable way for this to happen
I looked at BackgroundRB, it is the most robust, well documented solution available. But it was overkill since I didn’t need status feedback and my time was very limited (backgroundRB setup seems somewhat involved). And, I wasn’t sure how it would interact with Passenger mod_rails – although FooBarWidget mentioned on IRC that it should work as expected.
I looked at Spawn plugin which supports threading and forking ruby processes. No luck – setting it one way never ran inside mod_rails and setting it the other way tied up the request response cycle.
All the ruby code was in place, except for how to detach this process from the request/response cycle, when severnspoon provided this
Simple, Easy, One-Line Solution:
My_Controller
def generate_pdf_in_background
system " RAILS_ENV=#{RAILS_ENV} ruby #{RAILS_ROOT}/script/runner 'MyModel.create_pdf_in_background' & "
end
end
That ampersand was all I needed. It runs the command as a background process. A new ruby process is kicked off, and the 10 minute task runs perfectly. Something makes the browser hang and wait for a response, but we confirmed that other requests can happen along side this.

Command finished notification with Ruby
I wanted a visual notification in Ubuntu when long running commands finished in Terminal. My solution, run the command and pipe it into notify.
$ a-long-running-command | notify
notify.rb
#!/usr/bin/env ruby require 'rubygems' require 'libnotify' Libnotify.show :summary => "Command finished.", :body => "#{ARGF.read}"Make it executable
add an alias to it in ~/.bashrc
Requires:
ruby, rubygems, and libnotify.
Similar solutions:
“alert” alias (I’ll be switching to this in Maverick),
a python version