The Passionate Craftsman

Ruby, PHP, MySql, Software engineering and more.

Thursday, 29 December 2011

Create a basic Ruby app with Rack middleware - part 1

This post - or may be a series of posts - on Rack is intended to understand how modern Ruby frameworks work. Frameworks such as Sinatra or Ruby on Rails use Rack middleware to exchange requests and responses to application servers. Old time of CGI or FCGI are gone. The code below shows how simple is to start a ruby server to serve a 404 error page:

app = lambda do |env|
body = File.open(File.dirname(__FILE__)+'/404.html', 'r').read
[404, {'Content-Type' => 'text/html'}, [body]]
end

run app


Save the previous script in a file named config.ru. If you have a page 404.html in the same directory of config.ru and you run:

> rackup -p 3000

You will get the 404.html page by connecting to http://localhost:3000. Please notice the curly braces between body: it is needed by Ruby 1.9. The run app statement run the lambda we just created.

Labels: ,

Convert ruby code to HTML to paste it into your blog

I use the following script to read ruby code and output the HTML to the stdin of the shell:

require 'syntax/convertors/html'

code = File.read('code.rb')

convertor = Syntax::Convertors::HTML.for_syntax "ruby"
code_html = convertor.convert( code )

puts code_html


Put you ruby code in 'code.rb' and run

> ruby script_name.rb

Then cut and paste the content. You have to add the following CSS if you want to see your code properly formatted:

pre {
    background-color: #f1f1f3;
    color: #112;
    padding: 10px;
    font-size: 1.1em;
    overflow: auto;
    margin: 4px 0px;
          width: 95%;
}



/* Syntax highlighting */
pre .normal {}
pre .comment { color: #005; font-style: italic; }
pre .keyword { color: #A00; font-weight: bold; }
pre .method { color: #077; }
pre .class { color: #074; }
pre .module { color: #050; }
pre .punct { color: #447; font-weight: bold; }
pre .symbol { color: #099; }
pre .string { color: #944; background: #FFE; }
pre .char { color: #F07; }
pre .ident { color: #004; }
pre .constant { color: #07F; }
pre .regex { color: #B66; background: #FEF; }
pre .number { color: #F99; }
pre .attribute { color: #5bb; }
pre .global { color: #7FB; }
pre .expr { color: #227; }
pre .escape { color: #277; }


The style of the CSS code above has been created by changing the type of highlighter:


convertor = Syntax::Convertors::HTML.for_syntax "css"

Labels:

How to call a private method in Ruby

If you want to call a private method in Ruby - for any reason - you can use send, method and instance_eval:



class Foo

private
def bar
puts 'You called bar'
end
end

> foo = Foo.new
foo.bar # this, of course, throws an error
NoMethodError: private method `bar' called for #
from (irb):129
from :0

> foo.send(:bar)
You called bar
=> nil
m = foo.method(:bar)
=> #
> m.call
You called bar
=> nil
> foo.instance_eval { bar }
You called bar
=> nil


Remember you cannot use eval to call a private method:


> eval('foo.bar')
NoMethodError: private method `bar' called for #
from (irb):140
from (irb):140
from :0



Labels: ,

Sunday, 13 November 2011

Create a Rails 3 project with "activerecord", "capybara", "devise", "git", "haml", "jquery", "rspec", "sass", "settingslogic"

You can run this commend:

rails new APP_NAME -m http://railswizard.org/50fc74d6dfa659c06971.rb -J -T

I have created the template using http://railswizard.org/

Labels: ,

Friday, 11 November 2011

Catch all exceptions in your Ruby program

Just put your code between begin and rescue statements and print the error. An example:


ree-1.8.7-head :010 > begin
ree-1.8.7-head :011 > Testing.new
ree-1.8.7-head :012?> rescue Exception => msg
ree-1.8.7-head :013?> puts "Something went wrong ("+msg+")"
ree-1.8.7-head :014?> end
Something went wrong (uninitialized constant Testing)
=> nil

You can boot your application between begin and rescue and you will be able to print the error, perform an action, send an email in the rescue begin section:

begin
MyApp.run!
rescue Exception => msg
puts "Something went wrong ("+msg+")"
end

Labels:

Friday, 5 August 2011

conman: automate your server configuration

Probably you already know about Puppet and Chef and probably you felt overwhelmed when learning one of the the two server configuration management. I want to show you conman a simpler and easier approach then Puppet and Chef. Of course it has very basic features but it could be easily extended. So install conman:

gem install conman

conman has ingredients and recipes. Recipes contains ingredients. An ingredient is a class extending the Ingredient class having methods with commands. Here you can see and example of a class which can install or remove the apache2 package:


class Apache2Ingredient < Ingredient
def install
`sudo apt-get install apache2`
end

def remove
`sudo apt-get remove apache2`
end
end

The you can include you new ingredient in your recipe:


class MyRecipe < Recipe
apache2 :install
end


apache2 method search and load the Apache2Ingredient, then calls the install method. Simple!

You can run the recipe using the command line:

conman -i /path/to/ingredients /path/to/recipes/my_recipe.rb

or using Ruby:

Conman.init :ingredients => '/path/to/ingredients/' Conman.run '/path/to/recipes/my_recipe.rb'


conman does not know about packages, apt-get, rpm... but I think it can be easily implemented. Another important thing that is missing is the possibility to run remotely the recipes; a SSH session using a Ruby library could do the trick (execute the command remotely).

Link: https://github.com/moocode/conman

Labels: ,

Friday, 24 September 2010

Install pg gem with PostgreSql 9.0 on Leopard

Download the installer from: http://www.enterprisedb.com/products/pgdownload.do#osx.
Install PostgreSQL, insert your password and you will have pgAdmin and other tools in your Applications directory.

If you will try to install the pg gem now you will get a compile error. You need to define the architecture of PostgreSQL and its bin directory:

sudo -s
export ARCHFLAGS='-arch x86_64'
export PATH=/Library/PostgreSQL/9.0/bin:${PATH}
gem install pg

This is the output I get:

bash-3.2# gem install pg
Building native extensions. This could take a while...
Successfully installed pg-0.9.0
1 gem installed
Installing ri documentation for pg-0.9.0...
Installing RDoc documentation for pg-0.9.0...
bash-3.2#

Labels: ,

Monday, 2 August 2010

Kitty - a funny gem

I found a new screencast on Rubypulse about a gem named kitty. If you install the gem, then you will have a kitty command that will print a random ASCII-art cat. For instance:


Labels: ,

Tuesday, 24 November 2009

How to install mysql gem on Mac

Download and install the x86 version of MySql, the run the following command:

sudo env ARCHFLAGS="-arch i386" gem install mysql -- \
--with-mysql-dir=/usr/local/mysql --with-mysql-lib=/usr/local/mysql/lib \
--with-mysql-include=/usr/local/mysql/include

This should be enough to have the mysql gem installed

Labels: , ,

Friday, 23 October 2009

How to install Mysql/Ruby on Solaris SPARC 64

I found only partial documentation on how to install the Ruby driver for MySql. There are two version of drivers, one is MySql/Ruby and is written in C, the second is Ruby/MySql and is written in Ruby. Ruby/MySql is included in Rails but has slower performance, plus it was not working with MySql 5.0, it does not work with MySql 4.something too!

So I decieded to compile the C driver. Below you can find the commands:


curl http://tmtm.org/downloads/mysql/ruby/mysql-ruby-2.7.tar.gz -o mysql-gzip -d gzip -d mysql-ruby-2.7.tar.gz
tar xfv mysql-ruby-2.7.tar
cd mysql-ruby-2.7
ruby extconf.rb --with-mysql-include=/usr/local/mysql/include/mysql --with-mysql-lib=/usr/local/mysql/lib/mysql
make
sudo make install


Make sure that 'make install' will be executed as root. Now you can test the connection with:


ruby test.rb [hostname] [username] [dbpassword]


Of course you have to put the host, username and password. Another nice script to test your MySql connection is:


require 'mysql'

mysql = Mysql.init()
mysql.connect('localhost', 'username', 'password')
results = mysql.query("SELECT now();")
results.each{|row|; puts row;}
mysql.close()

Labels: ,

Thursday, 22 October 2009

Ruby database recipes with MySql

First of all I am using Windows as OS (yes, I have to use it here).

Rails has a very nice ORM: ActiveRecord. However ActiveRecord is quite complex and a simple library to manipulate data in a script can be more than enough. In this post I will use MySql as DBMS. First of all you need the MySql adapter and the MySql gem:


gem install mysql


If you have troubles when installing the gem and you have the MySql 5.1 client, download and install the 5.0 instead, there are, at the moment of writing some issues in Windows. Now you can check if you can connect to the database. The following example is the code to manipulate data in a MySql table named users. As you can see it is not so different from the previous example, but it can be use with other DBMSs, this is the beauty of a database abstracion layer, using the adapter design pattern.


require 'dbi'

# Connect to a database, old style
dbh = DBI.connect('DBI:Mysql:test:localhost', 'root', 'asdf')

# Insert some rows, use placeholders
1.upto(13) do |i|
sql = "insert into users (username) VALUES (?)"
dbh.do(sql, "user#{i}")
end

# Select all rows from users
sth = dbh.prepare('select * from users')
sth.execute

# Print out each row
while row=sth.fetch do
p row
end

# Close the statement handle when done
sth.finish

# Don't prepare, just do it!
dbh.do('delete from users where id > 10')

# And finally, disconnect
dbh.disconnect
Some useful links:

Labels: , ,