Twittershoes: programming in Shoes.rb

February 22nd, 2008

I have to share this piece of code, wich results look indeed nice. You’ll see in the next blog post…

def string_alert
  c = (LIMIT-@iSay.text.length)
  @remaining.style :stroke => "#3276BA"
  c > 10 ? (@remaining.style :stroke => orange) : (@remaining.style :stroke => red) if (c < 21)
  c > 0 ? “#{c.to_s} chars” : “Too Long!”
end

[update]: Twittershoes.rb is born: screenshot here


first repo at github.com

February 15th, 2008

… just got my github.com invitation and proceeded to the registration.
They say its free while in Beta. Hosted in Engine Yard.
I created my first repo there, and the design seems clear, simple, effective.
Info is presented clearly, and i enjoyed the way they went after the creation of my repo, showing “Next Steps”. Nice.

I’ll work there for this project.


pg_upgradecluster 8.2 main

February 12th, 2008

PostgreSQL 8.3 is here. After apt-get’ing it, the upgrade didn’t move the 8.2 cluster up. Having 8.2 running in a custom port, made 8.3 go use the standard 5432 port.
8.3 created a main cluster.

Check ports:
$ sudo netstat -anput | grep postgres

Check wich configuration files and wich versions are running:
$ ps -Af | grep postgres

pg_upgradecluster when upgrading the existing PostgreSQL cluster, will check ports of the new and old version (check both 8.2 and /etc/postgresql/8.3/main$ grep 'port' postgresql.conf), and make the newer version use the older version’s port number. Then the older version will use an available port number. This keeps the original Port # in use.

Stop and drop the newly created 8.3 main cluster:
$ sudo pg_dropcluster --stop 8.3 main

Time to upgrade the 8.2 main cluster to 8.3
$ sudo pg_upgradecluster 8.2 main

After checking everything is ok we could remove the older cluster:
$ sudo pg_dropcluster --stop 8.2 main

and “apt-get remove” the 8.2 version.

docs:
$ man pg_dropcluster
$ man pg_upgradecluster


JSON Ruby and Smallr API

February 3rd, 2008

Nuno’s smallr.net API talks JSON. So what about accessing it with Ruby ?
Well, quite easy thanks to Florian’s JSON implementation for Ruby. So:

$ sudo gem install json_pure

Now, just need some attention on the use of the address / (slash) just after json and before the query, or you’ll get a HTTP 301 Status Code.
Code follows:

require 'rubygems'
require 'net/http'
require 'json/pure'

url = 'http://www.google.pt/search?q=json+ruby'
escaped_url = URI.escape(url, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
call = Net::HTTP.get_response(URI.parse("http://smallr.net/json/?url=#{escaped_url}"))
res = JSON.parse(call.body)

puts res['status'] # ok
puts res['url'] # http://smallr.net/925


on URI Ruby escaping

February 3rd, 2008

URI.escape method with no options doesn’t provide a trully good escape, and i just noticed it upon the need to access an API.

url = 'http://www.ruby-lang.org'
bad = URI.escape(url)
good = URI.escape(url, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))

The difference is:

bad => "http://www.ruby-lang.org"
good => "http%3A%2F%2Fwww.ruby-lang.org"

(via snippets.dzone => Matt Zukowski)


The Ruby Programming Language

January 29th, 2008

… next buy.

“Bestselling author David Flanagan teams up with Ruby creator Yukihiro "Matz" Matsumoto and writer/cartoonist/programmer why the lucky stiff to bring you the authoritative guide to Ruby. Covering versions 1.9 and 1.8, this book helps you learn Ruby’s lexical structure, primary expressions, conditionals, syntax, classes, the data it manipulates, and more. For experienced programmers who want to look at this language in depth, this guide is invaluable.”


flash-like implementation

January 13th, 2008

Flash is a Ruby on Rails method to show (mainly warning/error) messages. Camping has no such method, so i implemented an approach for error messages. The thing is, after a post method in the controller, the redirect creates a new instance for the controller, loosing the class instance variables set before.
So, after talking a bit with Zimbatm at #camping, we setup what could be a good solution: to use the @state session variable.

@state.error = ‘The unit is still operational, Dave. But it will fail within seventy-two hours’

The variable is cleared on the View layout method. Flash means just it. Show and clear. The layout code includes:

div(:class => 'error') { p @state.error.to_s; @state.error = ''; } unless @state.error.blank?

and the CSS .error class wraps the message inside a lightred box with a nice solid red border (say RoR?).


Camping on IRB

December 22nd, 2007

IRB is a great tool. What about testing parts of a Camping app in IRB (meaning App::Models module) ? Just require the app, but do not forget to establish the (in case of using it) ActiveRecord connection, that problably is specified in dispatch.rb
Try this, using _Why’s Blog webapp example:

$ cd /path/to/blog/app
$ irb
irb(main):001:0> require 'rubygems'
irb(main):002:0> require 'blog'
irb(main):003:0> Camping::Models::Base.establish_connection :adapter => 'postgresql', :host => 'trees', :port => 54321, :database => 'beautifull', :username => 'green', :password => 'forest'
irb(main):004:0> Blog::Models::Post.find(1)

Answers from lines:
[#3] => #< ActiveRecord::Base::ConnectionSpecification:0xb77499a8 @adapter_method="postgresql_connection", @config={:host=>“trees”, :password=>”forest”, :port=>54321, :database=>”beautifull”, :adapter=>”postgresql”, :username=>”green”}>
[#4] => #< Blog::Models::Post:0xb7736e5c @attributes={"body"=>“… this is the first post on Why’s blog web app for testing Camping functionalities. \r\n\r\nIts cool. It’s Ruby. Its Lighttpd. Its Postgres (well, at least in my implementation) via Active Record.\r\n\r\nCamping(TM) of WhyTheLuckyStiff”, “title”=>”camping is fine”, “id”=>”1″, “user_id”=>”1″}>

[#4] is the first row from postgres ‘beautifull’ database ‘blog_posts’ table. Fetched via ActiveRecord, via Blog::Models module, via Blog Camping app.


ActiveRecord connection adapters

December 22nd, 2007

…because of Camping::Models I’m using ActiveRecord Ruby implementation gem. Because source code is pretty well documented I maintain an opened xterm to check how things are done. Since I’m not using SQLite but PostgreSQL, i had to dig for the other parameters for the connection and I noticed AR has now connectors for severall DMBS:

$ cat /var/lib/gems/1.8/gems/activerecord-1.15.3/lib/active_record.rb
[…]
unless defined?(RAILS_CONNECTION_ADAPTERS)
  RAILS_CONNECTION_ADAPTERS = %w( mysql postgresql sqlite firebird sqlserver db2 oracle sybase openbase frontbase )
end

[…]


… on git

December 9th, 2007

Melo will be focusing on git

Once you get used to git, you won’t be needing “anything else” to maintain your code. Git is gaining more and more traction, now that bigger (distributed) projects (or parts of them) are running away from other scm’s into this one (Gnome ?, Kde, …). CVS, SVN user base is still huge, though. From the questions at Google Tech Talks, seems that Google has a very centralized && protected development environment, wich is not that strange attending to their business core and innovative material under maintenance/production (they shut the camera/video down sometimes due to their non disclosure politics). That kind of environment, generally speaking, seems to fit for git usage, since it does ssh and its built-in cryptographic authentication of history ensures revisions purity.
He added a Randal Schwartz video also at Google, in addition to the Linus one i referred here a while ago (the last time i saw Randal, he was talking about the wonders of Smalltalk at #git :-) in a very interesting debate)

[append]
pfig first-try screencast on git. well done.
[append]
to wrap up, this podcast, on Floss (not that) Weekly, a talk between the gitster (maintainer) Junio Hamano, Leo Laporte and Randal.


msg upload to gmail ruby class (imap)

December 4th, 2007

… moving to Google Hosted (Google Apps), there was the need to upload some thousands of e-mail messages. Since they were (mt) MediaTemple Berkeley mbox stores, i scp’d them locally (backup) and them imported them into Evolution local folders.
The problem was the copy/move to the google hosted imap mail server. Evolution couldn’t finish the task on severall tries. Mozilla Iceape (Seamonkey) had a similar behaviour, suffering from server disconnects, thus stopping the operation. Because i had severall folders, the task needed lot’s of attention, and i wanted the machine to do it all by itself…

Solution: let’s code !! What response is the server sending… ?

Shugo Maeda’s Ruby net/imap.rb class (stdlib) is simple and trusty.
Not wasting lots of time in it, i made a new class with the following usage, to send specified mbox file mail messages to a gmail (google hosted) account:

$ ./2gmail.rb MBOXFILE GMAILFOLDER [STARTINGMESSAGE]

If GMAILFOLDER doesn’t exist, gets created (i prefered messages in temporary folders) upthere.
If it breaks, you can:

$ tail 2Gmail.log

to see the last message sent, and restart the process in that message. I could have threaded the whole thing, but this is done just once, so lets keep in focus…
Usual problems during the tests, msg headers/body separation, timestamps, etc…
Class Mail in mailread.rb does a great job creating an Hash for the Message Headers. Sweet…

Everything is logged, so that it’s easy to ‘grep’ for errors in the 2Gmail.log file.
I had one only problem on a message with a 25MB attachment (gmail didn’t accept it).
All the messages are now up there, nobody knows for certain where (EU ? US ? both ?…)

The code needs one or two more Exception Handling, but it works very well. I had 6 xterm’s uploading at the same time. And yes, I could have openned 6 tabs in Gnome Terminal since we have them for ages, Mr. Leopard ones! Hey, we can even detach Tabs to independent Terminal windows via drag-n-drop (like in Epiphany, way way long ago… way…)

There are some thousands more messages to be uploaded, from ancient backups… maybe next week.

Operation screenshot: at Flickr as usual
Wanna try ? Get it here (ready for Debian & Ubuntu. For other distros, check line 1 or just prepend ruby interpreter on call)

$ chmod u+x 2gmail.rb
$ ./2gmail.rb MBOXFILE GMAILFOLDER [STARTINGMESSAGE]


self link notes for Camping mcfrmwrk

November 10th, 2007

Marking Database Versions example. (class ActiveRecord::Migration)
Sessions in Camping.
Parasite: Turning Rails into a Camping factory.
Camping Server for Lighttpd configurations.
Mounting Camping apps as subdomains.


more BDD and RSpec…

November 4th, 2007

“RSpec is a framework which provides programmers with a Domain Specific Language to describe the behaviour of Ruby code with readable, executable examples that guide you in the design process and serve well as both documentation and tests.”
…in RSpec

This is, RSpec is a state of mind in Ruby, represented in a DSL (Domain Specific Language for Behaviour Driven Development (BDD). It deals with expressing desired behaviours when building applications, creating the specifications and writing the code to match them.
Create examples for what the application should do, and build the code. Add another example, write more code, refactor it if necessary, and:

$/var/lib/gems/1.8/bin/spec app_spec.rb --format specdoc
RSpec rdoc
RSpec documentation

This is a work in progress but means a refactor on the way to think about developing…
Example: For us to be able to drive a car:
- it should have fuel;
- its battery should be charged;
- it should have at least 4 tyres (optimally a spare one), with the right pressure;
- …

require 'car'
describe Car do
   before(:each) do
     @car = Car.new
   end
 
   it "should not be out of fuel" do
     @car.should_not be_fuel(0)
   end
 
   it "should have a charged battery" do
     @car.batt(0.6).should be_close(1, 0.5)
   end
 
   it "should have at least 4 tyres" do
     @car.should have_at_least(4).tyres
   end
 
   after(:each) do
     @car = nil
   end
 
end

Now, in car.rb:

class Car
 
   def fuel?(qt)
     qt > 0
  end
 
   def batt(amp)
     @amp = amp
   end
 
   def tyres
     { 'fr' => 2.1, 'fl' => 2.1, 'rr' => 2.0, 'rl' => 2.0, 's' => 2.1 }
   end
 
end

Ok, running this small spec:

$ /var/lib/gems/1.8/bin/spec car_spec.rb --format specdoc
 
Car
- should not be out of fuel
- should have a charged battery
- should have at least 4 tyres
 
Finished in 0.014326 seconds
3 examples, 0 failures

Now, what about using BDD RSpec module with Camping… ?


next is… Camping MVC microframework

October 30th, 2007

…next in line are 3 web apps that will me made entirely in Ruby with the help of Why’s very light yet functional Camping, the 4 Kbyte microframework.
Camping lacks things, and its Markaby is a bit slow compared to RoR’s Erb, but the approach taken by _Why looks very interesting for its simplicity.

I changed the DB connector, not to use the standard SQLite but PostgreSQL, done very rapidly in the dispatch.rb file:

Camping::Models::Base.establish_connection :adapter => 'postgresql', :host => 'localhost', :port => xxxx, :database => 'camping_db', :username => 'of_course', :password => 'you_wish'

Some more 100% free software, and open source, being used:
Gnu/Linux Debian server · Lighttpd web server · PostgreSQL database · ruby · rubygems · rubygorge · rubyforge’s Camping
Lib’s to pay closer attention:
lib/camping/fastcgi.rb · lib/camping/session.rb · ib/camping/db.rb
Classes:
Camping::Views · Camping::Session · Camping::Controllers · Camping::Controllers::ServerError · Camping::Controllers::NotFound · Camping::Helpers · Camping::Base · Camping::Models · Camping::Models::Session · Camping::FastCGI · Camping::Mab (for the Markaby(Markup as Ruby)) rdoc here · Camping::Reloader · Camping::H

I’ll add more stuff now on…

Of course the intention is making the effort for Camping to gain traction in the web scene. Model-View-Controller, is it to last ?
humm… i’m giving a look on Catalyst, but now its Ruby, not Perl time… for me.


Edit remote scipts on local VIM under SSH generated RSA keys

September 28th, 2007

Passphrases, when used the good way, present a higher level of security over passwords, but what if you are editing scripts on a remote server using a local Vim ? For every open, write, explore, you are asked for it. After a certain amount of times, it starts making no sense, and you’ll end up writing the entire passphrase in clear text mode (hopefully, not during a presentation).

So, a good solution is to generate a key to use with SSH, then edit the remote files with a local:

vim -f scp://user@host.tld//path/to/the/scripts/

To generate the public/private key pair, and conjecturing you have openssh local and remotely, just locally do:

$ cd ~/.ssh
$ ssh-keygen

you may have to specify the type, say,

$ ssh-keygen -t rsa

You may specify a name, or by default you’ll get a ~/.ssh/id_rsa for the rsa type.
Then insert the passphrase that is used to access the remote server.
This creates the private/public key pair, as you can see on a directory listing.

On the remote host: if you have no ~/.ssh dir on the remote host, to have it created by sshd just ssh any server you know and it will be created with the right privileges.

On the local host: there are other options, like using named files, but one is to:

$ scp ~/.ssh/id_rsa.pub user@host.tld:/home/user/.ssh/authorized_keys2

There will be no need to advise do_not_upload the private key, right ? Just upload the .pub public key file. Finally, locally, add the rsa identity to the authentication agent on the local host:

$ ssh-add

this, if your key is id_rsa, that contains the protocol version 2 RSA authentication identity of the user. If not:

$ ssh-add my_key_filename

Test ? Just try to ssh your remote host:

$ ssh user@there.tld

Specifying no user, it will assume your $USERNAME is ssh’ing… If it’s all right, you were not asked to insert the passphrase, did you ? Now go and lend your laptop to someone, or leave it in the trunk of the car while dating some chic…

Back to Vim. Let’s explore a remote dir, and open some files:

$ vim -f scp://user@host.tld//path/to/the/scripts

:Explore

Select and press Enter on some file

:Vexplore

Select and press Enter on another file

lovely ? Indeed, and you are using your own .vimrc specs!! The cool (but security questionable) part is that if you were not using the, say, RSA keys, you’d have to insert the passphrase on every operation. Back on our last example, 5 times.

Finally. Of course you are using Gnome :) and if you go Places > Connect to Server > Service type: SSH > … and you name your connection My_Server_02, you’ll not need to use the… passphrase. Go run GEdit and open the remote server scripts…

Advise: read more on the web about openssh, check the MAN pages for ssh, ssh-add, ssh-agent, ssh-keygen, sshd, scp,…


screen modes note

September 9th, 2007

XGA 1024 x 768
WXGA 1280 x 800
WXGA+ 1440 x 900
SXGA 1280 x 1024
SXGA+ 1400 x 1050
WSXGA 1280 x 854
WSXGA+ 1680 x 1050
UXGA 1600 x 1200
WUXGA 1920 x 1200


Ruby REXML::CData RDOC page

July 12th, 2007

… one can read this is in the official REXML::CData RDOC page:

ie_hack: Internet Explorer is the worst piece of crap to have ever been written, with the possible exception of Windows itself. Since IE is unable to parse proper XML, we have to provide a hack to generate XML that IE‘s limited abilities can handle. This hack inserts a space before the /> on empty tags.


</short post> Debian 10Y Social Contract

July 4th, 2007

10 years of Debian Social Contract… July 5, 1997 - July 5, 2007.


Debian CUT

July 3rd, 2007

Joey Hess proposed some months ago an interesting slight realign for the Debian release model. Basically he proposes the formation of a team to ensure a Constantly Usable Testing (CUT) allowing for some (lots of) users to have access to a well formed and current packaged version of… Testing. CUT would enforce that Testing should be installable at all times, giving fast answers on how to deal with bugs (fix fast or drop package), security (fix fast or track for user to deal (hey, it’s Testing)), etc.

CUT does not mean Testing_is_tha_new_Stable (policy used by Google, Yahoo, etc, labeling everything as Beta), but it’s a fact that Desktop Debianists are going more and more for the latest packages that populate Testing. One can say: “so go get Ubuntu, you get all the fancy stuff there, and you can even go for Ubuntu+1… and every 6 months you have the right, by promise, to a new release”. True, after all they are related, as familly. But lot’s of Debianists are using and maintaining Debian Stable servers and using Testing on their laptops (yes, OSX too) and desktops for the everyday computing.

Me ? Love Ubuntu, have Feisty partition, have Gutsy on ISO, but Debian Etch speed makes my day. I live on the Etch ;)

…delivered by, Vim

Linus Torvalds on git

July 1st, 2007

Linus talked on Google about his source control management system, with questions from the audience. 70 precious minutes… with humour, smart ideas, good explanations on the theory of team software development, focusing on building a trust network, on performance, on centralized vs distributed systems, security, etc.

(by minute 60, this guy kicks Google Code (SVN) ass… hard)

blogged with VIM

Save Net Radio . Org

June 27th, 2007

SaveNetRadio.org

Apple Safari for profit…

June 22nd, 2007

… seems that the main (or a higher) reason for Apple to release a Windows version of Safari is… income. And for that, the Google search box in to top right corner is the gateway for profit.

Windows still is the most used operating system out there, so why not take the ride ? Mozilla did it with great Firefox. Flock are aiming that too. So, dear Epiphany, you are pure, you don’t think profit ;)


Flickr SET’s RSS Feed

June 12th, 2007

… no. No feed available. But thanks to cygnoir and wirehead info at Flickr IRC channel, i can get these feed by using the API. So i’ll code it now and there, Ruby will help me get those feeds, hopefully. Good’old IRC…