Installing Nginx with Passenger on Snow Leopard Using MacPorts

Posted by Christopher Rigor on December 17, 2009 
Filed Under Web Development | Comments

Install MacPorts if you don’t have it.

Download and install the Portfile

git clone git://github.com:crigor/admoolabs-ports.git ports
cd ports/nginx-0.7.64-passenger-2.2.8
sudo port -v install

You need to have ruby installed to compile passenger. In case you don’t have ruby, you can also get it from macports.

sudo port -v install ruby

If you have an older version of nginx installed using macports, it might move nginx.conf to nginx.conf.altered. Copy it back to nginx.conf if you need it. You can also use this nginx.conf.

Edit /opt/local/etc/nginx.conf and add the following lines inside http {}

passenger_root /opt/local/lib/passenger;
passenger_ruby /opt/local/bin/ruby;

Change the ruby path if you’re not using ruby from macports.

For each rails app, you need to add the following, also inside http {}

server {
  server_name labs.local;
  root /Users/crigor/admoolabs/labs/public;
  access_log /opt/local/var/log/nginx/labs.local.access.log;
  error_log /opt/local/var/log/nginx/labs.local.error.log;
  passenger_enabled on;
  rails_env development;
}

Check if your syntax is correct.

sudo /opt/local/sbin/nginx -t

If it is, you’ll see

the configuration file /opt/local/etc/nginx/nginx.conf syntax is ok
configuration file /opt/local/etc/nginx/nginx.conf test is successful

Start nginx with

sudo /opt/local/sbin/nginx

You won’t get any output if it starts correctly. Check if nginx is running

ps -e | grep nginx -i
(You should see something like these lines)
nginx: master process /opt/local/sbin/nginx
nginx: worker process
PassengerNginxHelperServer /opt/local/lib/passenger /opt/local/bin/ruby 3 4 0 6 0 300 1 nobody 4294967294 4294967294 /tmp/passenger.10755

MacPorts added a startup item which is disabled by default. To start it,

sudo launchctl load -w /Library/LaunchDaemons/org.macports.nginx.plist

You can stop nginx with

sudo launchctl stop org.macports.nginx

but it would just be started right away. If you want it to remain stopped, use

sudo launchctl unload /Library/LaunchDaemons/org.macports.nginx.plist

When you make changes to the config, reload the config with

sudo /opt/local/sbin/nginx -s reload

Check the other nginx options using

/opt/local/sbin/nginx -h

One more thing…
When you add a rails or rack app, you need to specify a different server_name. You need to add it to /etc/hosts

127.0.0.1 localhost labs.local

Don’t you think it would be great if you can handle this automatically? Me too. Stay tuned for more. This shouldn’t be a pane pain. ;)

Install PHP 5.2 on Ubuntu Dapper

Posted by Christopher Rigor on November 11, 2009 
Filed Under Web Development | Comments

The repositories on Ubuntu Dapper don’t have php 5.2. To install php 5.2, I added the hardy repositories.

vi /etc/apt/sources.list

add the repositories
deb http://us.archive.ubuntu.com/ubuntu/ hardy main restricted
deb-src http://us.archive.ubuntu.com/ubuntu/ hardy main restricted

then run
sudo apt-get update
sudo apt-get install php5

This tried to install and upgrade a lot of packages including apache. I really needed php 5.2 and since the server is a development server, I accepted all the changes.

Sinatra: Suppress Newline in ERB

Posted by Christopher Rigor on November 11, 2009 
Filed Under Web Development | Comments

To suppress newline in ERB on Rails, you just add a dash on the closing tag -%>. In Sinatra, as of version 0.9.4, adding a dash doesn’t work. This has been fixed recently on the tilt gem version 0.3 which Sinatra uses for templates. You also need Sinatra newer than 0.9.4, which doesn’t exist yet so you need to get Sinatra from source.

You need to get tilt 0.3 from gemcutter.org.
sudo gem install --no-ri --no-rdoc tilt --source=http://gemcutter.org

To get the latest Sinatra
cd myapp
git clone git://github.com/sinatra/sinatra.git

and add it to the LOAD_PATH
$LOAD_PATH.unshift File.dirname(__FILE__) + '/sinatra/lib'

To set the dash as the ‘trim’ character, add
set :erb, :trim => '-'

RailsConf 2009

Posted by Christopher Rigor on May 4, 2009 
Filed Under Ruby on Rails | Comments


RailsConf 2009

Sortable Tables

Posted by Gerald Abrencillo on April 29, 2009 
Filed Under Ruby on Rails, Web Development | Comments

Rails has a helper function called sortable_element that generates ajax code to allow you to sort lists by dragging and dropping elements. The function defaults to handle lists and if you want to sort tables you should take note of the :tag option.

<%= sortable_element 'my_list',
:url => { :action => "order" },       
:tag => 'tr' %>

This should allow you to sort tables and hopefully save you from a big headache.

Rack::Flash

Posted by Christopher Rigor on March 20, 2009 
Filed Under Uncategorized | Comments

One advantage of using rack is having access to rack middleware. rack-flash is a middleware which you can use for flash hash on your rack apps.

If you’re using sinatra, the syntax is similar to rails. Check out the rack-flash page here.

I added rack-flash to my sinatra app. Check out the git commit. Since rack-flash uses the session, don’t forget to add Rack::Session::Cookie.

Watch the video of Jon Crosby’s talk In a World of Middleware, Who Needs Monolithic Applications? at Mountain West Ruby Conference 2009 for more on rack middleware.

G-Edit and Shell to make editing multiple views easier

Posted by Eumir Gaspar on March 3, 2009 
Filed Under Web Design, Web Development | Comments

I recently was given a task to change alt tags in ALL of our companies images for better SEO purposes(I do think it won’t impact that much, but I guess they’re thinking any additional impact is better than nothing). I was given an excel file with about 300 images with their current alt tags and their proposed replacements. Yes, another copy and paste task.

What really blows is I don’t have a way of knowing where ALL the instances of the images are, so I had to use my now current favorite shell command to search where a said image is placed in a view:

grep -r -i imagename *

What that does is look which file and line in that file that the imagename string is mentioned. I usually just look for the name itself, and not the extension and the sub-folder, so to look for logo.jpg, I just put

grep -r -i logo *

That returns all the files where logo is mentioned(so I guess you’ll also get non-image results). What’s good about this is that it looks for both the instances when the image was rendered using <img src> or <%= image_tag %>

Seeing my first search resulted in 11 hits(I think the options -r -i of grep searches incrementally so it will also look in all sub-folders of the directory you are in), it occurred to me that this might take a while, as I also had to look for all the files, etc. I asked my friend to help in some shell-fu and here’s what we came up with:

gedit `grep -r -i -l imagename *`

What does this do? Simple, the -l option just lists the filename of the file where imagename was seen(as opposed to including the actual line where it was seen), and the grep enclosed in “ means that the output will be a string…which in turn is sent to gedit. The result? It opens up all the files that contains imagename and that my friends, made my life a wee bit easier in changing the alt tags in all the instances of a said image.

*EDIT:
By the way, I know there is an easier way, like maybe replace all instances of said string in all files or something, but I haven’t found out about it yet. If I do, I’ll be sure to make a new post about it :P

Sinatra, Datamapper, and Haml

Posted by Christopher Rigor on February 13, 2009 
Filed Under Web Development | Comments

I recently tried Sinatra and what’s a better way to learn a new framework than to create an app.

If you want to learn sinatra, the README will quickly show you what you can do with this framework.

I haven’t used Datamapper so I took this opportunity to learn it as well. You just need to require ‘dm-core’. That’s it. If you want to put your models on a separate file, you have to require that as well. If you’re using Rails, you’re probably used to models being available right away. I also used haml instead of erb.

The code is available at github. The Sinatra book has a list of Real World Applications. I looked at the seinfeld app as a basis for the structure.

There is more I want to learn in Sinatra. Since it uses Rack, I want to try using the different Rack Middleware available.

Paperclip

Posted by Christopher Rigor on January 5, 2009 
Filed Under Ruby on Rails, Web Development | Comments

Paperclip recently made some changes making it more flexible.

Paperclip is a library for ActiveRecord used for file attachment. The most common use is for uploading images. It can optionally create thumbnails when you upload images. Paperclip requires ImageMagick for resizing images but it doesn’t require any Ruby libraries like RMagick or MiniMagick.

You can install paperclip as a gem or as a plugin. The paperclip gem needs right_aws, mocha, and shoulda.
gem install right_aws
gem install mocha
gem install thoughtbot-shoulda --source=http://gems.github.com
gem install thoughtbot-paperclip --source=http://gems.github.com

To install the plugin, run ./script/plugin install git://github.com/thoughtbot/paperclip.git.

Let’s say you have a User model and you want to add an avatar. On the users table, you need to add avatar_file_name.

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :login
      t.string :avatar_file_name
    end
  end

  def self.down
    drop_table :users
  end
end

On user.rb, add has_attached_file

class User < ActiveRecord::Base
  has_attached_file :avatar
end

You just need to set avatar to an uploaded file and paperclip will handle the rest. On app/views/users/new.html.erb

  <% form_for :user, @user, :url => users_path, :html => { :multipart => true } do |form| %>
    <%= form.text_field :login %> <br />
    <%= form.file_field :avatar %> <br />
    <%= submit_tag 'Save' %>
  <% end %>

:multipart => true is needed when uploading files. Then on app/controllers/users_controller.rb

  def new
    @user = User.new
  end

  def create
    @user = User.create(params[:user])
  end

@user.avatar.url will give you the url of the uploaded image. That’s all the code you need to use paperclip. There are more options for creating thumbnails, validating the model, and post-processing.

The uploaded files will be saved on RAILS_ROOT/public/system/:attachment/:id/:style/:basename.:extension. On my computer the file is saved on RAILS_ROOT/public/system/avatars/1/original/image.jpg.

As you can see, the default style is original. To add more ’styles’,

class User < ActiveRecord::Base
  has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end

When you upload the image, paperclip will save the original image, and resize the image to medium and thumb. On RAILS_ROOT/public/system/avatars/2, you will see the directories original, medium and thumb.

To get the medium and thumb images, you will use @user.avatar.url(:medium) and @user.avatar.url(:thumb).

On the users table, you can also add avatar_content_type (string), avatar_file_size (integer), and avatar_updated_at (datetime). These fields will be populated by paperclip automatically.

I will discuss validation and other post-processing options on my next post.

Rails for Designers 101 – Step by Step Version

Posted by Eumir Gaspar on December 30, 2008 
Filed Under Ruby on Rails, Tutorial, Web Design, Web Development | Comments

This is more of a ‘tutorialized’ version of my previous post. Here, I’ll be sharing how I made my ‘portfolio/haml converter’ rails application, since I unfortunately assumed that anyone reading that post also knew what I knew. This time though, I’ll be assuming nothing, just that you are a designer and you just want to try coding in Haml for a change(good for you!) even if you don’t know squat about rails.

For starters, if you don’t have Rails yet, I suggest either installing Rails the hardcore way, or take the easy way out like I did: just download InstantRails. Okay, after you’re done with that part(I’ll be assuming you also took the easy way out) just unzip that into your root directory(I’m using Windows *gasp* so mine is located at C:/Instantrails/)

Now, all you have to do is bring up a command line(windows key + r, then type cmd), go to your Instantrails folder(type ‘C:/Instantrails/’) then type ‘use_ruby’. You’ll know you did the right thing when the directory changes to C:/Instantrails/rails_apps(just realized it’ll be better with screenshots…but I’ll do that later)

OKay, next in line is installing haml. Ready? Just type:

gem install haml

That’s it! Haml should be automatically downloading now. As you wait for that one, you can open up a new command line, go to your IR(due to laziness I’ll be calling Instantrails IR from now on) folder again, type use_ruby again and then type

rails myhamlizedportfolio

Actually you can name it anything you want. Doesn’t really matter(I sugest you pick a short name though). This will effectively create a blank rails app for you. And by that I mean it will create a folder named myhamlizedportfolio in your rails_app folder, complete with all the folders needed for a blank rails app. Next would be to install haml as a plugin for your portfolio app(you should still be in C:/Instantrails/rails_app when you do this):

haml --rails myhamlizedportfolio

Easy, right? Next, you just have to tell rails that you won’t be needing any database of sorts. So goand open the myhamlizedportfolio/config folder. Open environment.rb(with your favorite text editor – notepad) and look for the following lines

# Skip frameworks you're not going to use. To use Rails without a database  
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]

Just take out the ‘#’ of the third line like so:

# Skip frameworks you're not going to use. To use Rails without a database
# you must remove the Active Record framework.
config.frameworks -= [ :active_record, :active_resource, :action_mailer ]

Save this and close the file. Delete database.yml in that same folder by the way – you won’t be needing that. Next up is to fix your routes(if you want to understand what you’re actually doing, I suggest learning basic rails first like a good citizen, but if you can’t be bothered, then just follow these steps and believe it will work :P ). Open up routes.rb with notepad(it’s still in the config folder) and add this line right after the first line like so:

ActionController::Routing::Routes.draw do |map|
map.connect 'projects/:id', :controller => 'projects', :action => 'index'
 

That just basically means that to access your projects all you have to do is go to http://localhost:3000/projects/projectnamehere. More on that later. For now, save and exit again and you’re done with the config folder. We’re almost there! 

Now go back to your command line and while in your project directory(in our case, myhamlizedportfolio) and type

ruby script/generate controller projects

This will generate some files but what we really want to focus on is the newly generated projects_controller.rb located in myhamlizedportfolio/app/controllers. Open this file up with notepad, as usual, and well, just replace all the code there with this:

class ProjectsController < ApplicationController
def index
render :action => "#{params[:id]}/index"
end
end

Don’t worry if you don’t understand. That’s just a ‘continuation’ of what we did with routes.rb, basically telling our app that going to http://localhost:3000/projects/projectnamehere means it should render the page with the same name located in your views(again, more on that soon).

Actually you’re done setting up. You can now start coding with Haml. To start, let’s make a design project named RedHelloWorld. Go to your views folder(myhamlizedportfolio/app/views) and make a new directory named RedHelloWorld. Open up notepad again and type these:

!!!

%html{:xmlns => "http://www.w3.org/1999/xhtml", "xml:lang" => "en", :lang => "en"}
  = yield :layout

If you have reviewed Haml, that just basically creates the basic headers for your html page. Save that as application.haml and save it in the views/layouts folder(also delete application.html there if it exists). Create a new document yet again and type the following:

%head
  %meta{"http-equiv" => "content-type", :content => "text/html;charset=UTF-8"}
  %title hamlicious home!
  = stylesheet_link_tag 'demo'

  %body
    %h1.red HELLO WORLD!

Just by looking at the code, you’ll already know that Haml really makes things easier for you. A lot of time is saved since you won’t be needing to type the appropriate closing tags for each div, or other html tag out there. Save that file as index.haml and save it in views/RedHelloWorld (yup, create a folder with that name).

Next up, is your sass(css) file. Open up a new text file again and type:

.red
  :color #ff0000

Save that as demo.sass and save it in myhamlizedportfolio/public/stylesheets/sass/(you’ll have to create a sass folder). While you’re at it, also delete the index.html in your public/ folder. And now all you have to do is run and test your app! Go to your command line(yet again) and after use_ruby and going to your project directory, just type

ruby script/server

Wait til ou see the lines:

** Mongrel available at 0.0.0.0:3000
** Use CTRL-C to stop.

And that’s it. You can now access your demo by opening up your browser and going to http://localhost:3000/projects/RedHelloWorld

Hopefully that’ll work. Any problems, leave a comment :P Oh and before I forget, if you need the html and css files(like I do – I just like coding in Haml/Sass) just view the page, view the source and copy paste it in a blank document and save it as .html(in another directory of course). Get the .css file that will be generated in myhamlizedportfolio/public/stylesheets/ and use that for the css file of your project. Enjoy!

More on customizing this app sometime in the future. (namely how to make a “homepage” where you have a list of all your hamlized projects.

← Previous PageNext Page →