Ruby on Rails
Last edited June 6, 2008
More by Adam Loving »
Downloading a Remote Image and Saving it with AttachmentFu

I had some issues this week figuring out how to save a file using AttachmentFu. It is well suited to handling files uploaded via a Web form, but when you load a file in programmatically, it isn't obvious what object properties need to be set. Here is what I ended up with.

response = HttpClient.default.request(url)
mugshot = Mugshot.new
temp_file_name = mugshot.write_to_temp_file(response.body)
mugshot.temp_path = temp_file_name
mugshot.content_type = "image/#{content_type}"
mugshot.filename = "imported_photo.#{content_type}"

if person.mugshot
    # remove existing database records of files for this person
    thumbnail = Mugshot.find_by_parent_id(person.mugshot.id)
    thumbnail.destroy
    person.mugshot.destroy
end

mugshot.person = person
mugshot.save
 
Labels: rails, attachmentfu
Q: How do you stub a method call for a rails unit test such that it returns a different value the second time it is called?

A:  stubs(:foo).returns(1,2)
returns 1 the first call, 2 the second, etc.
Q: What is the rake command to run a single rails unit test?

A: There is none, use ruby test/unit/my_test.rb
Which version of Ruby and Rails am I running?

Use these commands to figure out what versions you are running:

$ ruby -v
$ gem list

By default, Rails will append all asset paths with that asset‘s timestamp. This allows you to set a cache-expiration date for the asset far into the future, but still be able to instantly invalidate it by simply updating the file (and hence updating the timestamp, which then updates the URL as the timestamp is part of that, which in turn busts the cache).

It‘s the responsibility of the web server you use to set the far-future expiration date on cache assets that you need to take advantage of this feature. Here‘s an example for Apache:

# Asset Expiration ExpiresActive On

<FilesMatch "\.(ico|gif|jpe?g|png|js|css)$">

  ExpiresDefault "access plus 1 year"

</FilesMatch>

Also note that in order for this to work, all your application servers must return the same timestamps. This means that they must have their clocks synchronized. If one of them drift out of sync, you‘ll see different timestamps at random and the cache won‘t work. Which means that the browser will request the same assets over and over again even thought they didn‘t change. You can use something like Live HTTP Headers for Firefox to verify that the cache is indeed working (and that the assets are not being requested over and over).

Labels: ruby regex
Where are gems installed? Where is rfacebook?

/opt/local/lib/ruby/gems/1.8/gems/rfacebook-0.9.7/lib

or:

:/opt/local/bin$ find . -name "*rfacebook*"
Ruby: using send_file and send_data to relay files from one site through another
www.ruby-forum.com/topic/98626
 
Cache and relay images using:

require 'uri'

class ImagesController < ApplicationController
  # relays remote images so that we can encrypt them
  def index
    data = open(params[:src])
    send_data data.read, :type => data.content_type, :disposition => 'inline'
  end
end

gsub  is powerful

One of these days I really have to get better at regular expressions

    output = description
  
    unless output.nil?
      r = /src=\"?(http:\/\/[^\s\">]*)/
      output.gsub!(r){|s| "src=\"/images/?src=#{CGI::escape($1)}" }
    end
   
    output
 
Labels: gsub, url encoding, regex

In Ruby on Rails, there are three ways to do pagination:

  • 1. Simple pagination
  • 2. Custom pagination
  • 3. Plug-in pagination

Pagination will always take place in the Controller, where you’ll both find the records in the database to display and determine the pagination information. The View will take care of displaying the results of the pagination, but the heavy lifting will already be done. For that reason, let’s hold off on looking at how to display pagination results in the View until we’ve examined the first two types of Rails pagination.

Labels: rails, activerecord

When sending mail through ActionMailer/rails, @reply_to is not a valid way to set the reply to address. You must

@headers["reply-to"] = reply_address

 ActionMailer reply-to

Set up Rails to work with SSL protocol

The following steps were required to set up the rails app to work with the SSL protocol.

Make sure that the SSL plug-in for Rails is installed.

ruby script/plugin install ssl_requirement

Next edit the ApplicationController, add the line ‘include SslRequirement ‘

class ApplicationController < ActionController::Base

include SslRequirement

Now you can set policies for individual actions in each of the controllers.

EG

In the AuthController we want the login and the authenticate action accessible via SSL only.

class AuthController < ApplicationController

 

ssl_required :login, :authenticate

 
Labels: rails
Make Mongrel Reconize an HTTPS request
blog.innerewut.de/2006/06/21/mongrel-and-rails-beh...

After poking around in the ActionController sources there seems to be a much better and easier way. Just set this variable (in httpd.conf) and delete the before_filter:

RequestHeader set X_FORWARDED_PROTO 'https'
Labels: mongrel, rails
/etc/init.d/mongrel_cluster
 Mongrel Tutorial
How to use GMail SMTP server to send emails in Rails ActionMailer
www.stephenchu.com/2006/06/how-to-use-gmail-smtp-s...
Turns out GMail supports only SSL SMTP mailing service, meaning if you cannot create a SSL connection to its SMTP server, you cannot send email through them. My Rails and Ruby (1.84) version do not yet support creating a SSL SMTP connection through Net::SMTP. DHH writes about how to do so through installing msmtp here, but we developers just obviously love options =)

The dynamic nature of Ruby allows me to enhance the functionality of that class. I found the following code from a couple Japanese posts here and here on the web (fairly low Google ranking). Pasting them in my /vendor/plugins as follow:
 I couldn't get this to work
Ruby on Rails URL Mapping Cheat Shet
www.blainekendall.com/uploads/RubyOnRails-Cheatshe...
 good cheat sheet for beginners
Beginners: File uploads and rendering images to the database - Rails Forum - Ruby on Rails Help and
www.railsforum.com/viewtopic.php?pid=23884
used Rails' send_data method to render the binary image to the browser.

The send_data method can take several options:

:filename - suggests a filename for the browser to use.
:type - specifies an HTTP content type. Defaults to application/octet-stream.[/coplor] We've used the existing [color=red]content_type information that was stored in the database when we saved the image
:disposition - specifies whether the file will be shown inline or downloaded. Valid values are inline and attachment (default). We want the image displayed in the browser, so we've used inline.
:status - specifies the status code to send with the response. Defaults to 200 OK. We don't really need to worry about this today.
 used this to guard link to installer download
Delete Rails Session Files

 rake db:sessions:clear


 to delete all those files in the tmp/sessions directory
Rough translation of .net terms to Ruby terms  

MasterPage = Layout

this is going to take more thought... ;)


Ruby has some methods for converting between classes:

Method Converts
FromTo
String#to_i String Integer
String#to_f String Float
Float#to_i Float Integer
Float#to_s Float String
Integer#to_fIntegerFloat
Integer#to_sIntegerString
The content on this page is provided by a Google Notebook user, and Google assumes no responsibility for this content.