Paperclip

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

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.

Rails for Designers – Using Haml/Sass for all projects

I have recently acquired a newfound drive for designing sites(as opposed to my earlier desire to be a great design/backend mediator). As of now, due to some reent developments, I am the main designer for most of our projects, not to mention some of which are personal or freelance related. One pet peeve I had though was the diversity of my projects: meaning some were in rails(of course I was happy with fixing views and adding some javascript-fu), php, and some, just plain XHTML/CSS.

With that said, things can get pretty messy when multiple projects are at hand and I have to shift continually from regular XHTML/CSS coding and HAML/SASS. Though it is not a great hindrance, having to keep remembering which language I was using was kinda annoying. Add to the fact that I work twice(or thrice) as fast using HAML/SASS and the tiny nuisance becomes a glaring problem(for me that is).

At first, I made a semi-solution. A compromise of sorts: since I use the ever cool Elements CSS framework(actually I just use the general html structure and a modified reset.css which I have discussed with the author, Ben Henschel), my html is usually almost ready-made so my usual focus is just the css file. For projects that used Rails(I still didn’t have a solution for ones that didn’t) but not Haml, I just installed Haml on my part, and continued developing with Sass. Since Sass generates a .css file, that’s the one I usually push in repos(if the client can’t be bothered with installing Haml).

But that was just for Rails projects. The problem lies with normal design projects or ones that used PHP. Recently, I had another solution(I doubt this is the most efficient though): make a blank rails app and keep using Haml/Sass for myself and when done with coding the design, I just do a view source, copy-paste the whole thing in a blank html file, modify the paths for the css and javascripts, then just copy the images/stylesheets/javascripts folders in my public/ folder. Nifty!

It was a good thing for me, since now, I can just keep coding in Haml and Sass to my heart’s content. Thing is, I just realized I just can’t keep making blank rails apps for each project! So the plan was to separate the projects in self-titled folders and just use some routes.rb and controller magic suggested by my friend Greg:

In routes.rb:

map.connect 'projects/:id', :controller => 'projects', :action => 'index'

and in my single controller named projects_controller.rb:

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

With that, I can just go to say /projects/projectA and it will then render projectA. This also works as a portfolio and future-reference of sorts for me, which is excellent. Now I only need to think of a good way to organize the images and the stylesheets(especially the javascripts) so they won’t interfere with each other but basically, I’m just planning to put them in separate folders too(except for reset.css and jquery.js of course – every project needs that!)

Extra note:
Forgot to mention that I had to add 

config.frameworks -= [ :active_record, :active_resource, :action_mailer ]

since I wasn’t using any db.

Rack-based Session Stores on Rails

Rails edge is now using Rack-based session stores. That means you can access the same session on any Rack applications. Read about it on the Rails blog.

Nothing changes though on how you use sessions on Rails. On your Rails app, you’ll have something like

session[:user] = some_user_id

Let’s see how we can access the same session on a Rack application. You can read about Rack here.

Rack handles session using Rack::Session::Cookie. Create a file config.ru

use Rack::Session::Cookie, :key => '_railssession_session', :domain => 'railssession.labs.admoolabs.com'
run Proc.new {|env| [200, {"Content-Type" => "text/html"}, "Rack session 'user' has a value of #{env['rack.session'][:user] || 'nil'}."]}

The key should be the same key that you used on config/environment.rb on your Rails app.

Check out the demo. Set session[:user] on the Rails app, then view the session on the Rack app.

Scraping bot

I just recently found the joys of scraping. Yes, the “technique” is a bit underhanded, but it sure is fun. I guess as long as you don’t profit off of it, it’s ok(and it doesn’t affect the site you’re scraping). If you scraped a site just to present it in a different design(like scrape all the news off CNN and then make a site called BNN or something and then charged users with a smaller fee), then yeah, that’s just plain dirty.

I scrape for fun and that’s it. Anyways, there I was, scraping movie schedules off the only movie schedule site that I know of( clickthecity.com ) and suddenly, I had an idea. What if I just made an RSS feed for a movie house that I liked? It would be just so cool since clickthecity(or CTC) doesn’t have an RSS feed. So I started researching about makign RSS feed, and while doing so, Topher brought about the idea of making a bot. He showed me how jabberbot and from there I went on and played around with it.

To make the scraper, I used the Rubyful-soup plugin for Ruby on Rails(along with Mechanize). Using it was easy, and the main problem actually was how to traverse the atrocious table layout of clickthecity. Once I got over that hurdle though, getting the info I wanted was easy. And what did I need? I only just needed the date of the showtimes(so I’ll know if it was the latest update), the location of the cinemas(the mall the cinemas were located), the cinema name(or number), the movies being shown on each movie house,  and the show times of each. These were saved into a database I made(I had a bit of a trouble in putting them in, especially since there were movie houses that had two different movies being shown the same day)

Next was the bot itself. Like I said, I used jabberbot, which was also a handy plugin for Ruby on Rails. The syntax was easy, and this was the easiest part. I made a new google account just for the bot and now it is up. I still have yet to make it work on yahoo messenger(Topher tried it and it didn’t work, but I haven’t tried it for myself yet) so I’ll just have to settle with Gtalk.

The flow of the program is simple: scrape the data from clickthecity.com and then save it to the database(done using a rake task I made). I have yet to automate these tasks, along with the connection of the bot(I still have to manually start it using another rake task). Anyways, after manually callign the rake tasks for scraping the site and starting the bot, movieschedule-bot is ready to go.

So far, I only added a select few movie houses that me and my friends usually go to. You can actually add movieschedules (yes, google mail) to your gtalk/gmail contact list and start using it(don’t worry about down times. that just means I am currently updating/restarting it – try again after five minutes if it doesn’t work) Don’t try to spam it though as right now it is running from my local machine. I have yet to upload it to my free Heroku account and make it run the bot forever.

So there you have it. A scraper bot. There are a LOT of other uses for this, like a thesaurus bot, wikipedia bot, imdb bot or something but that’s for another discussion. As you can see, bots can be useful too! Right now, movieschedules is looking for more friends. Be kind to it!

To start using  movieschedules, just add it to your Google contact list then type “help” and send it. It will return you a list of commands that are currently available. Have fun!

Railsconf 2008

I will be at Railsconf 2008 at Portland. I still haven’t finalized the sessions I’m attending but I’m sure it will be great.


RailsConf 2008

Alphabar on Rails

I am working on this little project right now using Ruby on Rails and I ran into some trouble with the alphabar plugin. First, alphabar uses the with_scope method which, since Rails 2.0 I believe, has been protected, giving me some errors since I froze my Rails version. I was able to overcome this obstacle by using the send method instead. Just change the last part of the find method of the plugin from:

model.with_scope({:find =&gt; {:conditions =&gt; conditions}})
{model.find :all}

to:

model.send(:with_scope, {:find =&gt; {:conditions =&gt; conditions}})
{model.find :all}

After I finally got that to work the plugin was very useful, although the alphabar was limited to letters and blank which is useful if you don’t need numbers. To accomodate numbers just add this to the alphabar helper:

('0'..'9').to_a.each do |i|
slots &lt;&lt; i
end

Theoretically it should work for any character but I haven’t tried it yet.

So there you have it. Hoepfully somebody having trouble with this plugin will find this post useful.

Run from Capistrano

You can run shell commands from capistrano using the run method. For example, to create a symlink from the shared directory to the current directory, you’ll write

run "ln -nfs #{deploy_to}/shared/config/database.yml #{release_path}/config/database.yml"

run can also take a block like this

run "rsync /path/to/file host:/path/to/file" do |channel, stream, text|
  logger.info "[#{stream}] #{text}"
  output = case text
  when /\bpassword.*:/i
    "#{password}\n"
  when %r{\(yes/no\)}
    "yes\n"
  end
  channel.send_data(output) if output
end

When you run a command it might ask for your password. To handle this in capistrano, use send_data to send a response.

Check lib/capistrano/recipes/deploy/scm/subversion.rb on the capistrano gem to see how capistrano handles subversion commands.

RailsConf 2007 Keynote Videos

The keynote videos from RailsConf 2007 are now available online. Get them here.

DHH’s presentation is available here. DHH made a live demo showing REST and made a mistake. He said he wanted to show how easy it is to debug in Rails. I say the same thing when something goes wrong in my live demos. :)

nl2br in RoR

I recently found out that line breaks are not recognized when displaying a large block of text on the view (e.g. a post body). In PHP this was handled by the nl2br method but I had no luck finding a similar function in RoR. So I did what any sane person would do, create one myself. I placed this method in our model to format a particular field but it seems a better choice to put it in a helper.

def nl2br(text)

return text.gsub(/\n/, ‘<br/>’)

end

And there you have it, your very own nl2br method. Either you just found something really useful or I just wasted 2 minutes of your time. If anyone has a better solution or if I missed a function for this let us know by dropping a comment.

← Previous PageNext Page →