Divisible

I just published my first ruby gem on rubygems.org. It is a simple gem that is useful in case you need to find out if one number is divisible by another.

Usage

  9.divisible_by(3) # => true
  10.divisible_by(3) # => false
  12.divisible_by(3) # => true
  12.divisible_by(4) # => true
  15.divisible_by(4) # => false

Same can be done with

  Divisible.check(9, 3) # => true
  Divisible.check(10, 3) # => false
  Divisible.check(12, 3) # => true
  Divisible.check(12, 4) # => true
  Divisible.check(15, 4) # => false

Installation

  gem install divisible

For more info go to https://github.com/vlado/divisible

Simple Search Rails plugin

SimpleSearch brings simple search to ActiveRecord. It ads simple_search named scope that accepts query as parameter.

The idea is that you provide the query and plugin does the rest (splits query to keywords and compose where statement).

This can be very useful in case you just want to filter list of records by some query, you have autocomplete field, … or something similar.

Continue reading

Ruby library for parsing, validating and formatting phone numbers

Tomislav Car has just released Phone, Ruby library for phone number parsing, validation and formatting. It should save you a lot of time if you need any of the following:

* you have area where users input phone numbers in many different formats
* output phone numbers in specific format
* you need to send SMS messages from your app
* …

Continue reading

Radiant CMS, disable caching in development

I am working on extension for Radiant CMS. I wanted to disable caching for development, but wasn’t able to find right method for this, so finally I did it by putting this into my extensions activate method

if RAILS_ENV=="development"
  Page.class_eval {
    def cache?
      false
    end
  }
end

This is more of a hack then a real solution, so please use comments to point me in the right direction. I’m using Radiant version 0.8.1.

Determining the number of days in a month

Here is a simple method that returns number of days for wanted month and year. If year is ommited current year is selected.

def month_days(month, year=Date.today.year)
  mdays = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  mdays[2] = 29 if Date.leap?(year)mdays[month]
end

Simple examples:

month_days(1)       => 31
month_days(2, 2007) => 28
month_days(2, 2008) => 29

Now, let’s assume we have a date from a database, and we want to find number of days in a month from that date.

month_days(date.month, date.year)

But with two more lines of code

Continue reading

Ruby Inject

You probably frequently have to iterate through a list and accumulate a result that changes as you iterate. Let’s take the following array:

nums = [1, 3, 5, 7]

If you want to find a sum of all the items in the array, you could write something like this:

sum = 0
nums.each { |n| sum += n }

This works fine, but it doesn’t look much elegant. Luckly, for us that wants to be elegant there is a inject method.
(See: Enumerable::inject)

sum = nums.inject(0) { |x,n| x+n }

This code does the same thing, but also looks cool. Inject acomplish this by using accumulator or accumulated value (x). At each step accumulated value is set to the value returned by the block. Here, we set accumulator initial value to 0, and at each step current value from array (n) is added to accumulated value.

If initial value is omitted, the first item is used as the accumulator initial value and is then omitted from iteration.

sum = nums.inject { |x,n| x+n }

Is same as

sum = nums[0]
nums[1..-1].each { |n| sum += n }

Another example.
We have array with five names:

names = ["michael", "ron", "scottie", "dennis", "toni"]

The following code:

string = names.inject("") { |x,n| x << "#{n} " }

Will output:

=> "michael ron scottie dennis toni "

You can get the same output with:

string = ""
names.each { |n| string << "#{n} "}

Now, let's say you won't to separate them with comma, and capitalize those that have more then four characters.
You can do it like this:

string = ""
names.each do |n|
  name = n.length > 4 ? n.capitalize : n
  n == names.last ? string << name : string << "#{name}, "
end

Or like this:

string = names.inject("") do |x,n|
  name = n.length > 4 ? n.capitalize : n
  n == names.last ? x << name : x << "#{name}, "
end

In both ways we get the same result:

=> "Michael, ron, Scottie, Dennis, toni"

Technorati Tags: , , ,

Quick Start with Rails on OS X

Install Ruby

OS X (10.4) comes with Ruby 1.8.2 already installed.
For a quick start this is OK so let’s install Rails.

Install Rails

Since Rails comes as gem package, first we need to install RubyGems.
Download the latest package from RubyForge and unzip it.
Now go to the directory where you unpacked the package and run

$ sudo ruby setup.rb

When asked enter your password, and after install finish you can verify that everything went well by typing:

$ gem -v

Output should look something like this, depending on version you installed

=> 0.9.4

Now installing Rails is as simple as

$ sudo gem install rails --include-dependencies

To verify installation, type:

$ rails -v
=> Rails 1.2.3

Install MySQL

You can skip this step if you don’t want to use database but since Rails is a framework for developing database-backed web applications, you’ll probably want to use one.

  1. Download the MySQL package for OS X for your platform
  2. Double-click the drive image to mount it
  3. Locate the MySQL installer (something like mysql-5.0.45-osx10.4-i686.pkg) and run it, authenticating as needed
  4. Double-click MySQLStartupItem.pkg
  5. Double-click MySQL.prefPane and install it

Once the install is complete, start the MySQL server using the control panel. ( System Preferences -> Other -> MySQL ) and check Automatically Start MySQL Server on Startup

Test your installation

To start a new project (application), go to the directory where you plan to keep your applications (i.e. ~/Apps) and execute following commands

$ rails test_app
$ cd test_app
$ ./script/server

This will generate Rails skeleton in ~/Apps/test_app, and start a WEBrick server on port 3000.
Now open your browser and enter http://localhost:3000 in address bar. You should see a page with “Welcome aboard, You’re riding the Rails!” message.

We also need to tell Rails which database to use.
To do this edit database.yml file (~/Apps/test_app/config/database.yml) to look like this

development:
  adapter: mysql
  database: test_app_development
  username: root
  password:
  host: localhost

test:
  adapter: mysql
  database: test_app_test
  username: root
  password:
  host: localhost

production:
  adapter: mysql
  database: test_app_production
  username: root
  password:
  host: localhost

Naturally we also need to create a database

$ mysqladmin -u root create test_app_development

and table in that database

$ mysql -u root

mysql> create table items (
         id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
         name VARCHAR(100) );

Execute scaffold command

$ script/generate scaffold item

Open http://localhost:3000/items and if you see something like this

Listing items

Name

New item

you have everything needed to get started with Rails development so Enjoy!

Technorati Tags: , , ,