Currently Browsing: Uncategorized

Fútbol Con Sentido – Apertura 2012

Interesante plática con César Martinez y David Maiz acerca de la Apertura 2012, Fútbol Con Sentido.

Play

Generating PDFs from Ruby on Rails

Generating PDFs from Ruby on Rails

The problem

Ruby on Rails provides various helpers for generating dynamic web content but sometimes you need documents that users can easily store and share between them. The ubiquitous file format for this is Adobe PDF nowadays.

The common solution fro this problem is Prawn [github, introduction]. Alas it requires a custom DSL for document description, no existing Rails views or partials can be reused. An alternative is princeXML which transforms HTML/CSS into pdf through an external binary. This would allow reuse of existing templates and knowledge (think CSS designers) but has the downside of its price tag of $3800.

The solution

Enters wicked_pdf: it utilizes wkhtmltopdf to create a PDF document from a Rails HTML template. HTML rendering is done through the well-known webkit-engine. This allows developers to do PDFs in the right way™: define the document’s structure through a simple HTML document and theme them through CSS. You’ll get the automatic benefit of themability: exchange the CSS and you have another format. There are also lots of CSS artists out there that can supply you with different designs.

 

I’ve used this solution with a test Ruby on Rails 3.0-beta application, the steps involved were:

Install wkhtmltopdf:

This program will convert the HTML into the PDF format. To make it work you’ll need at least version 0.9 which isn’t installed in Ubuntu 9.10 by default. Just download the static compiled version from the wkhtmltopdf website and place it under /usr/local/bin.

Install the wicked_pdf plugin:

Just install it in the usual Rails way:

git submodule add git://github.com/mileszs/wicked_pdf.git vendor/plugins/wicked_pdf

Additionally a sample configuration file is needed. You could use the plugin’s generator script for it but alas this didn’t work for me with Rails 3.0. Let’s just copy it form the plugin’s directory into config/initializers.

$ cp vendor/plugins/wicked_pdf/generators/wicked_pdf/templates/wicked_pdf.rb config/initializers

and alter the wkhtmltopdf path within it:

  WICKED_PDF = {
       :exe_path => '/usr/local/bin/wkhtmltopdf-amd64'
  }

Add pdf instructions to your controller..

For example I’m using the invoice#index action to render a simple PDF document.

  format.pdf do
          @example_text = "some text"
          render :pdf => "file_name",
                 :template => 'offers/show.pdf.erb',
                 :layout => 'pdf',
                 :footer => {
                    :center => "Center",
                    :left => "Left",
                    :right => "Right"
                 }
  end

We are rendering the view with a predefined footer containing some sample “center”, “left” and “right” strings. The render :pdf call has various options which can be seen on the wicked_pdf homepage.

.. and create PDF templates

The other half of the PDF templates is the view code consisting of a special layout and template for pdf generation.

The layout (app/views/layouts/pdf.html.erb) resembles a normal Ruby on Rails layout file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <%= wicked_pdf_stylesheet_link_tag "pdf" %>
  </head>
  <body>
    <div id="content">
      <%= yield %>
    </div>
  </body>
</html>

The view code should not be too surprising, just place it under app/views/offers/index.pdf.erb :

<div id="someid"><%= @example_text %></div>

Lets also create a simple CSS file (public/stylesheets/pdf.css):

#someid {
  margin-left: 430px;
  display: float;
  height: 150px;
  background-color: green;
  width: 250px;
}

 

This is the whole rendering code.

Reference the PDF view and download it

We still need a reference to the newly created rendernig link, we can easily create this through:

link_to 'Create PDF document', invoice_path(@invoice, :format => :pdf)

When the link is clicked a pdf document will be generated and downloaded.

Conclusion

wicked_pdf allows easy pdf generation in a very Ruby on Rails’ way. It’s free, it works and is easy to employ..

..but not everything is perfect within the wicked_pdf world, especially error handlnig is lacking sometimes. When you’ve debugging initial problems you can expect the only error feedback to be a HTTP return code of 406. Just start with limited controller (rendering) options and double check that you’ve referenced the right view and layout paths and you should be fine.

Using Phusion Passenger to Deploy a Rails Application on Apache

Using Phusion Passenger to Deploy a Rails Application on Apache

In this tutorial, I will explain how to set up Phusion Passenger, configure Apache, and deploy multiple Rails applications on Apache. I assume you are running a Linux box, as most modern-day hosting solutions include a VPS (virtual private server) instance or a dedicated server instance, and you should be comfortable with the basics of using a Linux command line.

Setting Up Phusion Passenger

Phusion Passenger uses mod_rails, a module of Apache, to serve Rails applications via the Apache2 Web server. The first prerequisite for setting up the Passenger module is to install Apache2.

Phusion Passenger can be installed in three different ways. The first way is to install a typical gem like this:

saurabh@saurabh-laptop:~$ sudo gem install passenger
Building native extensions.  This could take a while...
Building native extensions.  This could take a while...
Successfully installed fastthread-1.0.7
Successfully installed passenger-2.2.11
2 gems installed

When the gem is installed, you can install the Apache2 module for Rails. A few other dependencies are required in order to install the Apache2 module. They are apache2-prefork-dev (The Apache2 Development headers), libapr1-dev (Apache Portable Runtime), and libaprutil1-dev (Apache Portable Runtime Utility). Make sure you install all of these as follows before you continue.

saurabh@saurabh-laptop:~$ passenger-install-apache2-module

You will be guided through some installation steps as shown in Figure 1-3:


Welcome to Phusion Passenger Apache 2 Module Installer
Click here for larger image

Figure 1. Welcome to Phusion Passenger Apache 2 Module Installer


Phusion Passenger Apache 2 Module Installer Checking for Required Software
Click here for larger image

Figure 2. Checking for Required Software


Phusion Passenger Apache 2 Module Successfully Installed
Click here for larger image

Figure 3. Apache 2 Module Was Successfully Installed

The second way to install Passenger is from source:

  1. Download the Passenger source from RubyForge and download it to a folder where it will permanently reside, as follows:
    saurabh@saurabh-laptop:/opt$ wget http://rubyforge.org/frs/download.php/69546/passenger-2.2.11.tar.gz
  2. Unzip the downloaded archive like this:
    saurabh@saurabh-laptop:~$ tar xvzf passenger-2.2.11.tar.gz
  3. Change the directory to bin inside the extracted Passenger folder and run the binary to install the Apache2 module, as follows:
    saurabh@saurabh-laptop:~/opt/passenger-2.2.11/bin$ ./passenger-install-apache2-module

The third way to install Passenger is by using the native Deb package. (The steps for this are the same as those shown in Figures 1-3.) This approach is specific to Debian and Debian-based distributions like Brightbox Ubuntu, a UK-based hosting repository that provides a package tested on Ubuntu 8.04.

First, open your favorite editor (nano in my case), so you can add the ppa line to the sources file.

saurabh@saurabh-laptop:~$ nano /etc/apt/sources.list

Next, add the ppa line at the end of the file and add the signature like this:

deb http://apt.brightbox.net hardy main

sudo sh -c 'wget -q -O - http://apt.brightbox.net/release.asc | apt-key add -'

saurabh@saurabh-laptop:~$sudo apt-get update

saurabh@saurabh-laptop:~$sudo apt-get install libapache2-mod-passenger

When these steps are complete, you are ready to serve your applications via Apache2 mod_rails and you can proceed to configuring your Apache server and deploying your app to it.

Apache Configuration

Move the Rails application to the /var/www folder on your server and start editing the Apache configuration file to add a virtual host. Point the document root to the public folder of the application, as follows:

saurabh@saurabh-laptop:~$ nano /etc/apache2/sites-enabled/000-default 

<VirtualHost *:80>
        ServerAdmin webmaster@localhost 

        ServerName www.mywebsite.com
        DocumentRoot /var/www/mywebsite/public
        <Directory /var/www/mywebsite/public>
                Options Indexes FollowSymLinks -MultiViews
                AllowOverride all
                Order allow,deny
                allow from all
        </Directory> 

        ErrorLog /var/log/apache2/error.log 

        LogLevel warn 

        CustomLog /var/log/apache2/access.log combined 

</VirtualHost>

Next, simply start your Apache server like this:

saurabh@saurabh-laptop:~$ /etc/init.d/apache start

Now, navigate to your domain in the browser and you will see your application running in the browser.

Deploying Multiple Rails Applications in Passenger

You can deploy multiple Rails applications in two ways, depending on the type of URI you want to deploy to. The first one is deploying to a sub URL, which looks something like this: www.mywebsite.com/suburl. The second one is deploying to a subdomain, which looks like this:www.subapplication.mywebsite.com.

Let’s take the first way, serving your application at www.mywebsite.com/suburl. Suppose your apps reside in /var/www/mywebsite/ and your document root is set to /mywebsites/. First, create a symbolic link from the Public folder of the app to the directory created inside the document root of the mywebsitesfolder as shown below:

ln -s /var/www/mywebsite/suburl/public /var/www/mywebsite/suburl

You have already seen how to create a virtual host for your Rails app. This is how it looks in this case:

<VirtualHost *:80>
        ServerAdmin webmaster@localhost 

        ServerName www.mywebsite.com
        DocumentRoot /var/www/ mywebsite
        <Directory /var/www/mywebsite>
                Options Indexes FollowSymLinks -MultiViews
                AllowOverride all
                Order allow,deny
                allow from all
        </Directory> 

        ErrorLog /var/log/apache2/error.log 

        LogLevel warn 

        CustomLog /var/log/apache2/access.log combined 

</VirtualHost>

Before proceeding further, verify two things:

  1. Apache has the appropriate permissions for every application directory.
  2. Multiviews is disabled for this folder.

When you are sure of these requirements, add a RailsBaseURI directive to the virtual host configuration as follows. You can define as manyRailsBaseURIs as you want.

<VirtualHost *:80>
        ServerName www.mywebsite.com
        DocumentRoot /var/www/ mywebsite
        <Directory /var/www/mywebsite>
                Options Indexes FollowSymLinks -MultiViews
                AllowOverride all
                Order allow,deny
                allow from all
        </Directory> 

    RailsBaseURI /suburl
    <Directory /var/www/mywebsite/suburl>
        Options -MultiViews
    </Directory>                        

        ErrorLog /var/log/apache2/error.log 

        LogLevel warn 

        CustomLog /var/log/apache2/access.log combined 

</VirtualHost>

When you edited and saved your virtual host configuration, restart the Apache server with the following command:

/etc/init.d/apache2 restart

Conclusion

Phusion Passenger is the most popular way to deploy Rails applications to Apache HTTP Server, because it offers multiple Apache scaling techniques. But its biggest advantage is that PHP apps can run in the same server. So, if a person wants to run his or her WordPress blog in the Rails application, Apache makes that possible also.

About the Author

Saurabh Bhatia has been working with Rails since early 2006 and has a startup company, Safew Labs, that offers Rails consulting. He likes to write clean code, read and write.

Installing kete-tiny_mce

Informacion original en http://github.com/kete/tiny_mce

Instalar el gem:

sudo gem install kete-tiny_mce

Add this to config/environment.rb of your Rails application:

config.gem ‘kete-tiny_mce’, :lib => ‘tiny_mce’, :source => ‘gems.github.com‘

Se agrega al controller:

uses_tiny_mce :o ptions => {

:theme => ‘advanced’,

:theme_advanced_resizing => true,

:theme_advanced_resize_horizontal => true,

:plugins => %w{safari spellchecker pagebreak style layer table save advhr advimage advlink emotions iespell inlinepopups insertdatetime preview media searchreplace print contextmenu paste directionality fullscreen noneditable visualchars nonbreaking xhtmlxtras template imagemanager filemanager },

:theme_advanced_buttons1 => %w{save newdocument | bold italic underline strikethrough | justifyleft justifycenter justifyright justifyfull | styleselect formatselect fontselect fontsizeselect},

:theme_advanced_buttons2 => %w{cut copy paste pastetext pasteword | search replace | bullist numlist | outdent indent blockquote | undo redo | link unlink anchor image cleanup help code | insertdate inserttime preview | forecolor backcolor},

:theme_advanced_buttons3 => %w{tablecontrols | hr removeformat visualaid | sub sup | charmap emotions iespell media advhr | print | ltr rtl | fullscreen},

:theme_advanced_buttons4 => %w{insertlayer moveforward movebackward absolute | styleprops spellchecker | cite abbr acronym del ins attribs | visualchars nonbreaking template blockquote pagebreak | insertfile insertimage},

:theme_advanced_toolbar_location => ‘top’,

:theme_advanced_toolbar_align => ‘left’,

:theme_advanced_statusbar_location => ‘bottom’,

:theme_advanced_resizing => true

},

:o nly => [:new, :create, :edit, :update]

Y a la form en el view se agrega:

:class => “mceEditor”

Y por ultimo se agrega al <head> del application view:

<%= include_tiny_mce_if_needed %>

Documentacion de opciones en:

http://tinymce.moxiecode.com/examples/example_01.php

way of life

Design first, program second is a rule of thumb for most agile RoR projects and something I live by.

If you looking for some help in the design area, here is a good strategy.

Basics

Learn HTML – It’s easy, know the basics and you’ll be fine

Learn CSS – Learn how to style HTML page, like font-colors, backgrounds etc

Learn how to do CSS layouts in HTML – complete a basic 2/3 column layout using DIVs.

Application Development

1) Find a CSS Layout – I’m an expert in html/css but I still use a CSS layout/template to start projects. It saves so much time. I recommend http://matthewjamestaylor.com/blog/perfect-3-column.htm

2) Find a color scheme – Go to http://kuler.adobe.com and find something you like

3) Take a screenshot of the color pallete and the css layout

4) Open the screenshots in Photoshop and use them as a base for a quick mock-up of the layout, get the logo up, columns etc. Write down all the html color codes you used in the layout.

5) Export any images needed to JPEGs to your sites directory

6) Download the Blueprint CSS framework mentioned above. Add it to your sites directory, and read the tutorial.

7) Open the CSS layout in your text-editor (dreamweaver/textmate). Starting hacking it to look like the layout you did in photoshop. Use the colors you wrote down.

8) Create your app framework in Rails

9) Break up the html layout into the view/application.html.erb and the content into the individual controller views.

10) Test and reiterate often.

Copy ideas from every site you like, its the best way to learn.

After that you can learn AJAX and JS but go easy, its not always user-friendly.

Original info:

http://railsforum.com/viewtopic.php?id=20357

Last edited by intrudah (2008-07-19 00:32:18)

http://dmix.ca | Toronto Start-ups, Rails, User Experiance and Indie Music