Padrino Routes Accept Regex URL Map

As Sinatra, Padrino route definitions accept regex when used as the :map option’s value in named aliases.

A standard named alias (‘thisroute’) mapped to some url with a code parameter embedded in the URL:

# For URLs like /someslug/anytext
get :thisroute, :map => '/someslug/:code' do
  # code param available as params[:code]
end

Accessing it as a block parameter, like in Sinatra, is also possible:

# For URLs like /someslug/anytext
get :thisroute, :map => '/someslug/:code' do |code|
  # code param available as request scope variable named code
end

And the killer one, if we want to enforce a pattern to the parameter, we capture it in a regex (suppose we only want to allow digits for that parameter, one or more), like this:

# For URLs with digits in param., only e.g. /someslug/123
get :thisroute, :map => %r|/someslug/([d]+)| do |code|
  # code made of digits captured by regex available as code var.
end

Behold! And YES!! The first capture (text matched by the regex portion inside the parenthesis – the regex syntax element which delimits a capturing group) is available as the first block parameter, super conviniently! Now go enjoy it, and boost up your Padrino application routing!

GNU Screen Howtos and Tutorials

Check these good links out. They are about the extremely powerful GNU Screen tool (the screen command):

To install it on Ubuntu execute the following commands:

$ sudo apt-get update
$ sudo apt-get install screen

Simple Spell Check on Linux

The file /usr/share/dict/words contains an english dictionary so search for your term like this:

$ grep tige /usr/share/dict/words

Output example:

antigen
antigen's
antigens
prestige
prestige's
tiger
tiger's
tigers
vestige
vestige's
vestiges

This file is very comprehensive as you can see from this example:

$ wc -l /usr/share/dict/words

Output example:

98569 /usr/share/dict/words

Ruby Numbers

Numbers in Ruby can be of 3 types (classes). Integers are represented by the classes Fixnum and Bignum. Values between -2^30 and (2^30) – 1 are of type Fixnum and numbers not in that range are Bignum objects. Ruby assigns the type automatically. The remaining class is Float. When using scientific notation you must place the zero after the dot otherwise in e.g. 1.e3 Ruby will try to call the method e3 on the Fixnum object with the value of 1.

You can represent binary numbers, octal, and hexadecimal by respectively starting the literal with 0b, 0, and 0x. Decimal numbers can receive the optional prefix 0d.

Integer (Fixnum and Bignum) numbers have methods, as they are objects. You can call methods such as abs (absolute value), zero? (returns true if the object has the zero value) etc. as available in the Ruby API Documentation.

tryruby.org Review – Ruby Summary

The tutorial described by this post is brief but not as brief as it states (15 minutes) not at least for those that are seeing this technology for the very first time. At least for me, it took around 45 minutes to traverse it completely paying attention and trying to understand every part as well as the whole of it. Nevertheless, this tutorial is amazing. It is a blazing fast and complete tutorial, showing very important and practical features of the language via straightforward examples.

The same content in that tutorial will be presented here in a very brief way. It will be non-interactive like in there, though. This is just for remembering or reviewing purposes.

Let’s start:

Ruby is a japanese creation and it is revolutionary.

Type this on the prompt at hand:

2 + 6

This command returns a result: 8. Here we have the first important principle:

1) “All code gives an answer.” – Every command yields a result.

Then comes the string syntax with double quotes: “Jimmy”. As it is quick it promptly shows us how to reverse that name by executing the reverse method:

"Jimmy".reverse

And get its length:

"Jimmy".length

Get 5 times “Jimmy”:

"Jimmy" * 5

reverse and length are English-language methods and * is a symbolic method.

Second principle:

2) Methods are action!

This causes an error:

40.reverse

Then try this:

40.to_s.reverse

In short:

  • to_s is for string;
  • to_i is for integer;
  • to_a is for array.

This is an empty array:

[]

A non-empty example, and obtaining the maximum of its values:

[12, 47, 35].max

Store the array in a variable:

ticket = [12, 47, 35]

Type ticket in and see it printed back.

Reverse it in place (the exclamation sign in a method name indicates that it alters the contents of the object):

ticket.sort!

Text replace is done in this fashion (poem is a variable pointing to a String object):

poem['searched text'] = 'replacement text'

Square brackets are for targeting and finding things. Search and replace.

Reversing the poem:

poem.reverse

Not good? Wanted to reverse the lines?

poem.lines.to_a.reverse.join

Instead of join it could have been to_s.

Analogous to the exclamation sign we have methods with a question mark, like this one:

poem.include? "some part"

It will return true when “some part” is a part of poem’s content. Pretty intuitive, huh? Keep following…

String methods e.g. downcase and delete are described here.

Hashes

Code:

books = {}
books["Full Dark, No Starts"] = :splendid
books["The Gunslinger"] = :good
books["If Tomorrow Comes"] = :awesome

{} is a hash. Its purpose is to pair up two things. In this case, book titles are receiving ratings.

But what are those words starting with a colon? This is the syntax for symbols. Unlike strings just one copy of it will lay in the memory for the process. Thus, its main purpose is performance. Symbols are tiny and fast.

To access a hash entry just type the name of the hash followed by the square brackets with the key to perform the lookup, but this time without the equal sign nor the value (assignment omitted), like this:

books["If Tomorrow Comes"]

One important thing to keep in mind is that the purpose of hashes is not sorting things up, but just pairing up two things, namely a key and a value. We can access a hash’s keys with e.g.

books.keys

Create a new hash:

ratings = Hash.new {0}

Then:

books.values.each { |rate| ratings[rate] += 1 }

The code within the curly braces is a block. A block is a bit of Ruby code that is attached to a method (the each method, above) and gets executed for each iteration of the method it is attached to. In this case, for each iteration, the each method gives the block an argument which was named rate.

Then at the end of the execution ratings will be a tally for how many times each rate was used.

Another example for a method that can have a block attached to it and executed – times:

5.times { print "Odelay!" }

The 5th part of the tutorial gives a taste of file manipulation. I will just toss the examples right here as they are very easy and intuitive to understand:

Dir.entries "/"
Dir["/*.txt"]

The Dir[] method is like entries but it searches for files with wildcard characters.

print File.read("/comics.txt")
FileUtils.copy('/comics.txt', '/Home/comics.txt')
File.open("/Home/comics.txt", "a") do |f|
  f << "Cat and Girl: http://catandgirl.com/n"
end

do and end are the same as { and }. Rubyists often use them when the block goes on for many lines.

File.mtime("/Home/comics.txt")

The mtime gives us a Ruby Time object. If we want to check just what hour it was:

File.mtime("/Home/comics.txt").hour

Note: Methods with more than one argument have them separated with commas.

Methods and Classes

def load_comics( path )
  comics = {}
  File.foreach(path) do |line|
    name, url = line.split(': ')
    comics[name] = url.strip
  end
  comics
end

File.foreach opens a file and hands one line at a time to the block.

The split there is an axe laid, chopping the string in half, yielding the url and name.

strip removes extra spaces. Just to be safe.

The popup example (require ‘popup’) was omitted. Go to the tutorial and try it if so desired.

Now create a hash:

Hash.new

{} is a shortcut for it. They are the same.

What is ahead of us? Well, to start doing more complicated things, the best idea is to start by defining a new class. The focus now has become the construction of a blog in Ruby.

class BlogEntry
  attr_accessor :title, :time, :fulltext, :mood
 
  def initialize( title, mood, fulltext )
    @time = Time.now
    @title, @mood, @fulltext = title, mood, fulltext
  end
end
 
entry = BlogEntry.new

Change the mood (access an attribute) without @ or $ (global variables) prepending the name, when outside the object:

entry.mood = :happy

mood there (outside the object) is an attribute accessor. Inside the object we have the instance variables (with the at-symbols prepending them).

Another identical way of expressing the @time assignment above, but outside of the object, is with this:

entry.time = Time.now

which is the attribute accessor alternative.

Using the initialize parameters:

entry2 = BlogEntry.new("In the Universe", :lost, "The Universe is infinite.")

Here are some more fundamental Ruby principles to remember:

3) Everything in Ruby is some kind of object. Classes explain objects. How a certain object works.

4) Accessors are variables attached to an object which can be used outside the object. (entry.time = Time.now)

5) Instance variables are the same variables used by accessors when inside the object. Like in a method definition. (@time = Time.now)

Now on to the very end. With Ruby we can do very neat things.

An array blog:

blog = [entry, entry2]

Try and guess what the following do:

blog.sort_by { |entry| entry.time }.reverse
blog.find_all { |entry| entry.fulltext.match(/cadillac/i) }

Add new entries to the blog with the << method:

blog &lt;&lt; new_entry

Map

blog.map { |entry| entry.mood }

The map method cycles through the array replacing each item with something new. This new thing is that one inside the block. In the above example each item in the array gets replaced by its mood.

If we wanted to replace each of our blog entries with the name Bruce Willis we would do it like so: blog.map { “Bruce Willis” }

Links (Anything from the # character to the end of the line is a comment in Ruby):

http://ruby-doc.org/core/classes/Array.html # << method etc.

http://ruby-doc.org/core/classes/Enumerable.html # find_all method etc.

http://ruby-doc.org/core/classes/String.html # match method etc.

http://rubyonrails.org/ # The proper way to start using your Ruby knowledge, lad.

http://rubyonrails.org/screencasts # Creating a blog in 15 minutes (Rails).

One thing Rails has is easy methods for dates. Like, try:

Time.now - 2.weeks