Open Source Linux Solutions » Ruby on Rails http://www.xmltree.com Open Source Linux Solutions: Linux Programs, Reviews Programs, Ruby on Rails, Tutorials for Web 2.0 Tue, 12 Feb 2013 17:50:22 +0000 en-US hourly 1 http://wordpress.org/?v=3.4.1 CD-o-matic with Ruby http://www.xmltree.com/?p=133 http://www.xmltree.com/?p=133#comments Sun, 10 Feb 2013 17:37:08 +0000 admin http://www.xmltree.com/?p=133 With just a bunch of ruby lines I created a small utility that fills a folder with songs picked randomly from a choosen repository until the maximum specified size is reached.

This tool is very useful for me ‘cause I can change my USB player music day-by-day without choosing each song from my repository (which is a boring and extremely long operation).

So, here you are the code:

require "ftools"

# Path were you want to store the randomly picked music

finalpath = "/Users/sandro/mp3xcd/"

# Path from which pick the music

repository = "/Volumes/ntfs/Musica/"

# Size Limit for the ‘finalpath’ folder (in bytes)

sizetomatch = 650000000

selected = []

cursize = 0

candidates = Dir.glob(repository+"**/*.mp3")

while cursize < sizetomatch do

nr = rand(candidates.length)

unless selected.include?(candidates[nr])

selected << candidates[nr]

puts "Adding: " + File.basename(candidates[nr])

cursize += File.size(candidates[nr])

puts "Space Left: " + (sizetomatch – cursize).to_s + " bytes"

end

end

selected.each do |f|

File.copy(f,finalpath + rand(selected.length).to_s + "-" + File.basename(f))

puts "Copying " + f + " to selected folder "

end

]]>
http://www.xmltree.com/?feed=rss2&p=133 0
PayPal Express Checkout and Ruby on Rails http://www.xmltree.com/?p=101 http://www.xmltree.com/?p=101#comments Wed, 06 Feb 2013 16:45:18 +0000 admin http://www.xmltree.com/?p=101 While working on the payment system solution for Whodoes we had to face the big challenge every online shop has to:

How can I connect and dialogate with my favourite payment gateway ?

Plus, having a company located in Italy means that you cannot use a lot of Americans and British payments gateway ( PayFlow, Authorize.net, and more… ) and you have to choose between a very few solutions.

Finally we decided to use the PayPal Express Checkout payment system and we started looking around for sample code and plugins.

The first plugin we found was ActiveMerchant that covers a wide variety of payments gateway and at the first look seemed the right choice for us.

Unfortunately the documentation related to this plugin is still in heavy development and the only sample we found about a PayPal Express Checkout payment with ActiveMerchant was very difficult to understand.

In the meanwhile I found that the same ActiveMerchant author Jaded Pixel had developed a plugin specifically designed for PayPal payments that is no longer supported because integrated into ActiveMerchant. However it is possible to download the latest version from the JadedPixel software repository ( I’m sorry I lost that url and google didn’t helped me in recovering) and also from here

This plugin is very easy to use, for exampe to create a form that redirect to paypal:

<%= paypal_form_tag %>

<%= paypal_setup "Test", Money.us_dollar(9000), "demo@demoaccount.com"%>

Please press here to pay $90US using paypal. <br/>

<%= submit_tag "Go to paypal >>" %>

<% end_form_tag %>

You can also handle IPN functionalities and cryptografich payment transmissions (everything is well documented in the plugin RDoc documentation)

In a nutshell, I found this plugin understandable and useful and I think that until ActiveMerchant will be properly documented this is the best solution avaiable for Paypal Express Checkout payments.

]]>
http://www.xmltree.com/?feed=rss2&p=101 0
Howto raise and rescue Exceptions in Ruby on Rails http://www.xmltree.com/?p=54 http://www.xmltree.com/?p=54#comments Wed, 30 Jan 2013 14:20:20 +0000 admin http://www.xmltree.com/?p=54 Hello ! This week we talk about exceptions. An Exception is an event that could be thrown in particular circumstances and that goes up all the application stack until someone rescue it.

Exceptions are commonly used for very exceptional events and could happen that we need to create a new Exception class for our programming purpose.

Ok, let’s suppose we need to raise a “PersonalException” exception at some point and rescue it in exactly the same way for all the controllers, the code is here:

Creating the Exception class

To create our “PersonalException” we just need to extend “Exception” class.

class PersonalException < Exception

end

Raise our Exception

raise PersonalException.new, "message"

Rescue our exception

We can do this by overwriting rescue_action_in_public and local_request?

functions to our application.rb file:

class ApplicationController < ActionController::Base

def rescue_action_in_public(exception)

if exception.to_s =~ /PersonalException/

# do your stuff here

else

raise exception

end

end

def local_request?

false

end

end

Some notes

As wrote on the Ruby on Rails wiki when you test this in development mode be sure to set to false this line in your “environments/development.rb”

config.action_controller.consider_all_requests_local = false

Also, if the server is on the same machine you’re developing you need to use the “-b ” option assoicated with your lan ip ( no 127.0.0.1 neither localhost) when starting the WEBrick server.

Conclusion

I’m still looking on how variables stored in our PersonalException instance can be retrieved. So, if someone wants to make suggestions please post a comment.

]]>
http://www.xmltree.com/?feed=rss2&p=54 0
Tutorial: a simple act_as plugin for ruby on rails http://www.xmltree.com/?p=38 http://www.xmltree.com/?p=38#comments Sun, 27 Jan 2013 13:40:10 +0000 admin http://www.xmltree.com/?p=38 Acts_as_commentable, acts_as_flaggable, acts_as… it seems that this kind of plug-ins is popping out from everywhere, so in this tutorial I’ll try to explain how to get your personal act_as plugin.

Chapter 1: Theory of an act_as

The key-word for a plug-in of this kind is ‘mixing’; mixing means using Modules nested inside Classes. In details this is how an acts_as plugin works:

  • inject into your Activerecord::Base class the module containing the function named ‘act_as_* ’
  • put your ‘act_as_* ’ into your target model
  • in the ‘act_as_* ’ function include the module that contains the instance functions and extend the module with the class functions

Ok, it seems easy, let’s try it out.

Chapter 2: Practice time

In few steps, we’re going to create a very easy act_as plugin: act_as_random. Our aim is to provide a random method that returns a random row from the choosen model. First, let’s create a rails application:

rails myactas

Now we’re ready to create our plugin:

ruby script/generate plugin act_as_random

We’re just 2 steps far from the end, the next one is open /vendor/plugins/act_as_random/lib/act_as_random.rb and put this code inside:

module MyMod

module Acts

module Roled

# included is called from the ActiveRecord::Base

# when you inject this module

def self.included(base)

# Add acts_as_roled availability by extending the module

# that owns the function.

base.extend AddActsAsMethod

end

# this module stores the main function and the two modules for

# the instance and class functions

module AddActsAsMethod

def acts_as_random(options = {})

# Here you can put additional association for the

# target class.

# belongs_to :role

# add class and istance methods

class_eval <<-END

include MyMod::Acts::Roled::InstanceMethods

END

end

end

# Istance methods

module InstanceMethods

# doing this our target class

# acquire all the methods inside ClassMethods module

# as class methods.

def self.included(aClass)

aClass.extend ClassMethods

end

module ClassMethods

# Class methods

# Our random function.

def random

find(:first,order=>"RAND()");

end

end

end

end

end

end

The last step involving our plugin is injecting our module inside ActiveRecord::Base, to achieve this just put this code inside our init.rb (in the plugins/myactas directory):

require ‘acts_as_random’

ActiveRecord::Base.send(:include, MyMod::Acts::Roled)

Done! Now we’re ready to use our new shiny plugin!

Chapter 3: Riding our plugin

Create a test model inside our app:

ruby script/generate model country

then fill our test model with some data using this sql file: countries.sql (i know, no migration and no yaml but it is just because is a test model :P ).

Now open app/models/country.rb and write:

# this is just because our table primary key name

# is not ‘id’

self.primary_key = "Code"

acts_as_random

In order to test this thing works, let’s open the console:

ruby script/console

>> puts "Today destination: " + Country.random.Name + " !!"

"Today destination: Netherlands !!"

=> nil

]]>
http://www.xmltree.com/?feed=rss2&p=38 0
Smart subversion script for Rails projects http://www.xmltree.com/?p=34 http://www.xmltree.com/?p=34#comments Sun, 27 Jan 2013 13:35:57 +0000 admin http://www.xmltree.com/?p=34 Using subversion is useful but sometimes very frustrating. You have to manually specify which files you want to ignore, and do this for each pc where the application is checkouted.

Luckily there is a very good-made page inside rails wiki called HowtoUseRailsWithSubversion that explain step by step how to create a trunk of you project,

But is not enough! Think, for each project you do you have to follow the same procedure! Doing this you’re violating one of the basic Ruby on Rails rules! DRY, aka Don’t Repeat Yourself!

We have the solution, here is a simple script you can add to you project and launch just after the first checkout. Do not repeat yourself anymore!

#!/bin/sh

svn remove log/*

svn commit -m"removing log files"

svn propset svn:ignore "*.log" log/

svn update log/

svn commit -m ‘Ignoring all files in /log/ ending in .log’

svn move config/database.yml config/database.example

svn commit -m ‘Moving database.yml to database.example to provide a

template for anyone who checks out the code’

svn propset svn:ignore "database.yml" config/

svn update config/

svn commit -m ‘Ignoring database.yml’

svn remove tmp/*

svn propset svn:ignore "*" tmp/

svn update tmp/

svn commit -m "ignore tmp/ content from now"

svn propset svn:ignore ".htaccess" config/

svn update config/

svn commit -m ‘Ignoring .htaccess’

svn propset svn:ignore "dispatch.fcgi" config/

svn update config/

svn commit -m ‘Ignoring dispatch.fcgi’

]]>
http://www.xmltree.com/?feed=rss2&p=34 0
Ruby on Rails is gaining momentum http://www.xmltree.com/?p=31 http://www.xmltree.com/?p=31#comments Sat, 26 Jan 2013 13:31:37 +0000 admin http://www.xmltree.com/?p=31 Since its first release by David Heinemeier Hansson in middle 2004, Ruby on Rails has enjoyed strong positive trend both in the open source and web development community. This trend can be easily noticed in Google Trend’s statistics.

It’s interesting to analyze the facts that generated hype in the past years. Main events are related to Rails releases or articles published by major tech-web sites.

The first peak is on June, when Slashdot posted an early review of the book Agile Web Development with Ruby on Rails by Dave Thomas and David Heinemeier.

The first release of RoR dates back to December 13: simple software movement gains momentum and RoR accelerates its presence both in blogs and tech related news (look at the News reference volume graph). Release 1.1 is on March, and was testified by InternetNews article Ruby on Rails Ramps Up by Sean Michael Kerner.

Than, consolidates the trend both for Ruby on Rails and Heinemeier’s company, 37Signals, which is winning several awards (Pc Magazine SMB 20 award, Technology Review Young innovator).

Will the release 1.2 give RoR the visibility it deserves in software panorama? Well, the trend is clear, Rails on Wave is born and will contribute to the spread of this powerful framework.

]]>
http://www.xmltree.com/?feed=rss2&p=31 0
We took the red pill http://www.xmltree.com/?p=28 http://www.xmltree.com/?p=28#comments Sat, 26 Jan 2013 13:25:55 +0000 admin http://www.xmltree.com/?p=28 Going through innovation is always the toughest path. When I think about Ruby On Rails “way of doing things” I always think about innovation.

The old way of coding MVC applications seems to me so damn complicated: no need to learn lots of of frameworks, integrate them together, without being completely sure to have a clear understanding of how things work, actually.

Taking the bandwagon of Rails “way of doing things” is like choosing between the “blue pill and the red pill”: we took the red one, being absolutely sure it’s going to be a winner in the web future.

How can I say that? Almost one year ago we got urgent a problem to be solved in our firm.

We had to streamline the process of Order Management for every engagement sold. We are a small company and buying a new module in our “ERP” (a big word to say “Accounting” for firms like ours) could seem the simplest way to address this organizational problem, but “eat your own dog food” prevailed.

After having thought for few minutes it was clear to me that this necessity could be the perfect test bed for Ruby On Rails. Normally we used to go through those kind of small apps using PHP or Java. I estimated we needed at least 4 weeks elapsed to complete our Web application, including a small analysis, coding and test.

Thinking about the requirements we got, the application seemed quite simple. So, why did we have to spend 4 weeks for a simple task like that? That was enough. I chose to challenge my team using Ruby On Rails to implement what we needed, adopting an agile methodology I sketched out in that period.

The teams feedback to my proposal was enthusiastic! I discovered that two of ours developers had already read something about Ruby, playing with it in the past months. An “8 day delivery challenge”- as we called it – began.

I was really amazed about how fast we could do stuff choosing the right approach: a simple methodology and an easy to learn framework. For the first time we could concentrate on the functionality instead of technicalities.

Simplicity instead of complexity. At day number 9 we were delivering a presentation of this new application we built to the firm. Then we collected some feedback and suggestions, and 7 days later we released the project.

After 15 days we got the first release working in production. It has been a success! We spent 50% time less. Our firm could see things happening quickly. The team could change assignment being completely satisfied.

Something special took place that day – something that improved our delivery skills a lot. Something magical happened.

]]>
http://www.xmltree.com/?feed=rss2&p=28 0