scriptrunner’s posterous

Tech Tidbits 

Heroku, Sinatra, and Gmail

To send email from Sinatra (or from any Ruby app that needs to send email, for that matter), there's nothing better than the super simple-to-use Pony, (written by Adam Wiggins, now maintained by Ben Prew). It uses sendmail by default, but also can use SMTP if sendmail isn't available.

At one point Pony didn't support SMPT/TLS, which is required for Gmail. Consequently, you'll see a few blog posts with workarounds using forks of Pony. However, Pony now supports SMTP/TLS and there's even a Gmail example in the docs.

From the Pony docs:

Pony.mail(:to => 'you@example.com', :via => :smtp, :smtp => {
  :host   => 'smtp.gmail.com',
  :port   => '587',
  :tls    => true,
  :user   => 'user',
  :password   => 'password',
  :auth   => :plain # :plain, :login, :cram_md5, no auth by default
  :domain => "localhost.localdomain" # the HELO domain provided by the client to the server
})

To use Pony on Heroku, simply add pony and smtp_tls to the gems maniftest (.gems):

pony
smtp_tls

Filed under  //   sinatra heroku gmail  

Comments [0]

Vim Tip: Comment out multiple lines

Comment:

  1. Select the lines to be commented using "VISUAL BLOCK" (CTRL-V).
  2. Press 'I' (SHIFT-I), which will allow insert before all highlighted lines.
  3. Enter your comment character. (in my case, # for Ruby)
  4. Press ESC.

Uncomment:

  1. Select the lines to be uncommented using "VISUAL BLOCK" (CTRL-V).
  2. In command mode, press 'd' to delete.

And of course, there's a plugin as well: ToggleComment plugin for vim 

Filed under  //   vim  

Comments [0]

Compile Gnuplot on Mac Snow Leopard

There is an incompatibility between Gnuplot and the readline library shipping with Snow Leopard (and 10.5).

If you get these errors:

Undefined symbols:
"_rl_ding", referenced from:
_alert in mouse.o
"_history_list", referenced from:
_write_history_list in history.o
"_rl_complete_with_tilde_expansion", referenced from:
_main in plot.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make[3]: *** [gnuplot] Error 1
make[2]: *** [all-recursive] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2

Then configure like this:
./configure –with-readline=builtin

Filed under  //   gnuplot mac  

Comments [0]

Sending email with Ruby on Rails 2.3.2+ and Gmail

I've seen several posts on using Gmail with Ruby on Rails ActionMailer, but had to go through a little trial and error to get it to work.

First, you'll need collectiveidea's action_mailer_optional_tls plugin:

script/plugin install git://github.com/collectiveidea/action_mailer_optional_tls.git

Next, you'll need to create a initializer file for ActionMailer (a lot of blog posts show this added to environment.rb, but I couldn't get it to work until I moved everything to an initializer file):

config/initializers/gmail_smtp.rb
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:enable_starttls_auto => :true,
:address => "smtp.gmail.com",
:port => 587,
:domain => "yourdomain",
:authentication => :plain,
:user_name => "yourgmailusername",
:password => "yourpassword",
:tls => :true
}
ActionMailer::Base.perform_deliveries = :true
ActionMailer::Base.raise_delivery_errors = :true
ActionMailer::Base.default_charset = "utf-8"

Note: though Rails 2.3 is supposed to eliminate the need for this plugin, I still had to include it with Rails 2.3. I believe I read it will work with Ruby 1.8.7, but not 1.8.6, but haven't had time to test it.

http://douglasfshearer.com/blog/gmail-smtp-with-ruby-on-rails-and-actionmailer

Filed under  //   ruby gmail  

Comments [0]

HTTP Load Testing/Tsung

Comments [0]

Symbol#to_proc (&:)

If you’ve ever seen “&:” and wondered what it does, then here’s a quick overview of what this little shortcut can do. I’ve provided a simple example without going too deep into the details. (but see the links at the end of the post for more information)

For our example we’ll take an array of words and return a new array where each word has been converted to uppercase.



#!/usr/bin/env ruby


tubbies = ["Dipsy", "Lala", "Po", "Tinky Winky"]

# using map and a block
tubbies_upcased = tubbies.map { |tubby| tubby.upcase }
p tubbies_upcased

# using Symbol#to_proc
tubbies_upcased = tubbies.map(&:upcase)
p tubbies_upcased

In both cases, the output is the same:

["DIPSY", "LALA", "PO", "TINKY WINKY"]

For more info, check out these links:
http://pragdave.pragprog.com/pragdave/2005/11/symbolto_proc.html
http://www.dcmanges.com/blog/29
http://memerocket.com/2007/08/02/ruby-symbolto_proc-dont-forget-it/
http://blog.jayfields.com/2007/01/ruby-invoking-method-with.html

Filed under  //   ruby  

Comments [0]

Ruby Tip #1: No braces required to interpolate global, instance, or class variables

Right there on page 15 of the Pickaxe is where you’ll find today’s tip. When interpolating variables within a double quoted string, we typically use #{var_name} to interpolate variables. Ruby provides a shortcut for global, instance, and class variables (but not locals), making the brackets are optional.

#!/usr/bin/env ruby
dipsy_color = 'green'  # local
$lala_color = 'yellow' # global
@po_color   = 'red'    # instance
@@tinky_winky_color = 'purple' # class

puts "Dipsy is #{dipsy_color}"
puts "Lala is #$lala_color"
puts "Po is #@po_color"
puts "Tinky Winky is #@@tinky_winky_color"</code>

This produces the following output:

Dipsy is green
Lala is yellow
Po is red
Tinky Winky is purple

For what it’s worth, I prefer the readability of the brackets. It’s just one of those little things you may have missed…

Filed under  //   ruby  

Comments [0]

Rendering different layouts with Sinatra

A few days ago I posted Explicit layouts for Sinatra.

There was a post (Rendering different layouts with Sinatra) a few days ago on GITTR that uses a similar technique, though they use one method per specific layout - it looks a cleaner than what I did, though if you have dozens of different layouts (probably not likely) you might want to go with passing the layout name as a param as I did.

I simplified my code and it now looks like the GITTR example:

def erb_special(template, layout, options={})
  erb template, options.merge(:layout => 'layouts/special')
end

get '/special/?' do
  erb_special :'special/index'
end

Filed under  //   sinatra  

Comments [0]

50+ Ruby-related Blogs to Read

50+ Ruby-related Blogs to Read

Filed under  //   ruby blogs  

Comments [0]

Testing nested resources with rspec

I’ve been using rspec quite a bit lately, but ran into a small roadblock when I needed to test nested resources in Rails. After a quick Google search and a few IMs later, here’s the solution I came up with. (These tests cover the index action of the nested resource)

This contrived application will use a classic example, posts have many comments, and a comment belongs to a post.

Create a test rails app and <em>cd</em> into the directory of the newly created app:

$ rails nestedresourceapp
$ cd nestedresourceapp

Next, install the rspec and rspec-rails gems (http://wiki.github.com/dchelimsky/rspec/rails):

$ ruby script/plugin install git://github.com/dchelimsky/rspec.git -r 'refs/tags/1.2.7'
$ ruby script/plugin install git://github.com/dchelimsky/rspec-rails.git -r 'refs/tags/1.2.7.1'
$ ruby script/generate rspec

Generate the Post and Comment rspec scaffolds:

$ script/generate rspec_scaffold Post
$ script/generate rspec_scaffold Comment

Add the associations to the models:
# app/models/post.rb

class Post &lt; ActiveRecord::Base
  has_many :post
end

# app/models/comment.rb

class Comment &lt; ActiveRecord::Base
  belongs_to :post
end

Modify the routes file to include the nested resources:
# config/routes.rb

map.resources :posts do |post|
  post.resources :comments
end

Update the migrations to include a few basic fields:
# db/migrate/20090716010730_create_posts.rb

class CreatePosts &lt; ActiveRecord::Migration
  def self.up
    create_table :posts do |t|
      t.string "title"
      t.text "body"
      t.timestamps
    end
  end

  def self.down
    drop_table :posts
  end
end

# db/migrate/20090716010737_create_comments.rb

class CreateComments &lt; ActiveRecord::Migration
  def self.up
    create_table :comments do |t|
      t.text "comment"
      t.integer "post_id"
      t.timestamps
    end
  end

  def self.down
    drop_table :comments
  end
end

Add the following to the spec helper file:
# spec/spec_helper.rb

module Spec
  module Mocks
    module Methods
      def stub_association!(association_name, methods_to_be_stubbed = {})
        mock_association = Spec::Mocks::Mock.new(association_name.to_s)
        methods_to_be_stubbed.each do |method, return_value|
          mock_association.stub!(method).and_return(return_value)
        end
        self.stub!(association_name).and_return(mock_association)
      end
    end
  end
end

And finally, the tests themselves:
# spec/controllers/comments_controller_spec.rb

require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe CommentsController, "handling GET /posts/1/comments" do

  before do
    @post = mock_model(Post, :to_param =&gt; "1")
    @post.stub_association!(:comments, :find =&gt; mock_model(Comment))
    Post.stub!(:find).and_return(@post)
  end

  def do_get
    get :index, :post_id =&gt; 1
  end

  it "should be successful" do
    do_get
    response.should be_success
  end

  it "should render index template" do
    do_get
    response.should render_template('index')
  end
end

Running the tests should give you an out similar to mine:
scriptrunner@scriptrunner-laptop:~/Projects/nestedresources$ rake spec
(in /home/scriptrunner/Projects/nestedresources)
......

Finished in 0.080328 seconds

6 examples, 0 failures

Comments [0]