Posts

Showing posts with the label rubyonrails

Teaching a One Day Intro to Rails 3 Class at University of Hawaii

Aloha! The University of Hawaii Pacific New Media Outreach College has just posted the details for my one day Intro to Ruby on Rails 3 course . It's a limited class size, so if you are interested, don't hesitate and sign up today! No computer necessary, as the facilities will provide all the computers, network, and software required to build and deploy a working Ruby on Rails application. This is an introductory course, designed for those students that are comfortable with their computers and willing to learn some very basic programming. However, students need not have any prior programming experience. My goal is to get your comfortable with the technology and to have a lot of fun. Therefore, we will be results focused and will ensure that you have a working application live on the internet before the end of the day! To get a head start, I recommend checking out: Also, I'll be teaching an HTML5 class for the fall semester. Stay tuned for more details on t...

Ruby on Rails and App Engine Performance Sample

Image
Statistics are always dangerous, and YMMV, but I wanted to post a set of performance tests I recently ran on a sample (and simple) Ruby on Rails application hosted on App Engine . These numbers are after the application has warmed up, and I've tried to make this test show results under the best real life circumstances. Ruby on Rails applications do have a higher than normal start-up time on App Engine, an issue acknowledged and currently worked on. After they are warmed up, however, users shouldn't experience a difference. The test was driven from the ab command, a simple benchmarking tool that comes with any Apache HTTPD software install. I ran the test from a Rackspace Cloud virtual machine. The Rails code for this test can be found on Github . Specifically, the controller and action being run in the test: class ContactsController Note: the database is empty for this test. Network latency between Rackspace Cloud and Google App Engine: sladd@slice84717:~...

Ext JS, Checkboxes, and Ruby on Rails

I am currently building a web application that makes heavy use of wizards and forms built with Ext JS . I am sending the form's values as JSON over to a Ruby on Rails server. Thanks to Rails 2.2.2, the JSON is automatically converted into an parameter hash. For a little background to the problem I am about to describe, HTML checkboxes are notoriously difficult to work with, because if the user does *not* check the box, then the browser will not send a value when the form is submitted. This makes it difficult to handle a state change from checked to unchecked. Rails makes this a bit easier because it will render both a hidden field with a value of "off" as well as the original checkbox. If the user checks the box, both values are sent but Rails will use the value from the checkbox (and not the hidden field). If the user does not check a box, only the hidden field's value is sent, which means the "off" value is sent. However, when using Ext JS to r...

Rails Builder Is Slow But Easy To Fix

For the impatient: Go install the fast_xs gem if you use Builder in Rails. The long story: I was using New Relic RPM to watch Errorlytics , and noticed everything was humming along just fine, except... the Atom feed of new 404 errors was taking an extremely long time. Request times of 800ms were not uncommon. RPM told me that the view rendering was taking most of the time, which made sense because I had already ensured that all the queries were by index. Errorlytics uses the Atom Builder to construct the Atom feed, and generally I like it. However, I had my doubts after learning it was the bottleneck, and I was hoping I wouldn't have to rip it out and write the XML by hand. After a bit of Googling around, I was lucky enough to run across Speed up your feed generation in Rails . This post details the same issue, in that the Builder had some major performance issues. Thankfully, the author of that post did all the hard work. They learned that installing the fast_xs gem is the ...

Errorlytics Captures and Fixes 404 Page Not Found Errors For Drupal, Wordpress, PHP, Rails, and Java

For the past several months, I've been working on Errorlytics, a Software as a Service that captures, analyzes, and helps you fix 404 Page Not Found errors for your Drupal, Wordpress, PHP, Rails, and Java web sites and applications. The original idea came from my friends and partners at Accession Media ( SEO and Internet Marketing experts ) and New Evolutions ( web application engineers ). Errorlytics is both a small plugin installed on your web site or application, and a hosted service which captures, processes, aggregates, and fixes 404 page not found errors. If you run a site with Drupal, Wordpress, straight PHP, Ruby on Rails, or Java, then Errorlytics can help you. After installing the open source (and small) plugin, you let the hosted service begin to capture the 404 page not found errors. You can then begin to handle those errors by telling Errorlytics where you want to redirect your visitors. The next time a visitor encounters a 404, they will be transparently redirecte...

Multi Model Forms With Rails

Ruby on Rails still doesn't have a good story to tell with regard to multi-model forms. Multi-model forms are HTML forms that have fields from more than one model, which the user edits and submits as one. Rails should take this single collection of fields, split it up into multiple models, and create, edit, or delete as necessary. Unfortunately, this still requires quite a bit of work. I've collected a set of links that may help those that are new handle multiple models in HTML forms with Rails. None of these are the "official" answer to this complex question. However, it appears that Rails core will one day have an out-of-the-box solution to this. Read on. Ryan Bates, of Railscasts fame, has probably the best known solution to this problem. He suggests Complex Forms Part 1 , Complex Forms Part 2 , and Complex Forms Part 3 . However, as even he mentions, it doesn't work with Rails 2. Refer to these screencasts, and their sometimes useful comments, as...

Lesser Known Rails 2.2 Features

With Ruby on Rails 2.2 released , no doubt you've seen the major feature overviews. But did you know there are lots of subtle improvements? Pathfinder Development has a nice summary at Rails 2.2 For Me And For You . My favorite new feature that I didn't know about: Also, partials now take blocks, meaning they can act somewhat like layouts. The partial itself can contain a yield: <table> <tr><td> <%= yield %> </td></tr> </table> Then the call to the partial can include a block: <% render :partial => "table_partial" do %> <%= @project.name %> <% end %> And the yield command invokes the block, as you would expect Awesome!

Rails Backwards Incompatible Change Coming to 2.3, Application is Now ApplicationController

Just a head's up to Ruby on Rails fans out there. DHH just checked in a very backwards incompatible change for the 2.3 branch. The root class for your controllers is now ApplicationController and not Application . I'm hoping this patch is reverted and instead rolled out for 3.0.

Displaying Deployment Date and Time and Git Revision Number in Rails Views

I had a need to display the deployment date and time (timestamp) and the current revision/version number in the footer of all our pages in our Rails application. Our users always were asking "Did you update the web site?" Thanks to capistrano , the deployment tool, this turned out to be fairly easy. Capistrano already collects the deployed version and places it into a file named REVISION in the deployment directory. The contents hold whatever is reported by your version control software. For git , this is a SHA1 hash. For the deployment timestamp, thankfully capistrano uses a timestamp for the deployment directory name. So we can just parse the path, looking for the timestamp. Below is the helper code, please let me know if there's a better way. [sourcecode language='ruby'] # pulls from the capistrano directory structure def deploy_timestamp if Rails.env.production? RAILS_ROOT.split('/').last else "Undeployed" e...

Easy Way to Configure Rails ActiveRecord and SQL Server on Mac OS X

Thanks to How to Connect To Microsoft SQL Server From Rails On OSX , I found out a very easy way to configure the database connection. Assuming you have FreeTDS installed (easily through macports ) and iODBC (comes out of the box with Mac OS X) then this is all you need in your database.yml file: development: adapter: sqlserver mode: odbc dsn: DRIVER=/opt/local/lib/libtdsodbc.so;TDS_Version=8.0;SERVER=10.0.6.20;DATABASE=awesome_development;Port=1433;uid=sa;pwd=password; No configuration of a DSN required, and no mucking about with freetds.conf! Now, if I could just use database.yml to get rid of SQL Server all together, I'd be a happy developer.

Issues with Active Scaffold and Rails 2.1, Solved

If you are looking to upgrade to Rails 2.1 and you are using Active Scaffold , be aware it still has a few rough edges. Make sure you install the Rails 2.1 branch of Active Scaffold: git clone git://github.com/activescaffold/active_scaffold cd active_scaffold git branch -r (just lists the branches) git checkout origin/rails-2.1 (Check out the full thread for Rails 2.1 and Active Scaffold compatibility ) Second, I had to patch vendor/plugins/active_scaffold/lib/extensions/generic_view_path.rb . On line 53, make it look like this: if !@template.controller.is_a?(ActionMailer::Base) && @template.controller.class.uses_active_scaffold? I had to add !@template.controller.is_a?(ActionMailer::Base) && All my tests are now passing! I still love Active Scaffold, even though it's a bit behind the times.

Nest Those Rails Resources Or Make Baby Semantic Web Cry

Proper web architecture dictates that a you should " Assign distinct URIs to distinct resources ." And Cool URIs for the Semantic Web states that: There should be no confusion between identifiers for Web documents and identifiers for other resources. URIs are meant to identify only one of them, so one URI can't stand for both a Web document and a real-world object. So we know that a URI should refer to one and only one resource. (Of course, you may have many URIs all referring to the same resource.) So why do so many web sites have URIs like http://www.example.org/myaccount ? That same URI is used to refer to any account in the system, depending on who is logged in. And that makes Baby Semantic Web cry. Why is the baby sobbing? A generic URI like http://www.example.com/myaccount isn't useful on the semantic web, because it's very difficult to make meaningful statements about that URI. Let's go and try. http://www.example.com/myaccount is the account ...

RSpec is Fun

I've been using RSpec with my latest project, and it's a welcome change from the traditional Test::Unit for Ruby . RSpec is a more natural way to write tests for your software. It seems to be much easier to compose tests, and anything that makes testing easier is OK in my book. A specific example of why I'm falling for RSpec: You can easily group common tests together, and include this grouping in your main tests. Of course you can do this in any number of ways with Test::Unit, but RSpec makes it so clean and obvious. Here's an example of a very common set of tests that I need to run again all my controllers: describe "Requires Authorization", :shared => true do describe "when not logged in" do describe "when accessing index page" do it "should redirect to login page" do get 'index' response.should redirect_to(new_session_path) end end describe "when accessing new datab...

Active Record, Parent-Child Relationships, and Validations

I've been reading through Advanced Rails Recipes , and so far I like the book. It has a nice collection of tips and tricks for the experienced Rails developer. This is the kind of book that you have to quickly scan through when you get it, so you know what tips are available. Remembering that the book has the solution for your problem at hand is the tough part. One common requirement for web frameworks is being able to handle nested forms on submit. It's too common to present to the user a complex form, representing many different, usually nested, objects. The difficulty isn't really in displaying or formatting the nested HTML form itself, but in handling the submit. How do you save or update all of the objects easily and efficiently? What if there's an error? The excellent and always useful RailsCasts had a series of episodes that handle the nested form issue ( Complex Forms 1 , Complex Forms 2 , and Complex Forms 3 ). There's a problem with their approach,...

How Not To Write An API

So a future version of Rails will get Pluggable Controller Caching . That's a good idea, and good on Rails for formalizing this extensibility. Better than monkey patching . Looking at the implementation, though, leaves me cold. Let's look at a code snippet: def read(name, options = nil) super @ether.get(name) end With some commentary: Invoking super for each method call ensures that the proper messages get logged for each action Wow, way to trust your users! </sarcasm> Requiring a call to super is very bad practice. Any time you are relying on a client of your class to call something, you're risking someone forgetting to make the call. It's better to use the Strategy Pattern . Here, you finalize the API method (here it is read ) and provide an abstract method or your subclasses. Marking the method as final (which I don't think you can do in Ruby, but I digress) ensures that a subclass can't override your functionality, and the abstract ...

SQL Server Adapter for Rails 2.0

UPDATE: Everything works now. Turns out I had a plugin installed that monkey patched the SQL Server Adapter. This plugin was from an older version of Rails, and the Rails 2.0 adapters now extend from AbstractAdapter. Fixing the parent class in my plugin monkey patch (to extend from AbstractAdapter) fixed this up and now I no longer get the error. I just installed the SQL Server Adapter Gem from gems.rubyonrails.org for my new Rails 2.0 project: gem install activerecord-sqlserver-adapter --source=http://gems.rubyonrails.org When I attempt to use it, I receive this error message: TypeError: superclass mismatch for class SQLServerAdapter from /var/lib/gems/1.8/gems/activerecord-sqlserver-adapter-1.0.0/lib/active_record/connection_adapters/sqlserver_adapter.rb:190 from /usr/lib/ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require' from /usr/lib/ruby/1.8/rubygems/custom_require.rb:27:in `require' from /home/sladd/development/workspace/...

Rails Bug With Has Many Collections Empty? and Build

After my long rant about problems in Ruby on Rails has_many collections and empty? calls , we spent some more time and really condensed the problem. I can explain this problem much more clearly now. Let's take the following code: f = Foo.new f.bars.build f.bars.empty? pp f.bars What do you think will be printed out when we pp f.bars ? Well, if you're like me, you'd think it would return an array with one Bar in it. And, if you were like me, you'd be wrong. Turns out that the call to f.bars.empty? doesn't realize you've ever added a new Bar to the collection of bars. Therefore, it will go into the database and do a select count(*) to determine the size of the collection. It will return zero, because at this point you haven't saved anything into the database. Not only is going to the database to determine the size of the collection wrong (in the line above, I've added a Bar though build so empty? should know there's at least one), but empty? ...

When Empty Isn’t Empty With Rails Active Record Collections

So I'm writing some Rails code, just playing around, and I run into a very strange situation. I've found a situation where Rails' Active Record code is calculating the results to empty? incorrectly, even if I add elements to the collection . So I had a has_many collection with elements inside of it, but calls to length or empty were returning 0 and true . Here's my simple models: class Query < ActiveRecord::Base has_many :measures validates_presence_of :cube_name def measure_attributes=(attrs) attrs.each {|a| measures.build(a)} end end and class Measure :query has_one :condition, :as => :conditionable end Notice that in Query, I've added a measure_attributes method which automatically handles the construction of new Measure instances from the form parameters. Here's the simple nested form. From the models, a Query has many Measures: <% form_for :query, :url => {:action => :new} do |f| %> Cube Name: <%= f.text_field :...

QOTD

7 reasons I switched back to PHP after 2 years on Rails PROGRAMMING LANGUAGES ARE LIKE GIRLFRIENDS: THE NEW ONE IS BETTER BECAUSE *YOU* ARE BETTER

Rails and Nested Singular Resources

One of the reasons I love Rails is the built in support for REST. If you're not yet writing your Rails applications RESTfully, then you're not really writing web applications. I'll detail an example that I just created which I thought illustrated REST support quite nicely. In Rails, you can model singular or plural Resources. A plural Resource might be Users, which means you'll have lots of Users in your system. In contrast, you can create singular Resources when there is only one instance of that Resource in the system. A good example of a singular resource is an User's avatar icon. For instance, most Web 2.0 applications let you upload a tiny picture that represents you. In Rails speak, we say a User has one Avatar Icon. An Avatar Icon belongs to a User. When creating the URI space for these models (User, AvatarIcon) you use map.resources and map.resource inside of your routes.rb file. We want to enforce that an AvatarIcon belongs to an User in the U...