Silverlight (and Ruby on the .NET CLR)

Posted by Bhushan Ahire | Posted in Rails | Posted on 23-08-2007

0

Silverlight

At MIX07 a few days ago, Microsoft announced “Silverlight“, a new Flash-esque .NET-based platform for delivering “media experiences” and “rich interactive applications” on the Web. It’s interesting, and some people seem to think it’s going to revolutionize the Web, but that’s not why we’re interested in it at Ruby Inside.

The most interesting part of the Silverlight announcement is that it’s based on a subset of the CLR (Common Language Runtime) from Microsoft’s .NET platform. The .NET CLR has become a common target for programming language runtimes recently, but Microsoft has officially announced C#, Javascript, VB, Python and Ruby support for Silverlight’s CLR. Microsoft are also adding new features in a system called the DLR (Dynamic Language Runtime) to bring more dynamic features (as required by Python and Ruby) to the CLR. InfoQ has more information on this, in terms of Ruby.

What all of this means is that there’s baked-in support for Ruby in what could be one of the biggest runtime environments on the Web in the next few years, and this can only be a good thing for Ruby. Jon Udell sat down with John Lam (the creator of RubyCLR) and talked about the DLR, Ruby, and how the whole caboodle works / will work.

Let’s cross our fingers and hope this isn’t ActiveX all over again.

relative_time_helpers Plugin: time_ago_in_words on Steroids

Posted by Bhushan Ahire | Posted in Rails | Posted on 23-08-2007

0

From Basecamp's screenshot

relative_time_helpers is a straightforward, but very useful Rails plugin by Rick Olson that formats timestamps to human-friendly relative dates. You’re probably already using Rails’ built-in time_ago_in_words helper in your applications, but Rick’s relative_time gives even better results:

<%= relative_time(Time.now) %># today<%= relative_time(1.day.ago) %># yesterday<%= relative_time(1.day.from_now) %># tomorrow<%= relative_time_span([Time.now, 5.days.from_now]) %># May 17th - 22nd

To install it:

script/plugin install http://ar-code.svn.engineyard.com/plugins/relative_time_helpers

Calendar Date Select: A Lightweight, Prototype-based Date/Time Picker for Rails Developers

Posted by Bhushan Ahire | Posted in Rails | Posted on 23-08-2007

0

Calendardateselect

Calendar Date Select is a new(ish) “date and time picker”, developed by Tim Harper, designed primarily for developers to use in Rails applications. It uses the standard Prototype JavaScript library, and is easily installed as a Rails plugin:

script/plugin install http://calendardateselect.googlecode.com/svn/tags/calendar_date_select

Take a look at the collection of demos of the picker to see its full range.

Rails performance tip – using YSlow

Posted by Bhushan Ahire | Posted in Rails | Posted on 23-08-2007

0

YSlow from Yahoo! is a Firefox add-on to analyse web pages and tell you why they’re slow based on rules for high performance web sites. YSlow requires the indispensable Firebug extension.

The 13 rules YSlow checks your site against are as follows:

1. Make Fewer HTTP Requests2. Use a Content Delivery Network3. Add an Expires Header4. Gzip Components5. Put CSS at the Top6. Move Scripts to the Bottom7. Avoid CSS Expressions8. Make JavaScript and CSS External9. Reduce DNS Lookups10. Minify JavaScript11. Avoid Redirects12. Remove Duplicate Scripts13. Configure ETags

This post will demonstrate that most of these are easily achievable for a Rails website through a combination of plugins and with correct configuration of a proxy web server (in front of a mongrel cluster) – in this case Nginx. This guide follows experience with improving performance for trawlr.com (an online RSS reader).

Make Fewer HTTP Requests, Minify JavaScript, Put CSS at the Top, Move Scripts to the Bottom, Remove Duplicate Scripts

The easiest way to make fewer HTTP requests is to combine all JavaScript and CSS files into one. The asset packager plugin does exactly this, plus it will also compress the source files (in production mode) and correctly handles caching (without query string parameters).

Moving CSS to the top (within the head section) and moving JavaScript to the bottom of the page are both manual tasks that should be done in the layout templates (such as app/views/layouts/application.rhtml). Remember to use stylesheet_link_merged :base and javascript_include_merged :base rather than the default Rails helpers.

By using asset packager you can also verify that scripts are only included once – another performance hit otherwise!

Excluding the Google analytics JavaScript file, trawlr.com now uses a single css and js file (including the entire prototype library). Note: You may need to add a missing semi-colon as per this defect for prototype to work correctly.

Asset Packager can be included as part of a Capistrano deployment with the following recipe:

desc "Compress JavaScript and CSS files using asset_packager" task :after_update_code, :roles => [:web] do  run <<-EOF    cd #{release_path} &&    rake RAILS_ENV=production asset:packager:build_all  EOFend

Use a Content Delivery Network

Ignoring this point for now; I’d suggest the use of Amazon S3 as a useful starting point for simple CDN.

Add an Expires Header

A first-time visitor to your page may have to make several HTTP requests, but by using the Expires header you make those components cacheable. This avoids unnecessary HTTP requests on subsequent page views. Expires headers are most often used with images, but they should be used on all components including scripts, stylesheets, and Flash components.

Nginx allows adding arbitrary HTTP headers via the expire and add_header directives. Adding the expires header to static content is done with a regular expression looking for relevant file extensions in the request URL. This example uses the maximum expiry date but could be set to more appropriate values as required (e.g. 24h, 7d, 1M)

# Add expires header for static contentlocation ~* .(js|css|jpg|jpeg|gif|png)$ {  if (-f $request_filename) {        expires      max;    break;   }        }

Gzip Components

Nginx can gzip any responses – including those proxied from a mongrel cluster.

gzip on;gzip_min_length  1100;gzip_buffers     4 8k;gzip_proxied any;              gzip_types  text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;

Avoid CSS Expressions

Just don’t do it!

Make JavaScript and CSS External

Add you JavaScript and CSS styles in external files rather than inline. The added benefit here is that the content will be merged and compressed thanks to the work already done above.

Reduce DNS Lookups, Avoid Redirects, Configure ETags

These weren’t an issue for me so I suggest the Yahoo! guidance for further information

Reduce DNS Lookups

Avoid Redirects

Configure ETags

How to Profile Your Rails Application and Make Rails Go Vroom!

Posted by Bhushan Ahire | Posted in Rails | Posted on 23-08-2007

0

Call Graph-1

Charlie Savage, author of ruby-prof, recently baked in support for Rails to ruby-prof, so now it’s possible to profile your Rails application, see where the delays are, and work on improving performance.

Hot on the heels of this development, Charlie wrote “How to Profile Your Application“, an article that does just what it says on the tin, and which demonstrates how to profile the CPU time used on a single Rails request, and visualize the call tree.

This was quickly followed up with “Making Rails Go Vroom“, another great article that looks at what parts of Rails significantly slow things down. Charlie comes up with six key suggestions:

  • Don’t use ActiveRecord#attributes or ActiveRecord#read_attribute
  • Get your :includes right
  • Don’t check template timestamps ( cache_template_loading = true)
  • Don’t use url_for
  • Don’t let Rails parse timestamps
  • Don’t symbolize keys (local_assigns_support_string_keys = false)

Learn more and see how Charlie came to his conclusions in the article.

10 Great New Ruby / Rails Screencasts from July 2007

Posted by Bhushan Ahire | Posted in Rails | Posted on 23-08-2007

0

Randscrcast-1

Railscasts, maintained by Ryan Bates, continues to release one great free screencast after another, with 9 so far this month, although we’re going to include one from June 29 for good measure. We first looked at Railscasts a few months ago, so if you haven’t visited again since, it’s worth it. Here are the latest screencasts:

  • Testing Without Fixtures – Fed up with using fixtures for your tests? Find a better way.
  • will_paginate – A look at the “new way” to do pagination in Rails using the will_paginate plugin.
  • Updating Through Checkboxes – How to perform actions on multiple items selected with checkboxes in a Rails view.
  • Handling Exceptions – Learn about exceptions and how to handle them in Rails apps.
  • The Logger – No, it’s not about felling trees. Learn how to send messages to the log and how to customize it.
  • How to Make a Generator – A look at building your own generator, much like the ones that come with Rails.
  • Optimistic Locking – How to resolve situations when two people want to update the same record at the same time.

At the same time, Geoffrey Grosenbach, curator of PeepCode (and a new sponsor of Ruby Inside), has been storming ahead with his own set of screencasts, a few of which will be of direct interest to Rubyists / Rails developers:

  • rSpec Basics – A look at Behavior Driven Development. An ideal starting point if you haven’t touched BDD yet but have been intrigued.
  • Rails From Scratch: Part I – A great up-to-date introductory “course” for getting into Rails. Even includes a free 20 page reference guide to Ruby and Rails, and an introduction to Ruby syntax. It’s everything a new Rails developer needs.
  • Rails From Scratch: Part II – Another 80 minutes of great introductory material for new Rails developers.

While Railscasts’ screencasts are totally free, Peepcode screencasts cost $9 each, but for the great packaging, length, and total depth of the material covered, they’re still bargains!

How To Scrape Google With Ruby In 0 Seconds

Posted by Bhushan Ahire | Posted in Rails | Posted on 23-08-2007

0

Scrubytgoogle

Okay, his title is a bit misleading, but Peter Szinek, developer of Ruby scraping toolkit scRUBYt!, has put together a great article showing the process, from start to finish, of scraping Google results using Ruby “in no seconds”. In reality, it’ll take you at least sixty to read the post.

How to send SMTP mail in Ruby using ActionMailer (outside Rails)

Posted by Bhushan Ahire | Posted in Rails | Posted on 09-08-2007

0

Like most bits of Rails, ActionMailer has an elegant and coder friendly interface. With a bit of set up, it’s remarkably quick and easy to get running from vanilla Ruby outside of Rails.

Recently I’ve needed to bulk email a bunch of files to an internal server for testing purposes. I’ve used ActionMailer inside Rails in the past, and wondered how hard it would actually be to get it up and running standalone. Sure, there are a stack of other mail gems and libraries in Ruby to do this, but they expose a lot of the internals of STMP and can be a pain to use. Definitely overkill when all you want to do is quickly fire off some mails from a script. (ActionMailer is actually built on top of a lot of those libraries, and acts like a coder friendly wrapper).

My requirements were pretty simple: Iterate over a bunch of files, and attach each one to a separate email and send to some address.

Here’s what the code looks like for the ActionMailer class:

require 'action_mailer'

ActionMailer::Base.smtp_settings ={:address => 'smtp.example.com',

:domain  => 'example.com'}

class FileMailer < ActionMailer::Base

 def file(to, sender, file_name, content_type, strip_ext = true)

   # strip any directory fluff    subj = file_name.gsub(/.*//,'')

   #remove the file extension if required   subj = subj.gsub(/.w*/,'') if strip_ext

   #standard ActionMailer message setup   recipients  to   from        sender   subject     subj

   #setting the body explicitly means we don't have to provide a separate template file   body        ''

   #set up the attachment   attachment  :content_type => content_type,

               :body         => File.read(file_name),               :filename     => file_name.gsub(/.*//,'')

 endend

The only thing different from Rails, is that you need to explicitly configure the SMTP details via ActionMailer::Base#smtp_settings.

It’s worth noting that you don’t actually need to create a .rhtml view file if you specify the body attribute of your message. I ran into a few blogs claiming there was no way to turn off the .rhtml requirement – a quick inspection of the ActionMailer source code proves otherwise. I’m sure it violates good MVC design, but if you’re just throwing together a quick script, who cares. I’ve left the body in the example as an empty string (the server at the other end was only interested in the attachement), but you can specify whatever string you want there.

To use the mailer class, you just call it in the normal Rails ActionMailer manner. With ActionMailer you don’t call the mail action method you implemented, but a generated method prefixed with deliver_. So in our example, even though we implemented a method file, we actually call deliver_file (passing it the same parameters).

FileMailer.deliver_file('recipient@example.com','julian@example.com','my_file.csv','text/csv')

How To pass Ruby Object to JavaScript function

Posted by Bhushan Ahire | Posted in Rails | Posted on 01-08-2007

0

If you want to pass ruby object to javascript function then do the followin steps…

In Ruby Controller Action…
def sample
ruby_variable = “Something”
ruby_variable.to_json
end

In Ruby RJS File

page.call ‘java_script_function_name’, ruby_variable

In JavaScript
function java_script_function_name(java_script_variable){
alert(java_script_variable);
}

java_script_variable comes in the form of array of javascript.
Add comments if anyone wants